Full Code of jeffWelling/ticgit for AI

master b9b1db477d26 cached
47 files
183.5 KB
48.2k tokens
189 symbols
1 requests
Download .txt
Repository: jeffWelling/ticgit
Branch: master
Commit: b9b1db477d26
Files: 47
Total size: 183.5 KB

Directory structure:
gitextract_jah_79j_/

├── .gitignore
├── .rvmrc
├── LICENSE_GPL
├── LICENSE_MIT
├── README.mkd
├── Rakefile
├── bin/
│   ├── ti
│   └── ticgitweb
├── development.mkd
├── examples/
│   └── post-commit
├── lib/
│   ├── ticgit-ng/
│   │   ├── attachment.rb
│   │   ├── base.rb
│   │   ├── cli.rb
│   │   ├── command/
│   │   │   ├── assign.rb
│   │   │   ├── attach.rb
│   │   │   ├── checkout.rb
│   │   │   ├── comment.rb
│   │   │   ├── help.rb
│   │   │   ├── init.rb
│   │   │   ├── list.rb
│   │   │   ├── milestone.rb
│   │   │   ├── new.rb
│   │   │   ├── points.rb
│   │   │   ├── recent.rb
│   │   │   ├── show.rb
│   │   │   ├── state.rb
│   │   │   ├── sync.rb
│   │   │   └── tag.rb
│   │   ├── command.rb
│   │   ├── comment.rb
│   │   ├── ticket.rb
│   │   └── version.rb
│   └── ticgit-ng.rb
├── note/
│   ├── IMPLEMENT
│   ├── NOTES
│   ├── OUTPUT
│   └── TODO
├── spec/
│   ├── attachments_spec.rb
│   ├── base_spec.rb
│   ├── base_ticket_revparse_spec.rb
│   ├── cache_spec.rb
│   ├── cli_spec.rb
│   ├── merging_spec.rb
│   ├── scalability_spec.rb
│   ├── spec_helper.rb
│   └── ticgit_spec.rb
└── ticgit-ng.gemspec

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
*.gem
*.swp
rdoc/
pkg/


================================================
FILE: .rvmrc
================================================
rvm use --create default@ticgit


================================================
FILE: LICENSE_GPL
================================================
This license applies ONLY to code authored by Jeff Welling. All
other code contributions until now have been under the MIT license.
To see the MIT license, see the LICENSE_MIT file.
For information on how to find out which code was authored by whom,
see http://www.kernel.org/pub/software/scm/git/docs/git-blame.html


                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: LICENSE_MIT
================================================
The MIT License

Portions, Copyright (c) 2008 Scott Chacon
Other portions, Copyright (c) 2011 Jeff Welling
Other portions, Copyright of their respective authors.

This MIT license and notice pertains ONLY to code NOT authored by Jeff Welling. 
Contributions by Jeff Welling are licensed under GPLv3, a copy of 
which is included with the source code.  For information on determining 
which code was authored by whom, see 
http://www.kernel.org/pub/software/scm/git/docs/git-blame.html

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


================================================
FILE: README.mkd
================================================
## TicGit-ng ##

This project provides a ticketing system built on Git that is kept in a
separate branch in your projects Git repository. Originally called TicGit,
it is now known as TicGit-ng to continue development and avoid namespace
clashes.

### About ###

TicGit-ng is a simple ticketing system, roughly similar to the Lighthouse model, that is based in git. It provides a command line client that uses the ‘git’ gem to keep its ticketing information in a separate branch (called ‘ticgit-ng’) within your existing git repository. All the data is file based and rarely changing, decreasing the likelihood of a merge issue. Right now, ticket branch merges need to be done manually and separately, but work is being done on a `ti sync` command to make this easier and more intuitive.

The idea is that it keeps your tickets in the same repository, but without mucking up your working tree. By using its own seperate branch to store its information it keeps the working trees in all your other branches untouched.

There are two interfaces available, the command line `ti` command and the `ticgitweb` web interface, though `ticgitweb` has many more prerequisites than `ti`.

It will automatically create the new branch the first time you use it, and it caches all the data (another working directory and index file) in your ~/.ticgit-ng directory by default. If you delete that directory, it will just create it again the next time, you will lose no data (except some of your saved preferences).

TicGit-ng is currently using itself to store its feature requests and bug reports.

### Prerequisites ###

There are two sets of prerequisites, those for people who intend to just run `ti`, and another set for those who wish to run `ticgitweb` as well. `ticgitweb` has additional dependancies that aren't required for `ti`'s use.

**ti**

Required Packages: git, ruby, rubygems

Required Ruby Gems: git

To install these packages on a Debian system, or a Debian based system like Ubuntu, do

    sudo aptitude install git ruby rubygems
    sudo gem install git

**ticgitweb**

Required Packages: git, ruby, rubygems

Required Ruby Gems: git, sinatra, haml, sass

To install these packages on a Debian system, or a Debian based system like Ubuntu, do

    sudo aptitude install git ruby rubygems
    sudo gem install git sinatra haml sass




**A Note about rubygems**

While the version of rubygems available from the repositories on Debian 5.0.5 stable will work just fine for using the command line `ti` program, using `ticgitweb` requires some extra effort.
Older versions of rubygems, such as the one available on Debian 5.0.5, will not work out of the box with the new gem repositories because the .deb in stable relies on rubyforge rather than rubygems for its operations. See [this bug](http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=558251) for an example. If you are running an older version of rubygems, you may need to get the latest rubygems package from http://rubygems.org/ or [apt](http://jaqque.sbih.org/kplug/apt-pinning.html) [pinning](http://jeffwelling.github.com//2010/09/05/Apt-Pinning.html) before being able to properly install the git and ticgit gems.

**A Note About The Git Gem**

The git gem requires a git version of 1.6.0.0 or later, but on Debian stable, git-core is currently (Sept 6th 2010) at 1.5.6.5.  This isn't a fatal problem and we can continue using version 1.5.6.5 with the git gem, but you will see notices like this if you do

    [WARNING] The git gem requires git 1.6.0.0 or later, but only found 1.5.6.5. You should probably upgrade.
    Please specify at least one action to execute.

If these annoy you as they do me and you've set up [apt](http://jaqque.sbih.org/kplug/apt-pinning.html) [pinning](http://jeffwelling.github.com//2010/09/05/Apt-Pinning.html), you can do

    $ sudo aptitude -t testing install git-core

And those notices should go away.

**A Note About Coloured Git Output**

If you use `[color] ui = always` instead of `[color] ui = true` then you will encounter a problem with the deprecated git gem parsing the color codes. Because it doesn't strip the color codes before parsing the output, it chokes and makes everything explode. 

Since time spent working on monkeypatching the git gem would soon be rendered fruitless by the eventual planned upgrade away from it, for the time being the suggested solution is to use `[color] ui = true`. 

### Installing ##
Installation on a Debian stable system.  Note that the command line interface for TicGit-ng can be run from Debian stable, but some of the gems required for the web interface may require you to use [apt](http://jaqque.sbih.org/kplug/apt-pinning.html) [pinning](http://jeffwelling.github.com//2010/09/05/Apt-Pinning.html) to run without errors.  See below

To install TicGit-ng on your system, you can go one of two ways,

    $ gem install TicGit-ng

or, you can install it from source by downloading this repository building your own gem (see below).

### Usage ###

To get a list of all commands with short description:

    > ti --help
    Usage: ti COMMAND [FLAGS] [ARGS]
     
    Options for help command:
     
    The available TicGit-ng commands are:
        recent                           List recent activities
        checkout                         Checkout a ticket
        tag                              Modify tags of a ticket
        comment                          Comment on a ticket
        milestone                        List and modify milestones
        assign                           Assings a ticket to someone
        points                           Assign points to a ticket
        state                            Change state of a ticket
        show                             Show a ticket
        new                              Create a new ticket
        attach                           Attach file to ticket
        list                             List tickets
     
    Common options:
        -v, --version                    Show the version number
        -h, --help                       Display this help
    "help" is not a command


To get help about a specific command:

    > ti <command> --help
    ## for example
    > ti assign --help
    Usage: ti assign [options] [ticket_id]
     
    Options for assign command:
        -c, --checkout TICKET            Checkout this ticket
        -u, --user USER                  Assign the ticket to this user
     
    Common options:
        -v, --version                    Show the version number
        -h, --help                       Display this help


The available commands are:

    ti list     - show all tickets
    ti show     - show details of a specific ticket
    ti new      - create a new ticket
    ti checkout - checkout a ticket
    ti state    - change a ticket state (open, resolved, invalid, hold)
    ti comment  - add a comment to a ticket
    ti tag      - add or delete a tag from a ticket
    ti assign   - change to whom a ticket is assigned


### Usage Examples ###

The first time you use any command in Ticgit-ng, it will create a new branch in your repo called ‘ticgit-ng’ and setup a caching area in ~/.ticgit-ng.

If you run it without arguments, it will tell you what is available to run

    $ ti
    Please specify at least one action to execute.

    Usage: ti COMMAND [FLAGS] [ARGS]
     
    The available TicGit-ng commands are:
        recent                           List recent activities
        checkout                         Checkout a ticket
        tag                              Modify tags of a ticket
        comment                          Comment on a ticket
        milestone                        List and modify milestones
        assign                           Assings a ticket to someone
        points                           Assign points to a ticket
        state                            Change state of a ticket
        show                             Show a ticket
        new                              Create a new ticket
        attach                           Attach file to ticket
        list                             List tickets
     
    Common options:
        -v, --version                    Show the version number
        -h, --help                       Display this help

The first time you run `ti list`, it will show an empty list.

    $ ti list
    I, [2010-09-06T15:47:52.075485 #4820]  INFO -- : creating ticgit repo branch

       TicId  Title                             State Date  Assgn    Tags                
    -----------------------------------------------------------------------------------------

To add a new ticket you can use `ti new -t 'Title of ticket'` and give it a title in one command line.

    $ ti new -t 'my new ticket'
    $ ti list

       TicId  Title                             State Date  Assgn    Tags                
    -----------------------------------------------------------------------------------------
       d7f2d8 my new ticket                     open  09/06 

For the ‘comment’ and ‘new’ commands, if you don’t specify a ‘-m’ for the message, it puts you into $EDITOR  to write it. The ‘new’ action is especially useful with this, because you can also tag it and give it an initial comment when you create it this way:

    
    # ---
    # tags:
    # # first line will be the title of the tic, the rest will be the first comment
    # # if you would like to add initial tags, put them on the 'tags:' line, comma delim
    #

To edit a ticket, such as assigning a tag to the new ticket we created, we first checkout the ticket and then use `ti tag`.
Always checkout the ticket you intend to edit.  Some commands allow you to include a tic_id argument but that can get confusing to keep track of and most of the time several edits will be done to the same ticket anyway, so it is suggested you use `ti checkout` for convenience if nothing else.

    #ti checkout can checkout tickets based on the TicId or based on it's place in the list
    $ ti checkout 1
    #checks out the first ticket, or to do the same thing by using the TicId
    $ ti checkout d7f2d8
    #then assign the tag
    $ ti tag 'bug'
    #and view the result..
    $ ti list

       TicId  Title                                           State Date  Assgn    Tags                
    -------------------------------------------------------------------------------------------------------
    *  d7f2d8 my new ticket                                   open  09/06          bug               


To assign the ticket to someone, use the `ti assign` command.  I assign the ticket to myself below.

    $ ti assign -u 'jeff.welling@gmail.com'
    $ ti list

       TicId  Title                                              State Date  Assgn    Tags                
    ----------------------------------------------------------------------------------------------------------
    *  d7f2d8 my new ticket                                      open  09/06 jeff.we… bug  


To change the state of a ticket, such as to change it from 'open' to 'hold' or 'resolved', use `ti state`. There are 4 valid states: hold, invalid, open, and resolved.

    $ ti state hold
    $ ti list

       TicId  Title                                              State Date  Assgn    Tags                
    ----------------------------------------------------------------------------------------------------------

*Dramatic Gasp!*
Where did all of our tickets go?  Don't worry, this isn't a bug and your tickets aren't gone.  

    $ ti list --states open,hold

       TicId  Title                                              State Date  Assgn    Tags                
    ----------------------------------------------------------------------------------------------------------
    *  d7f2d8 my new ticket                                      hold  09/06 jeff.we… bug                 

By default `ti list` doesn't show tickets with a state of 'hold', so we have to specify that we want to see those tickets with an argument.  Now you can see, out `ti state hold` command changed the state of that ticket to on hold. This can also be done without checking out the ticket by using `ti state 1 hold`.

Where ticgit expects a ticket id, it will take either the number of the ticket on the last ‘list’ you did, or it will take the partial sha each ticket is assigned when it is created – that number never changes for the life of the ticket, even across repositories, so you can email that number to someone else working on the project so they can identify it. If nothing is specified, it will use the currently checked out ticket.

    $ ti comment -m "I'm a new comment"
    $ ti show
    Title: my new ticket
    TicId: d7f2d8f6d6ec3da1a1800a33fb090d590a533bac

    Assigned: jeff.welling@gmail.com
    Opened: Mon Sep 06 15:52:03 -0700 2010 (0 days)
    State: OPEN
    Points: no estimate
    Tags: bug

    Comments (1):
      * Added 09/06 18:34 by jeff.welling@gmail.com
      I'm a new comment

`ti show` also has a '-f' argument to be able to see comments that are longer than 3 lines, which would normally be truncated.

The `ti list` command can also be sorted and filtered.

    $ ti list --help
    Usage: ti list [options]
     
    Options for list command:
        -l, --list                       Show the saved queries
        -S, --saveas SAVENAME            Save this list as a saved name
        -a, --assigned ASSIGNED          List only tickets assigned to someone
        -s, --states STATE[,STATE]       List only tickets in a specific state(s)
                                         Prefix the state with '-' to negate
        -t, --tags TAG[,TAG]             List only tickets with specific tag(s)
                                         Prefix the tag with '-' to negate
        -o, --order ORDER                Field to order by - one of : assigned,state,date,title
     
    Common options:
        -v, --version                    Show the version number
        -h, --help                       Display this help

So if you wanted to see a list of all your tickets that have the ‘feature’ tag, assigned to ‘jeff.welling@gmail.com’ and are ‘open’, ordered by date opened descending, and save that view as ‘not_mine’, you can run this:

    $ ti list -t feature -s open -a jeff.welling@gmail.com -o date.desc -S not_mine

Then if you want to later list tickets with the same options as you used above, use

    $ ti list not_mine

## Collaboration ##

If you have cloned a repository and would like to get the ticgit-ng branch for that repo (presuming they have one), do this.

    $git branch ticgit-ng origin/ticgit-ng

This will create a ticgit-ng branch in your local repo based on the ticgit-ng branch in origin.  Now you can run `ti list` and it will show you the ticgit-ng tickets for that repository.

### Getting the TicGit-ng ticgit-ng branch ##

To download your own copy of the TicGit-ng ticgit branch after cloning the repo, so that you can add or alter a bug yourself, follow these instructions.

This will checkout a ticgit-ng branch and set it to track the ticgit-ng branch upstream in origin, and then checks out the master branch.  You must checkout the master branch because TicGit-ng gets confused if you are already in the ticgit-ng branch when running TicGit-ng.

    $ git checkout origin/ticgit-ng
    $ git checkout -b ticgit-ng
    $ git checkout master

This will show you all of the bugs in TicGit-ng's ticgit-ng branch.

    $ ti list

To submit your changes back to the upstream maintainer, push the bugs in your ticgit-ng branch to your public repo on Github
    
    $ git push origin ticgit-ng

Then contact the upstream maintainer by sending a Pull Request or Email and ask them to review and accept your bug changes.

### Sharing your tickets with others ###

Sharing your ticgit tickets with other people is as easy as asking them either creating their ticgit-ng branch based on yours if they haven't already started their own ticgit-ng branch, or pulling your ticgit-ng branch into theirs.

If you host your repositories on [Github](http://www.github.com) as I do then this process is simplified some because you don't have to worry about hosting your repository somewhere where other people can access it to pull your ticgit-ng branch.

For example, when I want my friend wnight to have the changes I made to my tickets in my ticgit-ng repository, I do a

    $ git push origin

to update all my remote branches with my current ones, and then I ask him to do a

    $ git checkout ticgit-ng
    $ git pull git@github.com:jeffWelling/ticgit.git ticgit-ng
    $ git checkout master

to pull my changes into his ticgit-ng branch and then switch back to his master branch.  Now when he does `ti list` it will show the changes I made to the tickets on my system.


### Incorporating other peoples changes into your ticgit-ng branch ###

The process is much the same as above, except the rolls are reversed.  Once you know they have published their changes and you have a URL to do a git pull from, you simply do

    $ git checkout ticgit-ng
    $ git pull SOURCE_URL ticgit-ng
    $ git checkout master

Replacing SOURCE_URL with the URL you were told to pull from, now you can see the changes they made, in your ticgit-ng branch.  You can easily publish these changes with a `git push origin` so anyone following your work can also see these changes.


### Next generation collaboration ###

Changes made by [Bruno Santos](http://github.com/pheres) to add a [`ti sync`](http://github.com/jeffWelling/ticgit/commit/7388386fab4fb12c36e6eeb7d19eaa4e4b16b853) command were integrated on February 15th 2011.  You can now use the `ti sync [options]` command to sync your tickets with anyone else you've added with `git remote add`.  To use `ti sync`, all you need to do is first make sure you've already added the remote source with `git remote add`, and then do

    $ ti sync --repo REMOTE_SOURCE

if you want to pull their tickets into your ticgit-ng branch *and* push your tickets to their ticgit-ng branch, or

    $ ti sync --repo REMOTE_SOURCE --no-push

if you want to pull their tickets into your ticgit-ng branch without pushing your tickets to their branch.

More information on using ti sync can be gleemed from reviewing the [merge specs](https://github.com/jeffWelling/ticgit/blob/deving/spec/merging_spec.rb)

### Ticgitweb ###

To run the Sinatra enabled web UI for your TicGit-ng repo, simply cd to your repository and run 'ticgitweb', or 'ticgitweb -p 3456' to change the port to something other than '4567', which is the Sinatra default.

Here is what the Ticket listing looks like:

<a href="http://www.flickr.com/photos/chacon/2359042481/" title="TicGitWeb Ticket List by schacon, on Flickr"><img src="http://farm4.static.flickr.com/3289/2359042481_065867a92e.jpg" width="500" height="258" alt="TicGitWeb Ticket List" /></a>

And here is an individual ticket:

<a href="http://www.flickr.com/photos/chacon/2359042513/" title="TicGitWeb Ticket by schacon, on Flickr"><img src="http://farm4.static.flickr.com/3240/2359042513_6d4bd069d0.jpg" width="500" height="275" alt="TicGitWeb Ticket" /></a>


## Development ##

The original author had used rspec to write specs for ticgit-ng, but one of the maintainers since then switched it over to bacon[[1](http://www.ruby-forum.com/topic/137928)][[2](http://www.ruby-forum.com/topic/172139)][[3](http://testanything.org/wiki/index.php/Testing_with_Ruby)] and I haven't been too inclined to switch it back.

### Prerequisites ###

To install the prerequisites on Debian stable for testing ticgit-ng, you will need [apt](http://jaqque.sbih.org/kplug/apt-pinning.html) [pinning](http://jeffwelling.github.com//2010/09/05/Apt-Pinning.html).

    $ sudo aptitude -t testing install rubygems rake
    $ sudo gem install yard bacon

I pull rubygems from testing to avoid a problem with gherkin creating a syntactically incorrect gemspec which makes a lot of noise whenever `gem` is called. I ran into a problem when gem was installing yard, it had a problem with the documentation but thankfully the error wasn't fatal and was only about not being able to compile the documentation which I don't use, so it continued without trouble.


### How To Test ###

To test your version of ticgit-ng, go to your ticgit-ng directory and run

    rspec spec/*_spec.rb

### How to generate a gem from your development copy of ticgit-ng ###

To create a gem from your development copy of ticgit-ng, go to your ticgit-ng directory and do

    rake gem

This will create a pkg/ directory, which will contain a newly created ticgit-ng gem for you to install.

More information on developing TicGit-ng and collaborating with other TicGit-ng developers at [here](https://github.com/jeffWelling/ticgit/wiki/Development)

More information on developing TicGit-ng and collaborating with other TicGit-ng developers at [here](https://github.com/jeffWelling/ticgit/wiki/Development)

### Alternatives ###

ditz 
bugs everywhere
git-issues


## Authors ##

Original Author:
Scott Chacon                (schacon@gmail.com)

Current Active Maintainer:
Jeff Welling                (jeff.welling@gmail.com)

For a detailed list of contributors, use `git log`.


================================================
FILE: Rakefile
================================================
require 'rubygems'
require 'rake'
require 'rake/clean'
require 'rake/rdoctask'
require 'rspec/core/rake_task'

CLEAN.include('**/*.gem')

desc "Creates the TicGit-ng gem"
task :create_gem => [:clean] do
  spec = eval(IO.read('ticgit-ng.gemspec'))
  gem = Gem::Builder.new(spec).build
  Dir.mkdir("pkg") unless Dir.exists? "pkg"
  FileUtils.mv("#{File.dirname(__FILE__)}/#{gem}", "pkg")
end

desc "Runs spec suite"
RSpec::Core::RakeTask.new(:spec) do |spec|
  spec.pattern = 'spec/*_spec.rb'
  spec.rspec_opts = ['--backtrace --colour']
end

desc "Creates rdoc documentation"
Rake::RDocTask.new do |rdoc|
  version = File.exist?('VERSION') ? File.read('VERSION').chomp : ""
  rdoc.rdoc_dir = 'rdoc'
  rdoc.title = "TicGit-ng #{version}"
  rdoc.rdoc_files.include('README*')
  rdoc.rdoc_files.include('lib/**/*.rb')
end

task :default => :create_gem


================================================
FILE: bin/ti
================================================
#!/usr/bin/env ruby
require 'rubygems'
require 'fileutils'

# Add the library from the source tree to the front of the load path.
# This allows ti to run without first installing a ticgit gem, which is
# important when testing multiple branches of development.
if File.exist? File.join('lib', 'ticgit-ng.rb')
    $LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib')
end
require 'ticgit-ng'

TicGitNG::CLI.execute


================================================
FILE: bin/ticgitweb
================================================
#!/usr/bin/env ruby

# starts a sinatra based web server that provides an interface to 
# your ticgit tickets
# 
# some of the sinatra code borrowed from sr's git-wiki
#
# author : Scott Chacon (schacon@gmail.com)
#

# Add the library from the source tree to the front of the load path.
# This allows ticgitweb to run without first installing a ticgit gem,
# which is important when testing multiple branches of development.
$LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib')

%w(rubygems sinatra git ticgit-ng haml sass).each do |dependency|
  begin
    require dependency
  rescue LoadError => e
    puts "You need to install #{dependency} before we can proceed"
  end
end

#This line is required to resolve this issue
#https://github.com/jeffWelling/ticgit/issues/22
enable :run

# !! TODO : if ARGV[1] is a path to a git repo, use that
# otherwise, look in ~/.ticgit

$ticgit = TicGitNG.open('.')

get('/_stylesheet.css') { Sass::Engine.new(File.read(__FILE__).gsub(/.*__END__/m, '')).render }

# ticket list view
get '/' do
  @tickets = $ticgit.ticket_list(:order => 'date.desc')
  haml(list('all'))
end

get '/fs/:state' do
  @tickets = $ticgit.ticket_list(:state => params[:state], :order => 'date.desc')
  haml(list(params[:state]))
end

get '/tag/:tag' do
  @tickets = $ticgit.ticket_list(:tag => params[:tag], :order => 'date.desc')
  haml(list(params[:tag]))
end

get '/sv/:saved_view' do
  @tickets = $ticgit.ticket_list(:saved => params[:saved_view])
  haml(list(params[:saved_view]))
end

# ticket single view
get '/ticket/:ticket' do
  @ticket = $ticgit.ticket_show(params[:ticket])
  haml(show)
end


# add ticket
get '/t/new' do
  haml(new_ticket)
end

# add ticket finalize
post '/t/new' do
  title = params[:title].to_s.strip
  if title.size > 1
    tags = params[:tags].split(',').map { |t| t.strip } rescue nil  
    t = $ticgit.ticket_new(title, {:comment => params[:comment].strip, :tags => tags})
    redirect '/ticket/' + t.ticket_id.to_s
  else
    redirect '/t/new'
  end
end


# add comment
post '/a/add_comment/:ticket' do
  t = $ticgit.ticket_comment(params[:comment], params[:ticket])
  redirect '/ticket/' + params[:ticket]
end

# add tag
post '/a/add_tags/:ticket' do
  t = $ticgit.ticket_tag(params[:tags], params[:ticket])
  redirect '/ticket/' + params[:ticket]
end

# change ticket state
get '/a/change_state/:ticket/:state' do
  $ticgit.ticket_change(params[:state], params[:ticket])
  redirect '/ticket/' + params[:ticket]
end


def layout(title, content)
  @saved = $ticgit.config['list_options'].keys rescue []
  %Q(
%html
  %head
    %title #{title}
    %link{:rel => 'stylesheet', :href => '/_stylesheet.css', :type => 'text/css', :media => 'screen'}
    %meta{'http-equiv' => 'Content-Type', :content => 'text/html; charset=utf-8'}

  %body
    #navigation
      %a{:href => '/'} All
      %a{:href => '/fs/open'} Open
      %a{:href => '/fs/resolved'} Resolved
      %a{:href => '/fs/hold'} Hold
      %a{:href => '/fs/invalid'} Invalid
      - if !@saved.empty?
        | Saved:
        - @saved.each do |s|
          %a{:href => "/sv/\#{s}"}= s
    #action
      %a{:href => '/t/new'} New Ticket

    #{content}
  )
end

def new_ticket
  layout('New Ticket', %q{
    %h1 Create a New Ticket
    %form{:action => '/t/new', :method => 'POST'}
      %table
        %tr
          %th Title
          %td 
            %input{:type => 'text', :name => 'title', :size => 30}
        %tr
          %th Tags
          %td
            %input{:name => 'tags', :size => 30}
            %small (comma delimited)
        %tr
          %th Comment
          %td 
            %textarea{:name => 'comment', :rows => 15, :cols => 30}
        %tr
          %td
          %td
            %input{:type => 'submit', :value => 'Create Ticket'}
  })
end

def list(title = 'all')
  @title = title
  layout(title + ' tickets', %q{
    %h1= "#{@title} tickets"
    - if @tickets.empty?
      %p No tickets found.
    - else
      %table.long
        - c = 'even'
        - @tickets.each do |t|
          %tr{:class => (c == 'even' ? c = 'odd' : c = 'even') }
            %td
              %a{:href => "/ticket/#{t.ticket_id}" }
                %code= t.ticket_id[0,6]
            %td&= t.title
            %td{:class => t.state}= t.state
            %td= t.opened.strftime("%m/%d")
            %td= t.assigned_name
            %td
              - t.tags.each do |tag|
                %a{:href => "/tag/#{tag}"}= tag
  })
end

def show
  layout('ticket', %q{
  %center
    %h1&= @ticket.title
  
    %form{:action => "/a/add_tags/#{@ticket.ticket_id}", :method => 'POST'}
      %table
        %tr
          %th TicId
          %td
            %code= @ticket.ticket_id
        %tr
          %th Assigned
          %td= @ticket.assigned
        %tr
          %th Opened
          %td= @ticket.opened
        %tr
          %th State
          %td{:class => @ticket.state}
            %table{:width => '300'}
              %tr
                %td{:width=>'90%'}= @ticket.state
                - $ticgit.tic_states.select { |s| s != @ticket.state}.each do |st|
                  %td{:class => st}
                    %a{:href => "/a/change_state/#{@ticket.ticket_id}/#{st}"}= st[0,2]
        %tr
          %th Tags
          %td
            - @ticket.tags.each do |t|
              %a{:href => "/tag/#{t}"}= t
            %div.addtag
              %input{:name => 'tags'}
              %input{:type => 'submit', :value => 'add tag'}
    
    %h3 Comments
    %form{:action => "/a/add_comment/#{@ticket.ticket_id}", :method => 'POST'}
      %div
        %textarea{:name => 'comment', :cols => 50}
        %br
        %input{:type => 'submit', :value => 'add comment'}
        
    %div.comments
      - @ticket.comments.reverse.each do |t|
        %div.comment
          %span.head
            Added
            = t.added.strftime("%m/%d %H:%M")
            by
            = t.user
          %div.comment-text
            = t.comment
        %br
  })
end

__END__
body
  :font
    family: Verdana, Arial, "Bitstream Vera Sans", Helvetica, sans-serif
    color: black
  line-height: 160%
  background-color: white
  margin: 2em

#navigation
  a
    background-color: #e0e0e0
    color: black
    text-decoration: none
    padding: 2px
  padding: 5px
  border-bottom: 1px black solid
  
#action
  text-align: right
  
.addtag
  padding: 5px 0
  
h1
  display: block
  padding-bottom: 5px

a
  color: black
a.exists
  font-weight: bold
a.unknown
  font-style: italic

.comments
  margin: 10px 20px
  .comment
    .head
      background: #eee
      padding: 4px
    .comment-text
      padding: 10px
      color: #333
  
table.long
  width: 100%
  
table
  tr.even
    td
      background: #eee
  tr.odd
    td
      background: #fff
      
table
  tr
    th
      text-align: left
      padding: 3px
      vertical-align: top
    td.open
      background: #ada
    td.resolved
      background: #abd
    td.hold
      background: #dda
    td.invalid
      background: #aaa  
      
.submit
  font-size: large
  font-weight: bold

.page_title
  font-size: xx-large

.edit_link
  color: black
  font-size: 14px
  font-weight: bold
  background-color: #e0e0e0
  font-variant: small-caps
  text-decoration: none



================================================
FILE: development.mkd
================================================
## Development ##

This document describes workflows currently used for various tasks (and other shenanigans if necessary).
I try to follow [this git flow](http://nvie.com/posts/a-successful-git-branching-model/). 

### Testing ###

To test:

    rspec spec/*_spec.rb


### Hotfixes ###

To create a hotfix:

    git checkout master
    git checkout -b hotfix-VERSION
    #Edit lib/ticgit-ng/version.rb to bump the version number
    #Apply your changes
    git checkout master
    git merge --no-ff hotfix-VERSION
    git tag VERSION

### Creating a gem ###

To create a gem:

   gem build ticgit-ng.gemspec

This produces `TicGit-ng-VERSION.gem`.
To push the gem, you would do `gem push TicGit-ng-VERSION.gem` but this would require an account on Rubygems, and would also require renaming the gem due to namespace conflicts.

### Testing ###

I'm a firm believer in testing.  If you are submitting a patch or pull request, please do your absolute best to include a test. I will write the test myself if I can, but this increases the time it takes to get the patch included and published. In some circumstances it is fine to not include a patch, eg difficult to test problems.


================================================
FILE: examples/post-commit
================================================
#!/usr/bin/env ruby

require 'tempfile'


commit_log   = `git log -1`.chomp
m, commit_id = * commit_log.match(/commit\W*([A-Fa-f0-9]+)/)

Tempfile.open('ticgit_comment') do |tmp|
  tmp.write commit_log
  actions = {}

  # comment on any tickets this commit references
  commit_log.scan(/\(\W*[Rr]efs?\W*:*\W*\#([a-fA-F0-9]+)\W*\)/).each do |ticked_id|
    actions[ticket_id] = :ref
  end

  # close any tickets this commit solves
  # overwrite any refs, as the commit log will still
  # be added to the ticket as a comment, but will also be closed
  commit_log.scan(/\(\W*[Cc]loses\W*:*\W*\#([a-fA-F0-9]+)\W*\)/).each do |ticket_id|
    actions[ticket_id] = :close
  end

  actions.each do |ticket_id, action|
    `ti comment #{ticket_id} --file #{tmp.path}` if action
    `ti state #{ticket_id} resolved`             if action == :close
  end
end


================================================
FILE: lib/ticgit-ng/attachment.rb
================================================
module TicGitNG
    class Attachment
        attr_reader :user, :added, :filename, :sha, :attachment_name
        attr_reader :original_filename
        alias :read :initialize

        def initialize( fname )
            #FIXME expect fname to be a raw filename that needs to be converted
            #      into a properly formatted ticket name
            @filename=fname
            trailing_underscore= File.basename(fname)[/_$/] ? true : false
            trailing_underscore=false
            temp=File.basename(fname).split('_').reverse
            @added=Time.at(temp.pop.to_i)
            @user= temp.pop
            @attachment_name= temp.reverse.join('_')
            if trailing_underscore
              @attachment_name << '_'
            end
        end

        #Called when attaching a new attachment and when reading/opening attachments
        #FIXME Make a 'read' and 'create' function to differentiate between
        #      between creation of a ticket and reading an existing ticket.
        def self.create raw_fname, ticket, time 
            #Attachment naming format:
            #ticket_name/ATTACHMENTS/123456_jeff.welling@gmail.com_fubar.jpg
            #raw_fname "/home/guy/Desktop/fubar.jpg"

            #create attachment dir if first run
            a_name= File.expand_path( File.join(
                File.join( ticket.ticket_name, 'ATTACHMENTS' ), 
                ticket.create_attachment_name(raw_fname, time)
            ))
            #create new filename from ticket
            if File.exist?( File.dirname( a_name )  ) && 
               !File.directory?( File.dirname(a_name) )

                puts "Could not create ATTACHMENTS directory"
                exit 1
            elsif !File.exist?( File.dirname( a_name ) )
                Dir.mkdir File.dirname( a_name )
            end
            #copy/link the raw_filename
            Dir.chdir( File.dirname(a_name) ) do
                FileUtils.cp( raw_fname, a_name )
            end
            #call init on the new file to properly populate the variables
            a_name= File.join( 
                              File.basename( File.dirname( a_name ) ),
                              File.basename( a_name )
                             )
            return Attachment.new( a_name )
        end
    end
end


================================================
FILE: lib/ticgit-ng/base.rb
================================================
module TicGitNG
  class NoRepoFound < StandardError;end
  class Base

    attr_reader :git, :logger
    attr_reader :tic_working, :tic_index, :tic_dir
    attr_reader :last_tickets, :current_ticket  # saved in state
    attr_reader :config
    attr_reader :state, :config_file

    def initialize(git_dir, opts = {})
      @git = Git.open(find_repo(git_dir))

      begin
        git.lib.full_log_commits :count => 1
      rescue
        puts "Git error: please check your git repository, you must have at least one commit in git"
        exit 1
      end

      @logger = opts[:logger] || Logger.new(STDOUT)

      #This is to accomodate for edge-cases where @logger.puts
      #is called from debugging code.
      if @logger.respond_to?(:puts) && !@logger.respond_to?(:info)
        @logger.class.class_eval do
          alias :info :puts
        end
      elsif @logger.respond_to?(:info) && !@logger.respond_to?(:puts)
        @logger.class.class_eval do
          alias :puts :info
        end
      end
         
      @last_tickets = []
      @init=opts[:init]

      proj = Ticket.clean_string(@git.dir.path)

      #Use this hack instead of git itself because this is ridiculously faster then
      #getting the same information from git
      branches= Dir.entries( File.join(find_repo(git_dir),'.git/refs/heads/') ).delete_if {|i|
        i=='.' || i=='..'
      }
      branch= branches.include?('ticgit-ng') ? ('ticgit-ng') : ('ticgit')

      @tic_dir = opts[:tic_dir] ||"~/.#{branch}"
      @tic_working = opts[:working_directory] || File.expand_path(File.join(@tic_dir, proj, 'working'))
      @tic_index = opts[:index_file] || File.expand_path(File.join(@tic_dir, proj, 'index'))

      @last_tickets = []

      #expire @tic_index and @tic_working if it mtime is older than 
      #git log.  Otherwise, during testing, if you use the same temp
      #directory with the same name, deleting it and recreating it
      #to test something, ticgit would get confused by the cache from
      #the previous instance of the temp dir.
      if File.exist?(@tic_working)
        cache_mtime=File.mtime(@tic_working)
        begin
          gitlog_mtime= File.mtime(File.join( find_repo('.'), ".git/refs/heads/#{branch}" ))
        rescue
          reset_cache
        end

        #unless (cache_mtime > gitlog_mtime.-(20) and cache_mtime <= gitlog_mtime) or (cache_mtime > gitlog_mtime.+(30) and cache_mtime >= gitlog_mtime)
        #FIXME break logic out into several lines
        #FIXME don't bother resetting if gitlog_mtime.to_i == 0
        if needs_reset?( cache_mtime, gitlog_mtime ) and !cache_mtime==gitlog_mtime
          puts "Resetting cache" unless gitlog_mtime.to_i == 0
          reset_cache
        end

      end

      # load config file
      @config_file = File.expand_path(File.join(@tic_dir, proj, 'config.yml'))
      if File.exists?(config_file)
        @config = YAML.load(File.read(config_file))
      else
        @config = {}
      end

      @state = File.expand_path(File.join(@tic_dir, proj, 'state'))

      unless branches.include?(branch) && File.directory?(@tic_working)
        if branches.include?(branch) and !File.exist?(@tic_working)
          #branch exists but tic_working doesn't
          #this could be because the dir was deleted or the repo itself
          #was moved, so recreate the dir.
          reset_ticgitng
        elsif @init
          puts "Initializing TicGit-ng"
          init_ticgitng_branch( branches.include?(branch) )
        else
          puts "Please run `ti init` to initialize TicGit-ng for this repository before running other ti commands."
          exit
        end
      end

      if File.file?(@state)
        load_state
      else
        reset_ticgitng
      end
    end

    def find_repo(dir)
      full = File.expand_path(dir)
      ENV["GIT_WORKING_DIR"] || loop do
        return full if File.directory?(File.join(full, ".git"))
        raise NoRepoFound if full == full=File.dirname(full)
      end
    end

    # marshal dump the internals
    # save config file
    def save_state
      state_list = [@last_tickets, @current_ticket]
      unless File.exist? @state
        FileUtils.mkdir_p( File.dirname(@state) )
      end
      File.open(@state, 'w+'){|io| Marshal.dump(state_list, io) }
      File.open(@config_file, 'w+'){|io| io.write(config.to_yaml) }
    end

    # read in the internals
    def load_state
      state_list = File.open(@state){|io| Marshal.load(io) }
      garbage_data=nil
      if state_list.length == 2
        @last_tickets, @current_ticket = state_list
      else
        #This was left behind so that people can continue load_state-ing
        #without having to delete their ~/.ticgit directory when
        #updating to this version (rename to ticgit-ng)
        garbage_data, @last_tickets, @current_ticket = state_list
      end
    end

    # returns new Ticket
    def ticket_new(title, options = {}, time=nil)
      t = TicGitNG::Ticket.create(self, title, options, time)
      reset_ticgitng
      TicGitNG::Ticket.open(self, t.ticket_name, tickets[t.ticket_name])
    end

    #This is a legacy function from back when ticgit-ng needed to have its
    #cache reset in order to avoid cache corruption.
    def reset_ticgitng
      tickets
      save_state
    end

    # returns new Ticket
    def ticket_comment(comment, ticket_id = nil)
      if t = ticket_revparse(ticket_id)
        ticket = TicGitNG::Ticket.open(self, t, tickets[t])
        ticket.add_comment(comment)
        reset_ticgitng
        ticket
      end
    end

    # returns array of Tickets
    def ticket_list(options = {})
      reset_ticgitng
      ts = []
      @last_tickets = []
      @config['list_options'] ||= {}

      tickets.to_a.each do |name, t|
        ts << TicGitNG::Ticket.open(self, name, t)
      end

      if name = options[:saved]
         if c = config['list_options'][name]
           options = c.merge(options)
         end
      end

      if options[:list]
        # TODO : this is a hack and i need to fix it
        config['list_options'].each do |name, opts|
          puts name + "\t" + opts.inspect
        end
        return false
      end

      if options.size == 0
        # default list
        options[:state] = 'open'
      end

      # :tag, :state, :assigned
      if t = options[:tags]
        t = {false => Set.new, true => Set.new}.merge t.classify { |x| x[0,1] != "-" }
        t[false].map! { |x| x[1..-1] }
        ts = ts.reject { |tic| t[true].intersection(tic.tags).empty? } unless t[true].empty?
        ts = ts.select { |tic| t[false].intersection(tic.tags).empty? } unless t[false].empty?
      end
      if s = options[:states]
        s = {false => Set.new, true => Set.new}.merge s.classify { |x| x[0,1] != "-" }
        s[true].map! { |x| Regexp.new(x, Regexp::IGNORECASE) }
        s[false].map! { |x| Regexp.new(x[1..-1], Regexp::IGNORECASE) }
        ts = ts.select { |tic| s[true].any? { |st| tic.state =~ st } } unless s[true].empty?
        ts = ts.reject { |tic| s[false].any? { |st| tic.state =~ st } } unless s[false].empty?
      end
      if a = options[:assigned]
        ts = ts.select { |tic| tic.assigned =~ Regexp.new(a, Regexp::IGNORECASE) }
      end

      # SORTING
      if field = options[:order]
        field, type = field.split('.')

        case field
        when 'assigned'; ts = ts.sort_by{|a| a.assigned }
        when 'state';    ts = ts.sort_by{|a| a.state }
        when 'date';     ts = ts.sort_by{|a| a.opened }
        when 'title';    ts = ts.sort_by{|a| a.title }
        end

        ts = ts.reverse if type == 'desc'
      else
        # default list
        ts = ts.sort_by{|a| a.opened }
      end

      if options.size == 0
        # default list
        options[:state] = 'open'
      end

      # :tag, :state, :assigned
      if t = options[:tag]
        ts = ts.select { |tag| tag.tags.include?(t) }
      end
      if s = options[:state]
        ts = ts.select { |tag| tag.state =~ /#{s}/ }
      end
      if a = options[:assigned]
        ts = ts.select { |tag| tag.assigned =~ /#{a}/ }
      end

      if save = options[:save]
        options.delete(:save)
        @config['list_options'][save] = options
      end

      @last_tickets = ts.map{|t| t.ticket_name }
      # :save

      save_state
      ts
    end

    # returns single Ticket
    def ticket_show(ticket_id = nil)
      # ticket_id can be index of last_tickets, partial sha or nil => last ticket
      reset_ticgitng
      if t = ticket_revparse(ticket_id)
        return TicGitNG::Ticket.open(self, t, tickets[t])
      end
    end

    # returns recent ticgit-ng activity
    # uses the git logs for this
    def ticket_recent(ticket_id = nil)
      if ticket_id
        t = ticket_revparse(ticket_id)
        return git.log.object(which_branch?).path(t)
      else
        return git.log.object(which_branch?)
      end
    end

    def ticket_revparse(ticket_id)
      if ticket_id
        ticket_id = ticket_id.strip

        if /^[0-9]*$/ =~ ticket_id && (t = @last_tickets[ticket_id.to_i - 1])
          return t
        elsif ticket_id.length > 4 # partial (5 characters or greater to be considered unique enough) or full sha
          regex = /^#{Regexp.escape(ticket_id)}/
          ch = tickets.select{|name, t|
            t['files'].assoc('TICKET_ID')[1] =~ regex }
          ch.first[0] if ch.first
        end
      elsif(@current_ticket)
        return @current_ticket
      end
    end

    def ticket_tag(tag, ticket_id = nil, options = OpenStruct.new)
      if t = ticket_revparse(ticket_id)
        ticket = TicGitNG::Ticket.open(self, t, tickets[t])
        if options.remove
          ticket.remove_tag(tag)
        else
          ticket.add_tag(tag)
        end
        reset_ticgitng
        ticket
      end
    end

    def ticket_change(new_state, ticket_id = nil)
      if t = ticket_revparse(ticket_id)
        if tic_states.include?(new_state)
          ticket = TicGitNG::Ticket.open(self, t, tickets[t])
          ticket.change_state(new_state)
          reset_ticgitng
          ticket
        end
      end
    end

    def ticket_assign(new_assigned = nil, ticket_id = nil)
      if t = ticket_revparse(ticket_id)
        ticket = TicGitNG::Ticket.open(self, t, tickets[t])
        ticket.change_assigned(new_assigned)
        reset_ticgitng
        ticket
      end
    end

    def ticket_points(new_points = nil, ticket_id = nil)
      if t = ticket_revparse(ticket_id)
        ticket = TicGitNG::Ticket.open(self, t, tickets[t])
        ticket.change_points(new_points)
        reset_ticgitng
        ticket
      end
    end

    def ticket_checkout(ticket_id)
      if t = ticket_revparse(ticket_id)
        ticket = TicGitNG::Ticket.open(self, t, tickets[t])
        @current_ticket = ticket.ticket_name
        save_state
        ticket
      end
    end

    def tic_states
      ['open', 'resolved', 'invalid', 'hold']
    end

    def sync_tickets(repo='origin', push=true, verbose=true )
      puts "Fetching #{repo}" if verbose
      @git.fetch(repo)
      puts "Syncing tickets with #{repo}" if verbose
      remote_branches=@git.branches.remote.map{|b|
        b.full.gsub('remotes/', '')[Regexp.new("^#{Regexp.escape(repo)}/.*")]
      }.compact
      remote_branches.include?("#{repo}/ticgit-ng") ? r_ticgit='ticgit-ng' : r_ticgit='ticgit'
      in_branch(false) do
        repo_g=git.remote(repo)
        git.pull(repo_g, repo+'/'+r_ticgit)
        git.push(repo_g, "#{which_branch?}:"+r_ticgit ) if push
        puts "Tickets synchronized." if verbose
      end
    end

    def tickets
      read_tickets
    end

    def read_tickets
      tickets = {}

      tree = git.lib.full_tree(which_branch?)
      tree.each do |t|
        data, file = t.split("\t")
        mode, type, sha = data.split(" ")
        tic = file.split('/')
        if tic.size == 2  # directory depth
            ticket, info = tic
            tickets[ticket] ||= { 'files' => [] }
            tickets[ticket]['files'] << [info, sha]
        elsif tic.size == 3
            ticket, attch_dir, filename = tic
            if filename
                filename = 'ATTACHMENTS_' + filename
                tickets[ticket] ||= { 'files' => [] }
                tickets[ticket]['files'] << [filename, sha]
            end
        end
      end
      tickets
    end

    def init_ticgitng_branch(ticgitng_branch = false)
      @logger << 'creating ticgit-ng repo branch'

      in_branch(ticgitng_branch) do
        #The .hold file seems to have little to no purpose aside from helping
        #figure out if the branch should be checked out or not.  It is created
        #when the ticgit branch is created, and seems to exist for the lifetime
        #of the ticgit branch. The purpose seems to be, to be able to tell if
        #the ticgit branch is already checked out and not check it out again if
        #it is.  This might be superfluous after switching to grit.
        new_file('.hold', 'hold')

        unless ticgitng_branch
          git.add ".hold"
          git.commit('creating the ticgit-ng branch')
        end
      end
    end

    # temporarlily switches to ticgit branch for tic work
    def in_branch(branch_exists = true)
      needs_checkout = false

      unless File.directory?(@tic_working)
        FileUtils.mkdir_p(@tic_working)
        needs_checkout = true
      end
      needs_checkout = true unless File.file?('.hold')

      old_current = git.lib.branch_current
      begin
        git.lib.change_head_branch(which_branch?)
        git.with_index(@tic_index) do
          git.with_working(@tic_working) do |wd|
            git.lib.checkout(which_branch?) if needs_checkout &&
              branch_exists
            yield wd
          end
        end
      ensure
        git.lib.change_head_branch(old_current)
      end
    end

    def new_file(name, contents)
      File.open(name, 'w+'){|f| f.puts(contents) }
    end

    def which_branch?
      #At present use the 'ticgit' branch for backwards compatibility
      branches=@git.branches.local.map {|b| b.name}
      if branches.include? 'ticgit-ng'
        return 'ticgit-ng'
      else
        return 'ticgit'
      end

      #If has ~/.ticgit dir, and 'ticgit' branch
      #If has ~/.ticgit-ng dir, and 'ticgit-ng' branch, and not ~/.ticgit dir and not 'ticgit' branch
    end

    def reset_cache
      #@state, @tic_index, @tic_working
      #A rescue is appended to the end of each line because it allows
      #execution of others to continue upon failure, as opposed to
      #a begin;rescue;end segment.
      FileUtils.rm_r File.expand_path(@tic_working) rescue nil
      FileUtils.rm File.expand_path(@state) rescue nil
      FileUtils.rm File.expand_path(@tic_index) rescue nil
      FileUtils.mkdir_p File.expand_path(@tic_working) rescue nil
      @state=nil
    end

    def needs_reset? cache_mtime, gitlog_mtime
      ((cache_mtime.to_i - gitlog_mtime.to_i) > 120) or ((gitlog_mtime.to_i - cache_mtime.to_i) > 120)
    end
    
    def ticket_attach filename, ticket_id=nil, time=nil
        t = ticket_revparse( ticket_id )
        ticket= TicGitNG::Ticket.open( self, t, tickets[t] )
        ticket.add_attach( self, filename, time )
        reset_ticgitng
        ticket
    end

    #ticket_get_attachment()
    #file_id -      return the attachment identified by file_id
    #new_filename - save the attachment as new_filename
    #ticket_id -    get the attachment from ticket_id instead of current
    def ticket_get_attachment file_id=nil, new_filename=nil, ticket_id=nil 
        if t = ticket_revparse(ticket_id)
            ticket = Ticket.open( self, t, tickets[t] )
            ticket.get_attach( file_id, new_filename )
        end
    end
  end
end


================================================
FILE: lib/ticgit-ng/cli.rb
================================================
require 'ticgit-ng'
require 'ticgit-ng/command'

# used Cap as a model for this - thanks Jamis

module TicGitNG
  class CLI
    def self.execute
      parse(ARGV).execute!
    end

    def self.parse(args)
      #new() calls initialize(...) below
      cli = new(args)
      cli.parse_options!
      cli
    end

    attr_reader :action, :options, :args, :tic
    attr_accessor :out

    def initialize(args, path = '.', out = $stdout)
      @args = args.dup

      #set @init if one of the args is 'init'
      #this needs to be done because initialization of the ticgit branch must be done before
      #the branch is loaded, but because of the way commands are modularized this must be done
      #outside of and before the init.rb file itself is called (init.rb is where we would
      #normally put the code for such a command).
      args.include?( 'init' ) ? (@init=true) : (@init=false)
      #@init= ((args[0][/init/]=='init') rescue false)
      #@init= ((args[0][/init/]=='init') or (args[1][/init/]=='init') rescue false)
      
      @tic = TicGitNG.open(path, {:keep_state => true, :init => @init, :logger  => out })
      @options = OpenStruct.new
      @out = out

      @out.sync = true # so that Net::SSH prompts show up
    rescue NoRepoFound
      out.puts "No repo found"
      exit
    end

    def execute!
      if mod = Command.get(action)
        extend(mod)

        if respond_to?(:parser)
          option_parser = Command.parser(action, &method(:parser))
        else
          option_parser = Command.parser(action)
        end

        option_parser.parse!(args)

        execute if respond_to?(:execute)
      else
        puts usage

        if args.empty? and !action
          exit
        else
          puts('%p is not a command' % action)
          exit 1
        end
      end
    end

    def parse_options! #:nodoc:
      if args.empty?
        puts "Please specify at least one action to execute."
        puts
        puts usage(args)
        exit 1
      end

      #FIXME
      #this is a dirty hack that needs to be fixed
      if args.include?('list') and args.include?('init')
        @action = 'list'
      else
        @action = args.shift
      end
    end

    def usage(args = nil)
      old_args = args || [action, *self.args].compact

      if respond_to?(:parser)
        Command.parser('COMMAND', &method(:parser))
        # option_parser.parse!(args)
      else
        Command.usage(old_args.first, old_args)
      end
    end

    def get_editor_message(comments = nil)
      message_file = Tempfile.new('ticgitng_message').path
      File.open(message_file, 'w') { |f| f.puts comments } if comments

      editor = ENV["EDITOR"] || 'vim'
      system("#{editor} #{message_file}");
      message = File.readlines(message_file)
      message = message.select { |line| line[0, 1] != '#' } # removing comments
      if message.empty?
        return false
      else
        return message
      end
    end

    def ticket_show(t, more=nil)
        days_ago = ((Time.now - t.opened) / (60 * 60 * 24)).round

        data = [
            ['Title',    t.title],
            ['TicId',    t.ticket_id],
            '',
            ['Assigned', t.assigned],
            ['Opened',   "#{t.opened} (#{days_ago} days)"],
            ['State',    t.state.upcase],
            ['Points',   t.points || 'no estimate'],
            ['Tags',     t.tags.join(', ')],
            ''
        ]

        data.each do |(key, value)|
            puts(value ? "#{key}: #{value}" : key)
        end

        #FIXME display attachments inline chronologically with comments
        unless t.comments.empty? and t.attachments.empty?
            comments_and_attachments= Hash.new
            puts "Comments and attachments (#{t.comments.size + t.attachments.size}):"
            t.comments.each do |c|
                comments_and_attachments[c.added]=c
            end
            
            t.attachments.each do |a|
                comments_and_attachments[a.added]=a
            end
            comments_and_attachments.sort.each {|item|
                if item[1].class==TicGitNG::Comment
                    #print comment
                    puts "  * Added #{item[1].added.strftime('%m/%d %H:%M')} by #{item[1].user}"

                    wrapped = item[1].comment.split("\n").map{|line|
                        line.length > 80 ? line.gsub(/(.{1,80})(\s+|$)/, "\\1\n").strip : line
                    }.join("\n")

                    wrapped = wrapped.split("\n").map{|line| "\t#{line}" }

                    if wrapped.size > 6 and more.nil?
                        puts wrapped[0, 6].join("\n")
                        puts "\t** more... **"
                    else
                        puts wrapped.join("\n")
                    end
                    puts
                else
                    #print attachment
                    puts "  * Added #{item[1].added.strftime('%m/%d %H:%M')} by #{item[1].user}"
                    puts "    Attachment: #{t.attachments.index(item[1]) }"
                    puts "    Filename:   #{item[1].attachment_name}"
                    puts
                end
            }
        end
    end

    class << self
      attr_accessor :window_lines, :window_cols

      TIOCGWINSZ_INTEL = 0x5413     # For an Intel processor
      TIOCGWINSZ_PPC   = 0x40087468 # For a PowerPC processor
      STDOUT_HANDLE    = 0xFFFFFFF5 # For windows

      def reset_window_width
        try_using(TIOCGWINSZ_PPC) ||
        try_using(TIOCGWINSZ_INTEL) ||
          try_windows ||
          use_fallback
      end

      # Set terminal dimensions using ioctl syscall on *nix platform
      # TODO: find out what is raised here on windows.
      def try_using(mask)
        buf = [0,0,0,0].pack("S*")

        if $stdout.ioctl(mask, buf) >= 0
          self.window_lines, self.window_cols = buf.unpack("S2")
          true
        end
      rescue Errno::EINVAL, Errno::ENOTTY
      end

      def try_windows
        lines, cols = windows_terminal_size
        self.window_lines, self.window_cols = lines, cols if lines and cols
      end

      # Determine terminal dimensions on windows platform
      def windows_terminal_size
        m_GetStdHandle = Win32API.new(
          'kernel32', 'GetStdHandle', ['L'], 'L')
        m_GetConsoleScreenBufferInfo = Win32API.new(
          'kernel32', 'GetConsoleScreenBufferInfo', ['L', 'P'], 'L' )
        format = 'SSSSSssssSS'
        buf = ([0] * format.size).pack(format)
        stdout_handle = m_GetStdHandle.call(STDOUT_HANDLE)

        m_GetConsoleScreenBufferInfo.call(stdout_handle, buf)
        (bufx, bufy, curx, cury, wattr,
         left, top, right, bottom, maxx, maxy) = buf.unpack(format)
        return bottom - top + 1, right - left + 1
      rescue NameError
      end

      def use_fallback
        self.window_lines, self.window_cols = 25, 80
      end
    end

    def window_lines
      TicGitNG::CLI.window_lines
    end

    def window_cols
      TicGitNG::CLI.window_cols
    end

    if ''.respond_to?(:chars)
      # assume 1.9
      def just(value, size = 10, side = :left)
        value = value.to_s

        if value.bytesize > size
          sub_value = "#{value[0, size - 1]}+"
        else
          sub_value = value[0, size]
        end

        just_common(sub_value, size, side)
      end
    else
      def just(value, size = 10, side = :left)
        chars = value.to_s.scan(/./um)

        if chars.size > size
          sub_value = "#{chars[0, size-1]}+"
        else
          sub_value = chars.join
        end

        just_common(sub_value, size, side)
      end
    end

    def just_common(value, size, side)
      case side
      when :r, :right
        value.rjust(size)
      when :l, :left
        value.ljust(size)
      end
    end

    def puts(*strings)
      @out.puts(*strings)
    end
  end
end

TicGitNG::CLI.reset_window_width
begin
    Signal.trap("SIGWINCH") { TicGitNG::CLI.reset_window_width }
rescue
    TicGitNG::CLI.use_fallback
end


================================================
FILE: lib/ticgit-ng/command/assign.rb
================================================
module TicGitNG
  module Command
    # Assigns a ticket to someone
    #
    # Usage:
    # ti assign             (assign checked out ticket to current user)
    # ti assign {1}         (assign ticket to current user)
    # ti assign -c {1}      (assign ticket to current user and checkout the ticket)
    # ti assign -u {name}   (assign ticket to specified user)
    # ti assign -u {name} {1} (assign specified ticket to specified user)
    module Assign
      def parser(opts)
        opts.banner = "Usage: ti assign [options] [ticket_id]\n"+
                      "Note: to assign to nobody: ti assign -u ''"
        opts.on_head(
          "-u USER", "--user USER", "Assign the ticket to this user"){|v|
          options.user = v
        }
        opts.on_head(
          "-c TICKET", "--checkout TICKET", "Checkout this ticket"){|v|
          options.checkout = v
        }
      end
      def execute
        handle_ticket_assign
      end
      def handle_ticket_assign
        tic.ticket_checkout(options.checkout) if options.checkout
        if ARGV.length == 1  #ti assign
          tic_id=nil
        elsif ARGV.length == 2 #ti assign {ticid}
          tic_id=ARGV[1]
        elsif ARGV.length == 3 #ti assign -u/-c {user/ticid}
          if options.user
            tic_id=nil
          else
            tic_id=options.checkout
          end
        end
        tic.ticket_assign((options.user rescue nil), tic_id)
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/attach.rb
================================================
module TicGitNG
    module Command
        # Attach a file to a ticket
        #
        # Usage:
        # ti attach                             
        # (print help for 'ti attach')
        #
        # ti attach {filename}
        # (attach {filename} to current ticket)
        #
        # ti attach -i {ID} {filename}          
        # (attach file {filename} to ticket with ID {ID})
        #
        # ti attach -g {f_id}
        # (retrieve attached file {f_id}, place in current dir}
        #
        # ti attach -g {f_id} -n {new_filename}
        # (retrieve attached file {f_id}, place as {new_filename})
        module Attach
            def parser(opts)
                opts.banner = "Usage: ti attach [options] [filename]"

                opts.on_head(
                    "-i TICKET_ID", "--id TICKET_ID", "Attach the file to this ticket"){|v|
                    options.ticket_id = v
                }
                opts.on_head(
                    "-g FILE_ID", "--get FILE_ID", "Retrieve the file FILE_ID"){|v|
                    puts "Warning: ticket ID argument is not valid with the retrieve attachment argument" if options.ticket_id
                    options.get_file = v
                }
                opts.on_head(
                    "-n N_FILENAME", "--new-filename", "Use this filename for the retrieved attachment"){|v|
                    raise ArgumentError, "Error: New filename argument is only valid with the retrieve arrachment argument" unless options.get_file
                    options.new_filename = v
                }
            end
            def execute
                if options.get_file
                    tic.ticket_get_attachment( options.get_file, options.new_filename )
                else
                    tic.ticket_attach( args[0], options.ticket_id )
                end
            end
        end
    end
end


================================================
FILE: lib/ticgit-ng/command/checkout.rb
================================================
module TicGitNG
  module Command
    module Checkout
      def parser(opts)
        opts.banner = "ti checkout [ticid]"
      end

      def execute
        tid = args[0]
        tic.ticket_checkout(tid)
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/comment.rb
================================================
module TicGitNG
  module Command
    module Comment
      def parser(opts)
        opts.banner = "Usage: ti comment [tic_id] [options]"
        opts.on_head(
          "-m MESSAGE", "--message MESSAGE",
          "Message you would like to add as a comment"){|v|
          options.message = v
        }
        opts.on_head(
          "-f FILE", "--file FILE",
          "A file that contains the comment you would like to add"){|v|
          raise ArgumentError, "Only 1 of -f/--file and -m/--message can be specified" if options.message
          raise ArgumentError, "File #{v} doesn't exist" unless File.file?(v)
          raise ArgumentError, "File #{v} must be <= 2048 bytes" unless File.size(v) <= 2048
          options.file = v
        }
      end

      def execute
        tid = args[0].strip if args[0]
        message, file = options.message, options.file

        if message
          tic.ticket_comment(message, tid)
        elsif file
          tic.ticket_comment(File.read(file), tid)
        else
          return unless message = get_editor_message
          tic.ticket_comment(message.join(''), tid)
        end
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/help.rb
================================================
module TicGitNG
  module Command
    # Shows help for ticgit or a particular command
    #
    # Usage:
    # ti help               (show help for ticgit)
    # ti help {command}     (show help for specified command)
    module Help
      def parser(opts)
        opts.banner = "Usage: ti help [command]\n"
      end
      def execute
        cli = CLI.new([])
        if ARGV.length >= 2 # ti help {command}
          action = ARGV[1]
          if command = Command.get(action)
            cli.extend(command)
          else
            puts "Unknown command #{action}\n\n"
          end
        end
        puts cli.usage
      end
    end
  end
end



================================================
FILE: lib/ticgit-ng/command/init.rb
================================================
module TicGitNG
  module Command
    module Init
      def parser o
        o.banner= "Usage: ti init"
      end
      def execute
        @tic.read_tickets
=begin
        #Initialization has to happen earlier in the code so this code stands
        #as an example, when `ti init` is called, initialization is handled by
        #base.rb:354 (at the time of writing this).
        tic.base.init_ticgitng_branch(
          git.lib.branches_all.map{|b| b.first }.include?(which_branch?)
        )
=end
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/list.rb
================================================
module TicGitNG
  module Command
    # List tickets
    module List
      def parser(o)
        o.banner = "Usage: ti list [options]"
        o.on_head(
          "-o ORDER", "--order ORDER",
          "Field to order by - one of : assigned,state,date,title [.desc for reverse order]"){|v|
          options.order = v
        }

        o.on_head(
          "-t TAG[,TAG]", "--tags TAG[,TAG]", Array,
          "List only tickets with specific tag(s)",
          "Prefix the tag with '-' to negate"){|v|
          options.tags ||= Set.new
          options.tags.merge v
        }

        o.on_head(
          "-s STATE[,STATE]", "--states STATE[,STATE]", Array,
          "List only tickets in a specific state(s)",
          "Prefix the state with '-' to negate"){|v|
          options.states ||= Set.new
          options.states.merge v
        }

        o.on_head(
          "-a ASSIGNED", "--assigned ASSIGNED",
          "List only tickets assigned to someone"){|v|
          options.assigned = v
        }

        o.on_head("-S SAVENAME", "--saveas SAVENAME",
                     "Save this list as a saved name"){|v|
          options.save = v
        }

        o.on_head("-l", "--list", "Show the saved queries"){|v|
          options.list = true
        }
      end

      def execute
        options.saved = args[0] if args[0]

        if tickets = tic.ticket_list(options.to_hash)
          counter = 0
          cols = [80, window_cols].max

          puts
          puts [' ', just('#', 4, 'r'),
            just('TicId', 6),
            just('Title', cols - 56),
            just('State', 5),
            just('Date', 5),
            just('Assgn', 8),
            just('Tags', 20) ].join(" ")

          puts "-" * cols

          tickets.each do |t|
            counter += 1
            tic.current_ticket == t.ticket_name ? add = '*' : add = ' '
            puts [add, just(counter, 4, 'r'),
              t.ticket_id[0,6],
              just(t.title, cols - 56),
              just(t.state, 5),
              t.opened.strftime("%m/%d"),
              just(t.assigned_name, 8),
              just(t.tags.join(','), 20) ].join(" ")
          end
          puts
        end

      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/milestone.rb
================================================
module TicGitNG
  module Command
    # tic milestone
    # tic milestone migration1 (list tickets)
    # tic milestone -n migration1 3/4/08 (new milestone)
    # tic milestone -a {1} (add ticket to milestone)
    # tic milestone -d migration1 (delete)
    module Milestone
      def parser(opts)
        opts.banner = "Usage: ti milestone [milestone_name] [options] [date]"

        opts.on_head(
          "-n MILESTONE", "--new MILESTONE",
          "Add a new milestone to this project"){|v| options.new = v }

        opts.on_head(
          "-a TICKET", "--new TICKET",
          "Add a ticket to this milestone"){|v| options.add = v }

        opts.on_head(
          "-d MILESTONE", "--delete MILESTONE",
          "Remove a milestone"){|v| options.remove = v }
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/new.rb
================================================
module TicGitNG
  module Command
    module New
      def parser(opts)
        opts.banner = "Usage: ti new [options]"
        opts.on_head(
          "-t TITLE", "--title TITLE",
          "Title to use for the name of the new ticket"){|v| options.title = v }
      end

      def execute
        if title = options.title
          ticket_show(tic.ticket_new(title, options.to_hash))
        else
          # interactive
          prompt = "\n# ---\ntags:\n"
          prompt += "# first line will be the title of the tic, the rest will be the first comment\n"
          prompt += "# if you would like to add initial tags, put them on the 'tags:' line, comma delim"

          if message = get_editor_message(prompt)
            title = message.shift
            if title && title.chomp.length > 0
              title = title.chomp
              if message.last[0, 5] == 'tags:'
                tags = message.pop
                tags = tags.gsub('tags:', '')
                tags = tags.split(',').map { |t| t.strip }
              end
              if message.size > 0
                comment = message.join("")
              end
              ticket_show(tic.ticket_new(title, :comment => comment, :tags => tags))
            else
              puts "You need to at least enter a title"
            end
          else
            puts "It seems you wrote nothing"
          end
        end
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/points.rb
================================================
module TicGitNG
  module Command
    # Assigns points to a ticket
    #
    # Usage:
    # ti points {1} {points}   (assigns points to a specified ticket)
    module Points
      def parser(opts)
        opts.banner = "ti points [ticket_id] points"
      end

      def execute
        case args.size
        when 1
          new_points = args[0].to_i
        when 2
          tid = args[0]
          new_points = args[1].to_i
        else
          puts usage
          exit 1
        end

        tic.ticket_points(new_points, tid)
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/recent.rb
================================================
module TicGitNG
  module Command
    module Recent
      def parser(opts)
        opts.banner = 'Usage: ti recent'
      end

      def execute
        # "args[0]" seems to be superfluous.  It's usage
        # is undocumented, and supplying an argument
        # doesn't seem to do anything.
        #
        # Im guessing the purpose of args[0] was to provide a
        # specific ticket_id whos history would be looked up
        # intead of looking up the history for all tickets.
        #
        # #FIXME Reimplement that functionality and updte
        # docs to match
        tic.ticket_recent(args[0]).each do |commit|
          sha = commit.sha[0, 7]
          date = commit.date.strftime("%m/%d %H:%M")
          message = commit.message

          puts "#{sha}  #{date}\t#{message}"
        end
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/show.rb
================================================
module TicGitNG
  module Command
    module Show
      def parser(opts)
        opts.banner = "Usage: ti show [--full] [ticid]"
        opts.on_head(
          "-f", "--full", "Show long comments in full, don't truncate after the 5th line"){|v|
          options.full= v
        }
      end

      def execute
        t = tic.ticket_show(args[0])
        ticket_show(t, options.full ) if t
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/state.rb
================================================
module TicGitNG
  module Command
    module State
      def parser(opts)
        opts.banner = "Usage: ti state [ticid] state"
      end

      def execute
        if args.size > 1
          tid, new_state = args[0].strip, args[1].strip

          if valid_state?(new_state)
            tic.ticket_change(new_state, tid)
          else
            puts "Invalid State - please choose from: #{joined_states}"
          end
        elsif args.size > 0
          # new state
          new_state = args[0].chomp

          if valid_state?(new_state)
            tic.ticket_change(new_state)
          else
            puts "Invalid State - please choose from: #{joined_states}"
          end
        else
          puts 'You need to at least specify a new state for the current ticket'
          puts "please choose from: #{joined_states}"
        end
      end

      def valid_state?(state)
        available_states.include?(state)
      end

      def available_states
        tic.tic_states.sort
      end

      def joined_states
        available_states.join(', ')
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/sync.rb
================================================
module TicGitNG
  module Command
    module Sync
      def parser(opts)
        opts.banner = "Usage: ti sync [options]"
        opts.on_head(
          "-r REPO", "--repo REPO", "Sync ticgit-ng branch with REPO"){|v|
          options.repo = v
        }
        opts.on_head(
          "-n", "--no-push", "Do not push to the remote repo"){|v|
          options.no_push = true
        }
      end

      def execute
        begin
          if options.repo and options.no_push
            tic.sync_tickets(options.repo, false)
          elsif options.repo
            tic.sync_tickets(options.repo)
          elsif options.no_push
            tic.sync_tickets('origin', false)
          else
            tic.sync_tickets()
          end
        rescue Git::GitExecuteError => e
          if e.message[/does not appear to be a git repository/]
            repo= e.message.split("\n")[0][/^[^:]+/][/"\w+"/].gsub('"','')
            puts "Could not sync because git returned the following error:\n#{e.message.split("\n")[0][/[^:]+$/].strip}"
            exit
          end
        end 
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command/tag.rb
================================================
module TicGitNG
  module Command
    module Tag
      def parser(opts)
        opts.banner = "Usage: ti tag [tic_id] [options] [tag_name] "
        opts.on_head(
          "-d", "--delete",
          "Remove this tag from the ticket"){|v| options.remove = v }
      end

      def execute
        if options.remove
          puts 'remove'
        end

        if ARGV.size > 2 # `ti tag 1234abc tagname1`
          tic.ticket_tag(ARGV[2], ARGV[1].chomp, options)
        elsif ARGV.size == 2 # `ti tag tagname1`
          tic.ticket_tag(ARGV[1], nil, options)
        else
          puts 'You need to at least specify one tag to add'
          puts
          puts usage
        end
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/command.rb
================================================
module TicGitNG
  module Command
    COMMANDS = {}
    DOC = {}

    def self.register(mod_name, doc, *commands)
      autoload(mod_name, "ticgit-ng/command/#{mod_name.downcase}")
      DOC[commands] = doc
      commands.each{|cmd| COMMANDS[cmd] = mod_name }
    end

    register 'Assign', 'Assings a ticket to someone', 'assign'
    register 'Attach', 'Attach file to ticket', 'attach'
    register 'Checkout', 'Checkout a ticket', 'checkout', 'co'
    register 'Comment', 'Comment on a ticket', 'comment'
    register 'Help', 'Show help for a ticgit command', 'help'
    register 'List', 'List tickets', 'list'
#    register 'Milestone', 'List and modify milestones', 'milestone'
    register 'New', 'Create a new ticket', 'new'
    register 'Points', 'Assign points to a ticket', 'points'
    register 'Recent', 'List recent activities', 'recent'
    register 'Show', 'Show a ticket', 'show'
    register 'State', 'Change state of a ticket', 'state'
    register 'Tag', 'Modify tags of a ticket', 'tag'
    register 'Sync', 'Sync tickets', 'sync'
    register 'Init', 'Initialize Ticgit-ng', 'init'

    def self.get(command)
      if mod_name = COMMANDS[command]
        const_get(mod_name)
      end
    end

    def self.usage(action, args)
      option_parser = parser(action, &method(:default_usage))
      option_parser.parse!(args)
      option_parser
    end

    def self.default_usage(o)
      o.banner = "Usage: ti COMMAND [FLAGS] [ARGS]"
      o.top.append ' ', nil, nil
      o.top.append 'The available ticgit commands are:', nil, nil

      sorted_doc = DOC.sort_by do |cmds, doc|
        cmds.sort_by{|cmd| cmd.size }.last
      end
      sorted_doc.each do |commands, doc|
        # get the longest version
        command = commands.sort_by{|cmd| cmd.size }.last
        o.top.append("    %-32s %s" % [command, doc], nil, nil)
      end
    end

    def self.parser(action, &block)
      OptionParser.new do |o|
        o.banner = "Usage: ti #{action} [FLAGS] [ARGS]"

        o.base.append ' ', nil, nil
        o.base.append 'Common options:', nil, nil
        o.on_tail('-v', '--version', 'Show the version number'){
          puts TicGitNG::VERSION
          exit
        }
        o.on_tail('-h', '--help', 'Display this help'){
          puts o
          exit
        }

        if block_given?
          yield(o) if block_given?
          unless o.top.list.empty?
            if action
              o.top.prepend "Options for #{action} command:", nil, nil
              o.top.prepend ' ', nil, nil
            end
          end
        end
      end
    end
  end
end


================================================
FILE: lib/ticgit-ng/comment.rb
================================================
module TicGitNG
  class Comment
    attr_accessor :base, :user, :added, :comment

    def initialize( c, user, time=nil )
      raise unless c
      @comment= c
      @user=user
      @added= time.nil? ? Time.now : time
      self
    end

    def self.read( base, file_name, sha )
      type, date, user = file_name.split('_')

      new( (base.git.gblob(sha).contents rescue nil), user, Time.at(date.to_i) )
    end
  end
end


================================================
FILE: lib/ticgit-ng/ticket.rb
================================================
module TicGitNG
  class Ticket

    attr_reader :base, :opts
    attr_accessor :ticket_id, :ticket_name
    attr_accessor :title, :state, :milestone, :assigned, :opened, :points
    attr_accessor :comments, :tags, :attachments # arrays

    def initialize(base, options = {})
      # FIXME: what/where/who/how changed config to hash?
      if (cfg = base.git.config).is_a? Hash
        options[:user_name] ||= cfg["user.name"]
        options[:user_email] ||= cfg["user.email"]
      else
        options[:user_name] ||= cfg("user.name")
        options[:user_email] ||= cfg("user.email")
      end

      @base = base
      @opts = options || {}

      @state = 'open' # by default
      @comments = []
      @tags = []
      @attachments = []
    end

    def self.create(base, title, options = {}, time=nil)
      t = Ticket.new(base, options)
      t.title = title
      t.ticket_name = self.create_ticket_name(title, time)
      t.save_new
      t
    end

    def self.open(base, ticket_name, ticket_hash, options = {})
      tid = nil

      t = Ticket.new(base, options)
      t.ticket_name = ticket_name

      title, date = self.parse_ticket_name(ticket_name)
      t.opened = date

      ticket_hash['files'].each do |fname, sha|
        if fname == 'TICKET_ID'
          tid = sha
        elsif fname == 'TICKET_TITLE'
          t.title = base.git.gblob(sha).contents
        else
          # matching
          data = fname.split('_')

          case data[0]
          when 'ASSIGNED'
            t.assigned = data[1..-1].join('_')
          when 'ATTACHMENTS'
              #Attachments dir naming format:
              #ticket_name/ATTACHMENTS/123456_jeff.welling@gmail.com_fubar.jpg
              #data[] format:
              #"ATTACHMENTS_1342116799_jeff.welling@gmail.com_Rakefile".split('_')
            filename=File.join( 'ATTACHMENTS', fname.gsub(/^ATTACHMENTS_/,'') )
            t.attachments << TicGitNG::Attachment.new( filename )
          when 'COMMENT'
            t.comments << TicGitNG::Comment.read(base, fname, sha)
          when 'POINTS'
            t.points = base.git.gblob(sha).contents.to_i
          when 'STATE'
            t.state = data[1]
          when 'TAG'
            t.tags << data[1]
          when 'TITLE'
            t.title = base.git.gblob(sha).contents
          end
        end
      end

      if !t.attachments.class==NilClass and t.attachments.size > 1
          t.attachments= t.attachments.sort {|a1, a2| a1.added <=> a2.added }
      end
      t.ticket_id = tid
      t
    end

    def self.parse_ticket_name(name)
      epoch, title, rand = name.split('_')
      title = title.gsub('-', ' ')
      return [title, Time.at(epoch.to_i)]
    end

    # write this ticket to the git database
    def save_new
      base.in_branch do |wd|
        files=[]
        t=nil
        base.logger.puts "saving #{ticket_name}"

        Dir.mkdir(ticket_name)
        Dir.chdir(ticket_name) do
          base.new_file('TICKET_ID', ticket_name)
          files << File.join( ticket_name, 'TICKET_ID' )
          base.new_file('TICKET_TITLE', title)
          files << File.join( ticket_name, 'TICKET_TITLE' )
          base.new_file( (t='ASSIGNED_'+email) , email)
          files << File.join( ticket_name, t )
          base.new_file( (t='STATE_'+state) , state)
          files << File.join( ticket_name, t )
          base.new_file('TITLE', title)
          files << File.join( ticket_name, 'TITLE' )

          # add initial comment
          #COMMENT_080315060503045__schacon_at_gmail
          if opts[:comment]
            base.new_file(t=comment_name(email), opts[:comment])
            files << File.join( ticket_name, t )
          end

          # add initial tags
          if opts[:tags] && opts[:tags].size > 0
            opts[:tags] = opts[:tags].map { |t| t.strip }.compact
            opts[:tags].each do |tag|
              if tag.size > 0
                tag_filename = 'TAG_' + Ticket.clean_string(tag)
                if !File.exists?(tag_filename)
                  base.new_file(tag_filename, tag_filename)
                  files << File.join( ticket_name, tag_filename )
                end
              end
            end
          end
        end
        files.each {|file|
          base.git.add file
        }
        base.git.commit("added ticket #{ticket_name}")
      end
      # ticket_id
    end

    def self.clean_string(string)
      string.downcase.gsub(/[^a-z0-9]+/i, '-')
    end

    def add_comment(comment)
      return false if !comment
      base.in_branch do |wd|
        t=nil
        Dir.chdir(ticket_name) do
          base.new_file(t=comment_name(email), comment)
        end
        base.git.add File.join(ticket_name, t)
        base.git.commit("added comment to ticket #{ticket_name}")
      end
      @comments << TicGitNG::Comment.new( comment, email )
      self
    end

    def add_attach( base, filename, time=nil )
        filename=File.expand_path(filename)
        #FIXME Refactor -- Attachment.new should be called from Ticket.rb
        #               -- Attachment filename creation should be handled
        #                  by the Attachment.rb code
        base.in_branch do |wd|
            attachments << (a=TicGitNG::Attachment.create( filename, self, time))
            base.git.add File.join( ticket_name, a.filename )
            base.git.commit("added attachment #{File.basename(a.filename)} to ticket #{ticket_name}")
        end
        if attachments.class!=NilClass and attachments.size > 1
            @attachments=attachments.sort {|a1,a2| a1.added <=> a2.added }
        end
        self
    end

    #file_id can be one of:
    #  - An index number of the attachment (1,2,3,...)
    #  - A filename (fubar.jpg)
    #  - nil (nil) means use the last attachment
    #
    #if new_filename is nil, use existing filename
    def get_attach file_id=nil, new_filename=nil
        attachment=nil
        pwd=Dir.pwd
        base.in_branch do |wd|
            if file_id.to_i==0 and (file_id=="0" or file_id.class==Fixnum)
                if !attachments[file_id.to_i].nil?
                    attachment= attachments[0]
                else
                    puts "No attachments match file id #{file_id}"
                    exit 1
                end
            elsif file_id.to_i  > 0
                if !attachments[file_id.to_i].nil?
                    attachment= attachments[file_id.to_i]
                else
                    puts "No attachments match file id #{file_id}"
                    exit 1
                end
            else
                #find attachment by filename
                attachments.each {|a|
                    attachment=a if a.attachment_name==file_id
                }
                if attachment.nil?
                  puts "No attachments match filename #{file_id}"
                  exit 1
                end
            end

            if !new_filename
                #if no filename is specified...
                filename= attachment.attachment_name
            else
                #if there is a new_filename given
                if File.exist?( new_filename ) and File.directory?( new_filename )
                    #if it is a directory, not a filename
                    filename= File.join(
                        new_filename,
                        File.basename(attachment.attachment_name)
                    )
                else
                    #if it is a filename, not a dir
                    filename= new_filename
                end
            end

            unless File.exist?( File.dirname(filename) )
                FileUtils.mkdir_p( File.dirname(filename) )
            end
            #save attachment [as new_filename]
            t=File.join( ticket_name, attachment.filename )
            unless filename[/^\//]
                filename=File.join( pwd, filename )
            end
            FileUtils.cp( t, filename )
        end
        self
    end

    def change_state(new_state)
      return false if !new_state
      return false if new_state == state
      t=nil

      base.in_branch do |wd|
        Dir.chdir(ticket_name) do
          base.new_file(t='STATE_' + new_state, new_state)
        end
        base.git.remove(File.join(ticket_name,'STATE_' + state))
        base.git.add File.join(ticket_name, t)
        base.git.commit("added state (#{new_state}) to ticket #{ticket_name}")
      end
      @state=new_state
      self
    end

    def change_assigned(new_assigned)
      new_assigned ||= email
      old_assigned= assigned || ''
      return false if new_assigned == old_assigned

      base.in_branch do |wd|
        t=nil
        Dir.chdir(ticket_name) do
          base.new_file(t='ASSIGNED_' + new_assigned, new_assigned)
        end
        base.git.remove(File.join(ticket_name,'ASSIGNED_' + old_assigned))
        base.git.add File.join(ticket_name,t)
        base.git.commit("assigned #{new_assigned} to ticket #{ticket_name}")
      end
      @assigned=new_assigned
      self
    end

    def change_points(new_points)
      return false if new_points == points

      base.in_branch do |wd|
        Dir.chdir(ticket_name) do
          base.new_file('POINTS', new_points)
        end
        base.git.add File.join(ticket_name, 'POINTS')
        base.git.commit("set points to #{new_points} for ticket #{ticket_name}")
      end
      @points=new_points
      self
    end

    def add_tag(tag)
      return false if !tag
      files=[]
      added = false
      tags = tag.split(',').map { |t| t.strip }
      base.in_branch do |wd|
        Dir.chdir(ticket_name) do
          tags.each do |add_tag|
            if add_tag.size > 0
              tag_filename = 'TAG_' + Ticket.clean_string(add_tag)
              if !File.exists?(tag_filename)
                base.new_file(tag_filename, tag_filename)
                files << File.join( ticket_name, tag_filename )
                added = true
              end
            end
          end
        end
        if added
          files.each {|file|
            base.git.add file
          }
          base.git.commit("added tags (#{tag}) to ticket #{ticket_name}")
        end
      end
      tags.each {|tag|
        @tags << tag
      }
      self
    end

    def remove_tag(tag)
      return false if !tag
      removed = false
      tags = tag.split(',').map { |t| t.strip }
      base.in_branch do |wd|
        tags.each do |add_tag|
          tag_filename = File.join(ticket_name, 'TAG_' + Ticket.clean_string(add_tag))
          if File.exists?(tag_filename)
            base.git.remove(tag_filename)
            removed = true
          end
        end
        if removed
          base.git.commit("removed tags (#{tag}) from ticket #{ticket_name}")
        end
      end
      @tags.delete_if {|t| t==tag }
      self
    end

    def path
      File.join(state, ticket_name)
    end

    def comment_name(email)
      'COMMENT_' + Time.now.to_i.to_s + '_' + email
    end

    def email
      opts[:user_email] || 'anon'
    end

    def assigned_name
      assigned.split('@').first rescue ''
    end

    def self.create_ticket_name(title, time=nil)
      [time.nil? ? Time.now.to_i.to_s : time, Ticket.clean_string(title), rand(999).to_i.to_s].join('_')
    end

    def create_attachment_name( attachment_name, time=nil )
        raise ArgumentError, "create_attachment_name( ) only takes a string" unless attachment_name.class==String
        if time
            if time.to_i == 0
                raise ArgumentError, "argument 'time' is not valid"  unless time.class==Fixnum
            else
                time=time.to_i
            end
        end
        time or time=Time.now.to_i
        time.to_s+'_'+email+'_'+File.basename( attachment_name )
    end
    def ==(ticket2)
        self.instance_variables.each {|instance_var|
            unless send( instance_var.gsub('@','').to_sym ) == ticket2.instance_eval {send(instance_var.gsub('@','').to_sym)}
                return false
            end
        }
        return true
    end
  end
end


================================================
FILE: lib/ticgit-ng/version.rb
================================================
module TicGitNG
  VERSION = '1.0.2.18'
end


================================================
FILE: lib/ticgit-ng.rb
================================================
require 'fileutils'
require 'logger'
require 'optparse'
require 'ostruct'
require 'set'
require 'yaml'
require 'pp'

# Add the directory containing this file to the start of the load path if it
# isn't there already.
$:.unshift(File.dirname(__FILE__)) unless
  $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))

require 'rubygems'
# requires git >= 1.0.5
require 'git'

#Only redefine if we are not using 1.9
unless (defined?(RbConfig) ? RbConfig : Config)::CONFIG["ruby_version"][/^\d\.9/]
  # FIXME: Monkeypatch git until fixed upstream
  module Git
    class Lib
      def config_get(name)
        do_get = lambda do |x|
          command('config', ['--get', name])
        end
        if @git_dir
          Dir.chdir(@git_dir, &do_get)
        else
          build_list.call
        end
      end
    end
  end
end

require 'ticgit-ng/base'
require 'ticgit-ng/cli'
require 'ticgit-ng/attachment'
module TicGitNG
  autoload :VERSION, 'ticgit-ng/version'
  autoload :Comment, 'ticgit-ng/comment'
  autoload :Ticket, 'ticgit-ng/ticket'

  # options
  #   :logger            => Logger.new(STDOUT)
  #   :tic_dir           => "~/.#{ which_branch?() }"
  #   :working_directory => File.expand_path(File.join(@tic_dir, proj, 'working'))
  #   :index_file        => File.expand_path(File.join(@tic_dir, proj, 'index'))
  #   :init              => Boolean -- if true, allow initializing ticgit
  def self.open(git_dir, options = {})
    Base.new(git_dir, options)
  end

  class OpenStruct < ::OpenStruct
    def to_hash
      @table.dup
    end
  end
end


================================================
FILE: note/IMPLEMENT
================================================
~/.ticgit/HEAD -> branch name
~/.ticgit/CHECKOUT -> current ticket
~/.ticgit/USER -> schacon / email

ticgit/master

  open/
    080315060503_my_first_ticket_8956
	      TICKET_ID - this is filled with ts + random, the sha is 
	            used as the ticket handle
        ASSIGNED_schacon
	      COMMENT_080315060503045__schacon_at_gmail
	      COMMENT_080315060503045__schacon
	      COMMENT_080315060503045__someoneelse
	      COMMENT_080315060503045__schacon
	      COMMENT_080315060503045__someoneelse
	      COMMENT_080315060503045__schacon
	      TAG_something
	      TAG_my_tag
	      TAG_again
    080315140503_my_other_ticket_3982
  resolved/
    080215134503_easy_fix_9386
  invalid/
    080211134503_everything_is_broke_0183
  closed/
    080112153503_needs_fixing_3984
    080314134501_needs_fixing_2934
    080314040501_needs_fixing_9486

ticgit/devbranch


================================================
FILE: note/NOTES
================================================

* store the tickets (stories, cards, bugs) - in a subdir of the repo, or a branch?

* merge strategy - if in branch, we can automate, if in subdir, must be human readable

* branch work?
  - if closed in a branch, how do we handle that when branch merged? (seperate command)
  $ git merge branch_name; tic merge

* Lighthouse integration
  $ tic sync

States - open, resolved, invalid, hold

Assignment - user/email


USAGE
==========

tic recent

tic list (all open)
tic list state:closed
tic list tag:bug
tic list git:treeish

tic find assigned:me state:open date:"this week"

tic milestone
tic milestone migration1 (list tickets)
tic milestone -n migration1 3/4/08 (new milestone)
tic milestone -a {1} (add ticket to milestone)
tic milestone -d migration1 (delete)

tic status (tics grouped by milestone, stats)

tic tag (show tags)
tic tag {1} -n new_tag
tic tag {1} -d tag_name
tic tag -D tag_name
tic tag -r old_tag new_tag (rename tag)

tic show {1} 
tic show {1} -c (comments)
tic show {1} -t (tasks)
tic show {1} -a (attachments)

tic sync (lighthouse)

tic checkout {1} - checks out a bug for time tracking - says you're working on it
tic assign {1} (person/partial - defaults to self) [-c] (and checkout)
tic state {1} resolved [branch - defaults to current, only shows in this branch)

tic attach {1} file.ext -m "file description"
tic attach {1} 
tic attach {1} {attach-id} > file

tic comment {1} -m "I think this might be done"
tic comment --recent

tic new [prompts for info] (title, comment, tags, [state, assigned])
tic new -t bug "the thingy doesnt work" (treeish - defaults to current branch)

??

tic branch (shows tic branches - automatically created when using tic in a git branch)
tic merge [git_branch]  (brings in all bug states from branch)
tic merge --preview [git_branch]  (doesn't do the merge, but shows what it would do)

tic git-commit "message" (commits git and attaches tic number)

-- later? --

tic task
tic task new -m "my new task"


================================================
FILE: note/OUTPUT
================================================
OUTPUT
==========

> tic recent

1 34j238	this one is important   03/05  comment added
2 3kd898  anther bug              03/05  comment added
3 3kd898  anther bug              03/04  new ticket created
4 as8fk5  my first ticket	        02/01  tag added


> tic list
# on branch 'master'
1 34j238	this one is important 	open	  schacon (bug, accepted)
2 3kd898	anther bug	          	open	  schacon (bug)
3 as8fk5	my first ticket		      closed	nickh68 (bug, dead)


> tic list state:closed
# on branch 'master'
1 as8fk5	my first ticket		      closed	nickh68 (bug, dead)


> tic milestone
tix	ms		date		left
-----------------------------------------------
  3	 migration1	  03/15/08	 35 days
 18	 mall_network	04/15/08	 65 days
 87	 future       05/30/08	135 days


> tic milestone migration1 (list tickets)

|###########################-----------|
 open:   3  closed:  10  progress:  80%

* Open *
34j238	this one is important 	open	schacon (bug, accepted)
3kd898	anther bug		          open	schacon (bug)
as8fk5	open tick               open	nickh68 (bug, dead)

* Closed *
34j238	this one is important 	closed	schacon (bug, accepted)
3kd898	anther bug		          closed	schacon (bug)
as8fk5	open tick		            closed	nickh68 (bug, dead)


> tic tag 
bug		    35
accepted	20
dead		   8

> tic show {1} 

Ticket : 34j238
Title  : The Sweetest Ticket Ever

Assign : Scott Chacon <schacon@gmail.com>
State  : OPEN
Tags   : bug, accepted, sweet, feature
Date   : 03/01/08  (two weeks ago)

Attachments : 2  
329jd2 patch1.txt - some description
7sjhe3 patch2.txt - some other description

Recent Comments :
03/18 schacon - why do you think this is still open
03/14 schacon - why do you think this is still open -...(more)
03/12 schacon - another comment on the ticket that is...(more)
02/01 schacon - opening the ticket
(12 more comments)

# `tic show 34j238 -c` for more comments
# `tic show 34j238 -a` for more attachment detail

> tic checkout {1}
you are now working on tic 34j238, "The Sweetest Ticket Ever"


================================================
FILE: note/TODO
================================================
link to another ticket (child tickets)

Merge

link to a git object

Web UI

TicGit goes up directories until it finds .git dir

Ticket
- remove ticket ( git.remove(ticket_dir, :recursive => true) )

Color Output + Paging long results

Attachments
  - add
  - download    

Milestones

Tags
  * show all tags
  * rename tag
  * delete tag
  * tag multiple tics
  

================================================
FILE: spec/attachments_spec.rb
================================================
require File.dirname(__FILE__) + "/spec_helper"

describe TicGitNG::Attachment do
  include TicGitNGSpecHelper

  before(:all) do
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
  end

  after(:all) do
    Dir.glob(File.expand_path("~/.ticgit-ng/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("~/.ticgit/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("/tmp/ticgit-ng-*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
  end
  #To make sure attachments[] isn't loaded randomly and that we're aren't just getting 
  #lucky this time around, run the test 100 times in a loop.
  it "should sort attachments[] chronologically, not randomly" do
      #FIXME implementation failure
      #Does not properly detect randomized loads
      #Test with and without TicGitNG.open
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
      5.times do
          #setup git repo
          git_dir= setup_new_git_repo
          base= TicGitNG.open( git_dir, test_opts )
          #add ticket
          tic= base.ticket_new('new ticket')
          #add 5 attachments
          5.times do |i|
              #FIXME attahcments must not be added at the exact same time
              attachment_fname= File.join( Dir.mktmpdir('to_attach'), "fubar.txt#{i}" ) 
              new_file( attachment_fname, "content#{i}" )
              tic= base.ticket_attach( attachment_fname, tic.ticket_id, time_skew() )
          end
          tic.attachments.size.should == 5
          #re-read the ticket to read the attachments
          #check the sort
          last=nil
          tic.attachments.each {|a|
              unless last.nil?
                  a.added.should >= last.added
              end
              last=a
          }
          base= TicGitNG.open( git_dir, test_opts )
          #check attachments are in order
          tic= base.ticket_show( tic.ticket_id )
          #check the sort
          last=nil
          tic.attachments.each {|a|
              unless last.nil?
                  a.added.should >= last.added
              end
              last=a
          }
      end
    end
  end

  it "should be able to add an attachment to a ticket" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        #create a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        new_file( attachment_fname=File.join( to_attach, 'fubar.txt' ), "I am the contents of the attachment" )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname, tic.ticket_id ) 
        #check that the file was attached
        tic.attachments.map {|a|
            a.filename.split('_').pop=='fubar.txt'
        }.index( true ).should_not == nil
    end
  end

  it "should support multiple attachments per ticket" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        #create a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        new_file( attachment_fname1=File.join( to_attach, 'fubar.txt' ), "I am the contents of the attachment" )
        new_file( attachment_fname2=File.join( to_attach, 'fubar.jpg' ), "More contents!" )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id ) 
        tic= @ticgitng.ticket_attach( attachment_fname2, tic.ticket_id )
        tic= @ticgitng.ticket_show( tic.ticket_id )
        #check that the file was attached
        cond_1=false
        cond_2=false
        tic.attachments.map {|a|
            if a.filename.split('_').pop=='fubar.txt'
                cond_1=true
            elsif a.filename.split('_').pop=='fubar.jpg'
                cond_2=true
            end
        }
        [cond_1,cond_2].uniq.size.should == 1
        cond_1.should == true
    end
  end
  it "should be able to see an attachment that has been added to a ticket" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        #create a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        contents="I am the contents of the attachment"
        new_file( attachment_fname=File.join( to_attach, 'fubar.txt' ), contents )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname, tic.ticket_id ) 
        #check that the file was attached with details
        tic.attachments.size.should == 1
        tic.attachments[0].attachment_name.should == 'fubar.txt'
        tic.email.should == tic.attachments[0].user
        tic.base.in_branch do |wd|
            read_line_of(File.join( tic.ticket_name, tic.attachments[0].filename)).strip.should == contents 
        end
    end
  end
  it "should be able to get the attachment based on 'AttachmentID'" do     #AttachmentID is a number
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        #create a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        content1="More contents!"
        new_file( attachment_fname0=File.join( to_attach, 'fubar.txt' ), content0 )
        new_file( attachment_fname1=File.join( to_attach, 'fubar.jpg' ), content1 )
        #attach the file
        #FIXME time_skew randomizes the ordering of the attachments
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id, Time.now.to_i ) 
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id, Time.now.to_i+500)
        #get attachment
        new_filename0= File.join( 
            File.expand_path(Dir.mktmpdir('ticgit-ng-get_attachment-test')),
            'new_filename.txt' )
        new_filename1= File.join( 
            File.expand_path(Dir.mktmpdir('ticgit-ng-get_attachment-test')),
            'new_filename.jpg' )
        #check contents
        @ticgitng.ticket_get_attachment( 0, new_filename0, tic.ticket_id )
        File.exist?( new_filename0 ).should == true
        read_line_of( new_filename0 ).strip.should == content0
        @ticgitng.ticket_get_attachment( 1, new_filename1, tic.ticket_id )
        File.exist?( new_filename1 ).should == true
        read_line_of( new_filename1 ).strip.should == content1
    end
  end

  it "should be able to get the attachment based on filename" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        # a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        content1="More contents!"
        new_file( attachment_fname0=File.join( to_attach, 'fubar.txt' ), content0 )
        new_file( attachment_fname1=File.join( to_attach, 'fubar.jpg' ), content1 )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id ) 
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id )
        #get attachment
        new_filename0= File.join( 
            File.expand_path(Dir.mktmpdir('ticgit-ng-get_attachment-test')),
            'new_filename.txt' )
        new_filename1= File.join(
            File.expand_path(Dir.mktmpdir('ticgit-ng-get_attachment-test')),
            'new_filename.jpg' )
        #check contents
        @ticgitng.ticket_get_attachment( 'fubar.txt', new_filename0, tic.ticket_id )
        #test getting a file to a directory by specifying new-filename as a directory
        @ticgitng.ticket_get_attachment( 'fubar.txt', File.dirname(new_filename0), tic.ticket_id )
        File.exist?( new_filename0 ).should == true
        File.exist?( File.join(File.dirname(new_filename0), 'fubar.txt') ).should==true
        read_line_of( new_filename0 ).strip.should == content0
        read_line_of( File.join(File.dirname(new_filename0), 'fubar.txt') ).strip.should == content0
        @ticgitng.ticket_get_attachment( 'fubar.jpg', new_filename1, tic.ticket_id )
        #test getting a file to a directory by specifying new-filename as a directory
        @ticgitng.ticket_get_attachment( 'fubar.jpg', File.dirname(new_filename1), tic.ticket_id )
        File.exist?( new_filename1 ).should == true
        File.exist?( File.join(File.dirname(new_filename1), 'fubar.jpg' ) ).should==true
        read_line_of( new_filename1 ).strip.should == content1
        read_line_of( File.join(File.dirname(new_filename1), 'fubar.jpg') ).strip.should==content1
    end
  end
  it "should only have valid filenames that begin with 'ATTACHMENTS/'" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        # a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        content1="More contents!"
        new_file( attachment_fname0=File.join( to_attach, 'fubar.txt' ), content0 )
        new_file( attachment_fname1=File.join( to_attach, 'fubar.jpg' ), content1 )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id, Time.now.to_i) 
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id, Time.now.to_i + 60)
        tic.attachments.each {|a| a.filename[/^ATTACHMENTS\//].nil?.should == false }
    end
  end
  it "should be able to list the attachments on the current ticket" do  #`ti attach list`
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        # a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        content1="More contents!"
        new_file( attachment_fname0=File.join( to_attach, 'fubar.txt' ), content0 )
        new_file( attachment_fname1=File.join( to_attach, 'fubar.jpg' ), content1 )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id, Time.now.to_i ) 
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id, Time.now.to_i+60 )
        tic.attachments.size.should == 2
        tic.attachments[0].attachment_name.should == 'fubar.txt'
        tic.attachments[1].attachment_name.should == 'fubar.jpg'
        tic.attachments[0].user.should_not == nil
        tic.attachments[1].user.should_not == nil
    end
  end
  it "should not change the attachment that has been attached if the local file changes" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        # a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        content1="More contents!"
        new_file( attachment_fname0=File.join( to_attach, 'fubar.txt' ), content0 )
        new_file( attachment_fname1=File.join( to_attach, 'fubar.jpg' ), content1 )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id, Time.now.to_i ) 
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id, Time.now.to_i+60 )
        File.open( attachment_fname0, 'a' ) {|f|
            f.puts "I am a second line in the first attachment!"
        }
        File.open( attachment_fname1, 'a' ) {|f|
            f.puts "I am a second line in the second attachment!"
        }
        tic.base.in_branch {|wd|
            File.read( File.join( 
                                 tic.ticket_name,
                                 tic.attachments[0].filename 
                                )
                     ).strip.split("\n").size.should==1
            File.read( File.join(
                                 tic.ticket_name,
                                 tic.attachments[1].filename 
                                )
                     ).strip.split("\n").size.should==1
        }
        File.read( attachment_fname0 ).strip.split("\n").size.should==2
        File.read( attachment_fname1 ).strip.split("\n").size.should==2
        #FIXME checkout the attachments to see if they have changed
    end
  end
  it "should not explode violently when retrieving an attachment from no attachments" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        lambda {
            tic.attachments[0]
        }.should_not raise_error
        lambda {
            @ticgitng.ticket_get_attachment( 0, nil, tic.ticket_id )
        }.should raise_error(SystemExit)
    end
  end
  it "should be able to handle filenames with '_' in them -- '_' is a special char" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        #Split the attachment basename, delete the first two (time,user), remianing is filename
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        # a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        new_file( attachment_fname0=File.join( to_attach, 'fu_bar.txt' ), content0 )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id, Time.now.to_i ) 
        tic.attachments[0].attachment_name.should == 'fu_bar.txt'
    end
  end
  it "should allow the attaching of multiple filenames with the same name" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        # a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        content1="More contents!"
        new_file( attachment_fname0=File.join( to_attach, 'fubar.jpg' ), content0 )
        new_file( attachment_fname1=File.join( to_attach, 'fubar.jpg' ), content1 )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id, Time.now.to_i ) 
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id, Time.now.to_i+60 )
        tic.attachments[0].attachment_name.should == 'fubar.jpg'
        tic.attachments[1].attachment_name.should == 'fubar.jpg'
    end
  end
  it "should not explode violently when a duplicate file is attached" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        # a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        new_file( attachment_fname0=File.join( to_attach, 'fubar.jpg' ), content0 )
        new_file( attachment_fname1=File.join( to_attach, 'fubar.jpg' ), content0 )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id, Time.now.to_i ) 
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id, Time.now.to_i+60 )
        tic.attachments[0].attachment_name.should == 'fubar.jpg'
        tic.attachments[1].attachment_name.should == 'fubar.jpg'
    end
  end
  it "should be able to properly get attachments with '_' in the filename" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        tic= @ticgitng.ticket_new('my_delicious_ticket')
        # a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        content0="I am the contents of the attachment"
        content1="More contents!"
        new_file( attachment_fname0=File.join( to_attach, 'fu_bar_baz_ted_zim.txt' ), content0 )
        new_file( attachment_fname1=File.join( to_attach, 'fu_bar_baz_ted_zim*$@#.jpg' ), content1 )
        #attach the file
        tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id ) 
        tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id )
        #get attachment
        new_filename0= File.join( 
            File.expand_path(Dir.mktmpdir('ticgit-ng-get_attachment-test')),
            'new_filename.txt' )
        new_filename1= File.join(
            File.expand_path(Dir.mktmpdir('ticgit-ng-get_attachment-test')),
            'new_filename.jpg' )
        #check contents
        @ticgitng.ticket_get_attachment( 'fu_bar_baz_ted_zim.txt', new_filename0, tic.ticket_id )
        @ticgitng.ticket_get_attachment( 'fu_bar_baz_ted_zim.txt', File.dirname(new_filename0), tic.ticket_id )
        File.exist?( new_filename0 ).should == true
        File.exist?( File.join(File.dirname(new_filename0), 'fu_bar_baz_ted_zim.txt') ).should==true
        @ticgitng.ticket_get_attachment( 'fu_bar_baz_ted_zim*$@#.jpg', new_filename1, tic.ticket_id )
        @ticgitng.ticket_get_attachment( 'fu_bar_baz_ted_zim*$@#.jpg', File.dirname(new_filename1), tic.ticket_id )
        File.exist?( new_filename1 ).should == true
        File.exist?( File.join(File.dirname(new_filename1), 'fu_bar_baz_ted_zim*$@#.jpg' ) ).should==true
    end
  end
  it "should fail gracefully when trying to get a filename that does not exist" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
      lambda {
          tic= @ticgitng.ticket_new('my_delicious_ticket')
          # a file to attach
          to_attach= Dir.mktmpdir('to_attach')
          content0="I am the contents of the attachment"
          content1="More contents!"
          new_file( attachment_fname0=File.join( to_attach, 'fubar.txt' ), content0 )
          new_file( attachment_fname1=File.join( to_attach, 'fubar.jpg' ), content1 )
          #attach the file
          tic= @ticgitng.ticket_attach( attachment_fname0, tic.ticket_id )
          tic= @ticgitng.ticket_attach( attachment_fname1, tic.ticket_id )
          #get attachment
          new_filename0= File.join(
              File.expand_path(Dir.mktmpdir('ticgit-ng-get_attachment-test')),
              'new_filename.txt' )
          new_filename1= File.join(
              File.expand_path(Dir.mktmpdir('ticgit-ng-get_attachment-test')),
              'new_filename.jpg' )
          #check contents
          @ticgitng.ticket_get_attachment( 'fake_file.txt', new_filename0, tic.ticket_id )
        }.should raise_error SystemExit
    end
  end
end


================================================
FILE: spec/base_spec.rb
================================================
require File.dirname(__FILE__) + "/spec_helper"

describe TicGitNG::Base do
  include TicGitNGSpecHelper

  before(:all) do
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
  end

  after(:all) do
    Dir.glob(File.expand_path("~/.ticgit-ng/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("~/.ticgit/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("/tmp/ticgit-ng-*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
  end

  it "should fail gracefully when init-ing if git has no commits" do
    tempdir = Dir.mktmpdir
    Dir.chdir(tempdir) do
      git = Git.init
    end
    opts=test_opts
    lambda {
      TicGitNG.open( tempdir, opts )
    }.should raise_error SystemExit
  end

  it "should have 4 ticket states" do
    @ticgitng.tic_states.size.should eql(4)
  end

  it "should be able to create new tickets" do
    @ticgitng.tickets.size.should eql(0)
    @ticgitng.ticket_new('my new ticket').should be_an_instance_of(TicGitNG::Ticket)
    @ticgitng.tickets.size.should eql(1)
  end

  it "should be able to list existing tickets" do
    @ticgitng.ticket_new('my second ticket').should be_an_instance_of(TicGitNG::Ticket)
    list = @ticgitng.ticket_list
    list.first.should be_an_instance_of(TicGitNG::Ticket)
    list.size.should eql(2)
  end

  it "should be able to change the state of a ticket" do
    tic = @ticgitng.ticket_list.first
    @ticgitng.ticket_change('resolved', tic.ticket_id)
    tic = @ticgitng.ticket_show(tic.ticket_id)
    tic.state.should eql('resolved')
  end

  it "should not be able to change the state of a ticket to something invalid" do
    tic = @ticgitng.ticket_list.first
    @ticgitng.ticket_change('resolve', tic.ticket_id)
    tic = @ticgitng.ticket_show(tic.ticket_id)
    tic.state.should_not eql('resolve')
  end

  it "should be able to change to whom the ticket is assigned" do
    tic = @ticgitng.ticket_list.first
    @ticgitng.ticket_assign('pope', tic.ticket_id)
    tic = @ticgitng.ticket_show(tic.ticket_id)
    tic.assigned.should eql('pope')
  end

  it "should not be able to change to whom the ticket is assigned if it is already assigned to that user" do
    tic = @ticgitng.ticket_list.first
    tic_id = tic.ticket_id
    lambda {
      @ticgitng.ticket_assign(tic.assigned, tic_id)
      @ticgitng.ticket_show(tic_id)
    }.should_not change(@ticgitng.ticket_recent(tic_id), :size)
  end

  it "should default to the current user when changing to whom the ticket is assigned" do
    tic = @ticgitng.ticket_list.first
    @ticgitng.ticket_checkout(tic.ticket_id)
    @ticgitng.ticket_assign()
    tic = @ticgitng.ticket_show(tic.ticket_id)
    tic.assigned.should eql(tic.email)
  end

  it "should only show open tickets by default" do
    @ticgitng.ticket_new('my third ticket')
    tics = @ticgitng.ticket_list
    states = tics.map { |t| t.state }.uniq
    states.size.should eql(1)
    states.first.should eql('open')
  end

  it "should be able to filter tickets on state" do
    tics = @ticgitng.ticket_list(:state => 'resolved')
    tics.size.should eql(1)
    tics = @ticgitng.ticket_list(:state => 'open')
    tics.size.should eql(2)
  end

  it "should be able to save and recall filtered ticket lists" do
    tics = @ticgitng.ticket_list(:state => 'resolved', :save => 'resolve')
    tics.size.should eql(1)
    rtics = @ticgitng.ticket_list(:saved => 'resolve')
    tics.size.should eql(1)
  end

  it "should be able to comment on tickets" do
    t = @ticgitng.ticket_new('my fourth ticket')
    t.comments.size.should eql(0)

    @ticgitng.ticket_comment('my new comment', t.ticket_id)
    t = @ticgitng.ticket_show(t.ticket_id)
    t.comments.size.should eql(1)
    t.comments.first.comment.should eql('my new comment')
  end

  it "should retrieve specific tickets" do
    tid = @ticgitng.ticket_list.last.ticket_id
    tic = @ticgitng.ticket_show(tid)
    tic.ticket_id.should eql(tid)
  end

  it "should be able to checkout a ticket" do
    tid = @ticgitng.ticket_list.last.ticket_id
    @ticgitng.ticket_checkout(tid)
    @ticgitng.ticket_show.ticket_id.should eql(tid)
  end

  it "should resolve partial shas into ticket" do
    tid = @ticgitng.ticket_list.last.ticket_id
    @ticgitng.ticket_checkout(tid[0, 5])
    @ticgitng.ticket_show.ticket_id.should eql(tid)

    @ticgitng.ticket_checkout(tid[0, 20])
    @ticgitng.ticket_show.ticket_id.should eql(tid)
  end

  it "should resolve order number from most recent list into ticket" do
    tics = @ticgitng.ticket_list(:state => 'open')
    @ticgitng.ticket_show('1').ticket_id.should eql(tics[0].ticket_id)
    @ticgitng.ticket_show('2').ticket_id.should eql(tics[1].ticket_id)
  end

  it "should be able to tag a ticket" do
    t = @ticgitng.ticket_list.last
    t.tags.size.should eql(0)
    @ticgitng.ticket_tag('newtag', t.ticket_id)
    t = @ticgitng.ticket_show(t.ticket_id)
    t.tags.size.should eql(1)
    t.tags.first.should eql('newtag')
  end

  it "should not be able to tag a ticket with a blank tag" do
    t = @ticgitng.ticket_new('my fourth ticket', :tags => [' '])
    t.tags.size.should eql(0)

    @ticgitng.ticket_tag(' ', t.ticket_id)
    t = @ticgitng.ticket_show(t.ticket_id)
    t.tags.size.should eql(0)

    @ticgitng.ticket_tag('', t.ticket_id)
    t = @ticgitng.ticket_show(t.ticket_id)
    t.tags.size.should eql(0)

    @ticgitng.ticket_tag(',mytag', t.ticket_id)
    t = @ticgitng.ticket_show(t.ticket_id)
    t.tags.size.should eql(1)
    t.tags.first.should eql('mytag')
  end

  it "should be able to remove a tag from a ticket" do
    t = @ticgitng.ticket_new('my next ticket', :tags => ['scotty', 'chacony'])
    t.tags.size.should eql(2)

    o=OpenStruct.new
    o.remove=true
    @ticgitng.ticket_tag('scotty', t.ticket_id, o)
    t.tags.size.should eql(2)
    t.tags.first.should eql('chacony')
  end

  it "should save state to disk after a new ticket" do
    time = File.lstat(@ticgitng.state).mtime.to_i
    sleep 1
    t = @ticgitng.ticket_new('my next ticket', :tags => ['scotty', 'chacony'])
    File.lstat(@ticgitng.state).mtime.to_i.should_not eql(time)
  end

  it "should be able to change the points of a ticket" do
    @ticgitng.ticket_new('my new ticket')
    tic = @ticgitng.ticket_list.first
    tic.state.should_not == 3
    @ticgitng.ticket_points(3, tic.ticket_id)
    tic = @ticgitng.ticket_show(tic.ticket_id)
    tic.points.should == 3
  end

  it "should detect the ticgit branch when the repository is moved" do
    #create git dir
      #done in before(:all) block
    #create some tickets
    tic=@ticgitng.ticket_new('my new ticket')
    #move the git dir
    FileUtils.mv( @path, @path+'1' )
    #test that the program does not raise SystemExit
    opts=test_opts
    opts[:init]=false
    lambda {
        @ticgitng=TicGitNG.open( @path+'1', opts )
    }.should_not raise_error SystemExit
  end

  it "should use the same email that git provides" do
    #This is necessary because the other specs depend
    #on the side effects of one another, but those 
    #side effects are detrimental to this spec so
    #we initialize things again for a clean slate.
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
    tic=@ticgitng.ticket_new('my new ticket')
    tic.email.should == @ticgitng.git.lib.config_get('user.email')
  end

  it "should be able to use '_' in assigning" do
    #This is necessary because the other specs depend
    #on the side effects of one another, but those
    #side effects are detrimental to this spec so
    #we initialize things again for a clean slate.
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
    tic=@ticgitng.ticket_new('my new ticket')
    tic=@ticgitng.ticket_assign( 'some_random_user', tic.ticket_id )
    tic=@ticgitng.ticket_show( tic.ticket_id )
    tic.assigned.should == 'some_random_user'
  end

  it "should return an updated ticket for each of the ticket_* methods" do
    #This is necessary because the other specs depend
    #on the side effects of one another, but those
    #side effects are detrimental to this spec so
    #we initialize things again for a clean slate.
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
    num_of_methods= @ticgitng.methods.collect {|m|
      m if m[/^ticket_/]
    }.compact.size.-(1).should == 12
    #ticket_new, ticket_points, ticket_tag
    ticket=@ticgitng.ticket_new('my new ticket')
    ticket.class.should == TicGitNG::Ticket
    ticket.title.should == 'my new ticket'
    ticket=@ticgitng.ticket_points( 1337, ticket.ticket_id )
    ticket.class.should == TicGitNG::Ticket
    ticket.points.should == 1337
    ticket=@ticgitng.ticket_tag( 'fubar', ticket.ticket_id )
    ticket.class.should == TicGitNG::Ticket
    ticket.tags.size.should == 1
    ticket.tags[0].should == 'fubar'
    #ticket_attach, ticket_get_attachment,
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
        #create a file to attach
        to_attach= Dir.mktmpdir('to_attach')
        new_file( attachment_fname=File.join( to_attach, 'fubar.txt' ), "I am the contents of the attachment" )
        #attach the file
        ticket= @ticgitng.ticket_attach( attachment_fname, ticket.ticket_id )
        ticket.class.should == TicGitNG::Ticket
        ticket.attachments.size.should == 1
        ticket.attachments[0].attachment_name.should == 'fubar.txt'
        ticket= @ticgitng.ticket_get_attachment( 'fubar.txt', nil, ticket.ticket_id )
        ticket.class.should == TicGitNG::Ticket
        ticket.attachments.size.should == 1
        ticket.attachments[0].attachment_name.should == 'fubar.txt'
    end
    #ticket_assign, ticket_revparse,
    ticket=@ticgitng.ticket_assign( 'some_random_guy', ticket.ticket_id )
    ticket.class.should == TicGitNG::Ticket
    ticket.assigned.should == 'some_random_guy'
    ticket1=@ticgitng.ticket_revparse( ticket.ticket_id[/[0-9a-z]{5}/] )
    ticket1.should == ticket.ticket_name
    #ticket_change, ticket_show,
    ticket=@ticgitng.ticket_change( 'resolved', ticket.ticket_id )
    ticket.class.should == TicGitNG::Ticket
    ticket.state.should == 'resolved'
    @ticgitng.ticket_change( 'open', ticket.ticket_id )
    ticket=@ticgitng.ticket_show( ticket.ticket_id )
    ticket.class.should == TicGitNG::Ticket
    #ticket_checkout, ticket_list,
    ticket=@ticgitng.ticket_checkout( ticket.ticket_id )
    ticket.class.should == TicGitNG::Ticket
    @ticgitng.current_ticket.should == ticket.ticket_name
    tickets=@ticgitng.ticket_list
    tickets.size.should == 1
    tickets[0].class.should == TicGitNG::Ticket
    tickets[0].ticket_id.should == ticket.ticket_id
    #ticket_comment
    ticket=@ticgitng.ticket_comment( 'fubar fubar fubar', ticket.ticket_id )
    ticket.comments[0].comment.should == 'fubar fubar fubar'
  end

end


================================================
FILE: spec/base_ticket_revparse_spec.rb
================================================
require File.dirname(__FILE__) + "/spec_helper"

describe TicGitNG::Base do
  include TicGitNGSpecHelper

  before(:each) do
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
  end

  after(:each) do
    Dir.glob(File.expand_path("~/.ticgit-ng/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("~/.ticgit/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("/tmp/ticgit-ng-*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
  end

  it "should return a ticket by index" do
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
    test_titles = ["0", "1", "2"]
    test_titles.each do |title|
      @ticgitng.ticket_new(title)
    end

    # This forces the ticket list to cache as an indexable list
    # Use the middle ticket as our test ticket
    title_index = @ticgitng.ticket_list[1].title.to_i

    # Ticket indexing is 1 based. Query for the middle ticket.
    found_tic_name = @ticgitng.ticket_revparse("2")
    clean_name = test_titles[title_index].downcase.gsub(/[^a-z0-9]+/i, '-')
    found_tic_name.should match /^\d+_#{clean_name}_\d+$/
  end

  it "should return a ticket by full SHA" do
    test_title = "My SHA test ticket"
    tic = @ticgitng.ticket_new(test_title)

    found_tic_name = @ticgitng.ticket_revparse(tic.ticket_id)
    clean_name = test_title.downcase.gsub(/[^a-z0-9]+/i, '-')
    found_tic_name.should match /^\d+_#{clean_name}_\d+$/
  end

  it "should return a ticket by partial SHA which is an integer" do
    test_title = "My partial integer SHA test ticket"
    integer_partial_sha = '432513'

    clean_name = test_title.downcase.gsub(/[^a-z0-9]+/i, '-')
    @ticgitng.should_receive(:read_tickets).with().and_return(
      {
        "1306092232_#{clean_name}_317" =>
          {
            "files"=> [
                ["ASSIGNED_some_person@email.com", "2d4e94d6963e02f079bc5712ed90a8237a415ebf"],
                ["STATE_open", "f510327578a4562e26a7c64bdf061e4a49f85ee6"],
                ["TICKET_ID", integer_partial_sha+'ajf34j2lk23bk3423'],
                ["TICKET_TITLE", "44c496d5543823f54e7920738b70b03e85955866"],
                ["TITLE", "44c496d5543823f54e7920738b70b03e85955866"]
            ]
          }
      }
    )

    found_tic_name = @ticgitng.ticket_revparse(integer_partial_sha)
    found_tic_name.should match /^\d+_#{clean_name}_\d+$/
  end

  it "should return a ticket by partial SHA" do
    test_title = "My partial SHA test ticket"
    tic = @ticgitng.ticket_new(test_title)

    found_tic_name = @ticgitng.ticket_revparse(tic.ticket_id[0..5])
    clean_name = test_title.downcase.gsub(/[^a-z0-9]+/i, '-')
    found_tic_name.should match /^\d+_#{clean_name}_\d+$/
  end

  it "should not return a ticket by short partial SHA" do
    tic = @ticgitng.ticket_new("My short partial SHA test ticket")

    found_tic_name = @ticgitng.ticket_revparse( tic.ticket_id[0..3] )
    found_tic_name.should == nil
  end

end


================================================
FILE: spec/cache_spec.rb
================================================
require File.dirname(__FILE__) + "/spec_helper"
require 'pp'

describe TicGitNG do
  include TicGitNGSpecHelper
  include TicGitNG

  before(:each) do
    @path= setup_new_git_repo
    @orig_test_opts= test_opts
    @ticgitng= TicGitNG.open(@path, @orig_test_opts)
  end

  after(:each) do
    Dir.glob(File.expand_path("~/.ticgit-ng/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("~/.ticgit/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("/tmp/ticgit-ng-*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
  end

  it "Should not contaminate ticgit/ticgit-ng branch just because working dir is contaminated" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
      @ticgitng.ticket_new('new ticket, clean state', :comment=>"I am the content")
      workingdir_ticket=File.join( @ticgitng.tic_working, @ticgitng.tickets.sort[0][0] )
      new_file( File.join(workingdir_ticket, 'fake_file'), 'I am a file that should not be commited' )
      @ticgitng.ticket_new('another ticket', :comment=>"This commit should not add the new_file()" )
      #@ticgitng.git.gtree(@ticgitng.which_branch?).trees.map {|dir_name| dir_name.include?('fake_file') }.size.should eq(2)
      has_fake_file=false
      @ticgitng.git.gtree(@ticgitng.which_branch?).trees.each {|tree| tree[1].blobs.map {|blob_name| has_fake_file=true if blob_name[0].include?('fake_file') }}
      has_fake_file.should eq(false)
    end

  end

end


================================================
FILE: spec/cli_spec.rb
================================================
require File.dirname(__FILE__) + "/spec_helper"

describe TicGitNG::CLI do
  include TicGitNGSpecHelper

  before(:each) do
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
  end

  after(:each) do
    Dir.glob(File.expand_path("~/.ticgit-ng/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("~/.ticgit/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("/tmp/ticgit-ng-*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
  end

  it "should list the tickets" do
    @ticgitng.tickets.size.should eql(0)
    @ticgitng.ticket_new('my new ticket').should be_an_instance_of(TicGitNG::Ticket)
    @ticgitng.ticket_new('my second ticket').should be_an_instance_of(TicGitNG::Ticket)
    @ticgitng.tickets.size.should eql(2)
    fields = %w[TicId Title State Date Assgn Tags]
    output = []
    # It's unclear why it's necessary to append each line like this, but
    # cli('list') would otherwise return nil. The spec helper probably
    # needs some refactoring.
    cli(@path, 'init','list') do |line|
      output << line
    end
    output.shift.should match ""
    output.shift.should match /#{fields.join( '\s+' )}/
    output.shift.should match /^-+$/
    #check that at least the SHA1 prefix exists
    output.shift[/^[a-z0-9]{6}\s/].should_not == nil
    output.shift[/^[a-z0-9]{6}\s/].should_not == nil
    output.shift.should match ""
  end

  it "should return the same ticket from ticket_show and ticket_new" do
      #FIXME the output of cli(@path,'list') produces a random order
      #- This has to do with a lack of timeskew
      20.times do
        #setup git repo
        git_dir= setup_new_git_repo
        base= TicGitNG.open( git_dir, test_opts )
        base.tickets.size.should eql(0)

        tic1=base.ticket_new('my new ticket', Hash.new, t1=time_skew)
        tic1.should be_an_instance_of(TicGitNG::Ticket)
        tic1.should == base.ticket_show( tic1.ticket_id )

        tic2=base.ticket_new('my second ticket', Hash.new, t2=time_skew)
        tic2.should be_an_instance_of(TicGitNG::Ticket)
        tic2.should == base.ticket_show( tic2.ticket_id )

        tic1.should_not == tic2
        tic1.should_not == base.ticket_show( tic2.ticket_id )

        tic1.title.should == 'my new ticket'
        tic2.title.should == 'my second ticket'
        base.tickets.size.should eql(2)

        if t1>t2
            t=tic2
            tic2=tic1
            tic1=t
        end

        fields = %w[TicId Title State Date Assgn Tags]
        output = []
        # It's unclear why it's necessary to append each line like this, but
        # cli('list') would otherwise return nil. The spec helper probably
        # needs some refactoring.
        cli(git_dir, 'init','list') do |line|
          output << line
        end
        output.shift.should match ""
        output.shift.should match /#{fields.join( '\s+' )}/
        output.shift.should match /^-+$/

        #first ticket
        line=output.shift.split(' ')
        line[0].should match /^[a-z0-9]{6}/
        #This doesn't hinge on t1<t2 because assigned will be
        # the same for both tickets
        a=tic1.assigned
        if a.bytesize > 8
            a="#{a[0, 7]}+"
        end
        line.pop.should == a
        #FIXME if t1<t2, t1, else, t2
        line.pop.should == tic1.opened.strftime('%m/%d')
        line.pop.should == 'open'
        #delete the sha1
        line.shift
        line.join(' ').should == tic1.title

        #second ticket
        line=output.shift.split(' ')
        line[0].should match /^[a-z0-9]{6}/
        a=tic2.assigned
        if a.bytesize > 8
            a="#{a[0, 7]}+"
        end
        line.pop.should == a
        line.pop.should == tic2.opened.strftime('%m/%d')
        line.pop.should == 'open'
        #delete the sha1
        line.shift
        line.join(' ').should == tic2.title
      end
  end

  it "should show a ticket" do
    #FIXME needs time_sku to avoid random failures
    @ticgitng.tickets.size.should eql(0)

    tic1=@ticgitng.ticket_new('my new ticket', Hash.new, t1=time_skew)
    tic1.should be_an_instance_of(TicGitNG::Ticket)
    tic1=@ticgitng.ticket_show(tic1.ticket_id)

    tic2=@ticgitng.ticket_new('my second ticket', Hash.new, t2=time_skew)
    tic2.should be_an_instance_of(TicGitNG::Ticket)
    tic2=@ticgitng.ticket_show(tic2.ticket_id)

    @ticgitng.tickets.size.should eql(2)
    if t1>t2
        t=tic2
        tic2=tic1
        tic1=t
    end

    fields = %w[TicId Title State Date Assgn Tags]
    output = []
    # It's unclear why it's necessary to append each line like this, but
    # cli('list') would otherwise return nil. The spec helper probably
    # needs some refactoring.
    cli(@path, 'init','list') do |line|
      output << line
    end
    output.shift.should match ""
    output.shift.should match /#{fields.join( '\s+' )}/
    output.shift.should match /^-+$/

    #first ticket
    line=output.shift.split(' ')
    line[0].should match /^[a-z0-9]{6}/
    a=tic1.assigned
    if a.bytesize > 8
        a="#{a[0, 7]}+"
    end
    line.pop.should == a
    line.pop.should == tic1.opened.strftime('%m/%d')
    line.pop.should == 'open'
    #delete the sha1
    line.shift
    line.join(' ').should == tic1.title

    #second ticket
    line=output.shift.split(' ')
    line[0].should match /^[a-z0-9]{6}/
    a=tic2.assigned
    if a.bytesize > 8
        a="#{a[0, 7]}+"
    end
    line.pop.should == a
    line.pop.should == tic2.opened.strftime('%m/%d')
    line.pop.should == 'open'
    #delete the sha1
    line.shift
    line.join(' ').should == tic2.title
  end

  it 'displays --help' do
    expected = format_expected(<<-OUT)
Please specify at least one action to execute.

Usage: ti COMMAND [FLAGS] [ARGS]

The available ticgit commands are:
    assign                           Assings a ticket to someone
    attach                           Attach file to ticket
    checkout                         Checkout a ticket
    comment                          Comment on a ticket
    help                             Show help for a ticgit command
    init                             Initialize Ticgit-ng
    list                             List tickets
    new                              Create a new ticket
    points                           Assign points to a ticket
    recent                           List recent activities
    show                             Show a ticket
    state                            Change state of a ticket
    sync                             Sync tickets
    tag                              Modify tags of a ticket

Common options:
    -v, --version                    Show the version number
    -h, --help                       Display this help
    OUT

    cli(@path) do |line|
      line.should == expected.shift
    end
  end

  it 'displays empty list' do
    fields = %w[TicId Title State Date Assgn Tags]
    output = []
    # It's unclear why it's necessary to append each line like this, but
    # cli('list') would otherwise return nil. The spec helper probably
    # needs some refactoring.
    cli(@path, 'init','list') do |line|
      output << line
    end
    output.shift.should match ""
    output.shift.should match /#{fields.join '\s+'}/
    output.shift.should match /^-+$/
  end
end


================================================
FILE: spec/merging_spec.rb
================================================
require File.dirname(__FILE__) + "/spec_helper"
require 'pp'

describe TicGitNG do
  include TicGitNGSpecHelper

  before(:each) do
    @path= setup_new_git_repo
    @orig_test_opts= test_opts
    @ticgitng= TicGitNG.open(@path, @orig_test_opts)
  end

  after(:each) do
    Dir.glob(File.expand_path("~/.ticgit-ng/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("~/.ticgit/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("/tmp/ticgit-ng-*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
  end

  it "Should merge in tickets from a remote source" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
      #prep, get temp dirs, init git2
      @ticgitng.ticket_new('my new ticket')
      git2=Git.clone(@path, 'remote_1')
      git=Git.open(@path)
      git_path_2= tmp_dir + '/remote_1/'

      #Make ticgit-ng branch in remote_1
      git2.checkout('origin/ticgit')
      git2.branch('ticgit-ng').checkout
      ticgit2=TicGitNG.open(git_path_2, @orig_test_opts)

      ticgit2.ticket_new('my second ticket')
      git2.checkout('master')

      git.add_remote('upstream', git_path_2)
      git.checkout('ticgit')
      git.pull('upstream', 'upstream/ticgit-ng')
      git.checkout('master')

      ticgit2.tickets.length.should == @ticgitng.tickets.length
    end
  end

  it "should be able to sync with origin" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
      #prep, get temp dirs, init git2

      #@ticgitng.ticket_new('my new ticket')
      #git=Git.open(@path)

      git_path_2= tmp_dir + '/remote_1/'
      git_path_3= tmp_dir + '/remote_2/'

      #Make ticgit-ng branch in remote_1
      git2=Git.clone(@path, 'remote_1')
      git2.checkout('origin/ticgit')
      #this creates the ticgit-ng branch, tracking origin/ticgit-ng
      git2.branch('ticgit-ng').checkout
      git2.checkout('master')

      git3=Git.clone(git_path_2, 'remote_2')
      git3.checkout('origin/ticgit-ng')
      git3.branch('ticgit-ng').checkout
      git3.checkout('master')

      ticgit2=TicGitNG.open(git_path_2, @orig_test_opts)
      ticgit2.ticket_new('my first ticket')
      ticgit3=TicGitNG.open(git_path_3, @orig_test_opts)
      ticgit3.ticket_new('my second ticket')
      ticgit2.ticket_new('my third ticket')

      #git.add_remote('upstream', git_path_2)
      #git.checkout('ticgit-ng')
      #git.pull('upstream', 'upstream/ticgit-ng')
      #git.checkout('master')
      ticgit3.sync_tickets('origin', true, false)

      ticgit3.tickets.length.should == ticgit2.tickets.length
    end
  end

  it "should be able to sync with other repos" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
      #prep, get temp dirs, init git2

      git_path_2= tmp_dir + '/remote_1/'
      git_path_3= tmp_dir + '/remote_2/'
      git_path_4= tmp_dir + '/remote_3/'

      #Make ticgit-ng branch in remote_1
      git2=Git.clone(@path, 'remote_1')
      git2.checkout('origin/ticgit')
      #this creates the ticgit-ng branch, tracking from the 
      #branch we are already on, origin/ticgit-ng
      git2.branch('ticgit-ng').checkout
      git2.checkout('master')

      #Make ticgit-ng branch in remote_2
      git3=Git.clone(@path, 'remote_2')
      git3.checkout('origin/ticgit')
      git3.branch('ticgit-ng').checkout
      git3.checkout('master')

      #Make ticgit-ng branch in remote_2
      git4=Git.clone(@path, 'remote_3')
      git4.checkout('origin/ticgit')
      git4.branch('ticgit-ng').checkout
      git4.checkout('master')

      ticgit2=TicGitNG.open(git_path_2, @orig_test_opts)
      ticgit2.tickets.length.should==0
      ticgit2.ticket_new('my first ticket')
      ticgit3=TicGitNG.open(git_path_3, @orig_test_opts)
      ticgit3.tickets.length.should==0
      ticgit3.ticket_new('my second ticket')
      ticgit4=TicGitNG.open(git_path_4, @orig_test_opts)
      ticgit4.tickets.length.should==0
      ticgit4.ticket_new('my third ticket')
      ticgit2.ticket_new('my fourth ticket')

      #git.add_remote('upstream', git_path_2)
      #git.checkout('ticgit-ng')
      #git.pull('upstream', 'upstream/ticgit-ng')
      #git.checkout('master')
      
      git3.add_remote('ticgit2', git_path_2)
      git4.add_remote('ticgit3', git_path_3)

      ticgit3.sync_tickets('ticgit2', true, false) #ticgit3 should now have tickets 1, 2, and 4
                                                   #and ticgit2 should now have the same
      ticgit3.tickets.length.should==3
      ticgit2.tickets.length.should==3

      ticgit4.sync_tickets('ticgit3', false, false) #ticgit4 should now have tickets 1,2,3,4
                                                    #but ticgit2 and 3 should only have 1,2,4
      ticgit4.tickets.length.should==4
      ticgit3.tickets.length.should==3
      ticgit2.tickets.length.should==3

      git4.add_remote('ticgit2', git_path_2)
      ticgit4.sync_tickets('ticgit2', true, false) #ticgit2 and 4 should now have 4 tickets while
                                                   #ticgit3 only has 3 tickets
      ticgit4.tickets.length.should==4
      ticgit3.tickets.length.should==3
      ticgit2.tickets.length.should==4
    end
  end
  it "Use the 'ticgit' branch if 'ticgit-ng' isn't available (legacy support)" do
    Dir.chdir(File.expand_path( tmp_dir=Dir.mktmpdir('ticgit-ng-gitdir1-') )) do
      #Because there is no 'ticgit' or 'ticgit-ng' branch
      #this will create a new ticket in 'ticgit-ng'
      @ticgitng.ticket_new('original shinanigins')
      git1=Git.clone( @path, 'remote_0' )
      #This checks out origin/ticgit-ng and creates a new 
      #branch following it callled ticgit, which should be
      #used transparently instead of ticgit-ng
      git1.checkout( 'origin/ticgit' )
      git1.branch('ticgit').checkout
      ticgitng1=TicGitNG.open( tmp_dir+'/remote_0/', @orig_test_opts )
      ticgitng1.which_branch?.should == 'ticgit'

      git2=Git.clone( @path, 'remote_1' )
      git2.checkout( 'origin/ticgit' )
      git2.branch('ticgit-ng').checkout
      ticgitng2=TicGitNG.open( tmp_dir+'/remote_1/', @orig_test_opts )
      ticgitng2.which_branch?.should == 'ticgit-ng'

      git3=Git.clone( @path, 'remote_2' )
      git3.checkout( 'origin/ticgit' )
      git3.branch('ticgit').checkout
      git3.checkout( 'origin/ticgit' )
      git3.branch('ticgit-ng').checkout
      ticgitng3=TicGitNG.open( tmp_dir+'/remote_2/', @orig_test_opts )
      ticgitng3.which_branch?.should == 'ticgit-ng'

      # if 'ticgit' and 'ticgit-ng'
      #   should use 'ticgit-ng'
      # elsif 'ticgit' and !'ticgit-ng'
      #   should use 'ticgit'
      # elsif !'ticgit' and 'ticgit-ng'
      #   should use 'ticgit-ng'
      # end
    end
  end
end


================================================
FILE: spec/scalability_spec.rb
================================================
require File.dirname(__FILE__) + "/spec_helper"

describe TicGitNG::Base do
  include TicGitNGSpecHelper

  before(:each) do
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
  end

  after(:each) do
    Dir.glob(File.expand_path("~/.ticgit-ng/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("~/.ticgit/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("/tmp/ticgit-ng-*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
  end

  it "Should take the same amount of time to init on a large repo as a small one" do
    t1_before=0
    t1_after=0
    t2_before=0
    t2_after=0
    path1= setup_new_git_repo
    Dir.chdir( path1 ) do
      #test a small repo
      #do this a couple times to make it a bit fairer re caching
      10.times do
        t1_before=Time.now.to_i
        ticgit1=TicGitNG.open( path1, @orig_test_opts )
        t1_after=Time.now.to_i
      end
    end

    path2= setup_new_git_repo
    Dir.chdir( path2 ) do
      #test a large repo
      git=Git.open '.'
      500.times do |i|
        new_file("file_#{i}", "#{rand(9999999)}_#{i}")
        git.add "file_#{i}"
        git.commit "Added file_#{i}"
      end
      #do this a couple times to make it fairer re caching
      10.times do
        t2_before=Time.now.to_i
        ticgit2=TicGitNG.open( path2, @orig_test_opts )
        t2_after=Time.now.to_i
      end
    end
    #Opening is a simple operation, it should take less than a second in most cases,
    #But this test is intended to make sure that the size of the repo does not impact
    #the initialization time of TicGit-ng
    #FIXME Fix this dirty hack, find out what the proper way to do this is
    true.should == ((t1_after-t1_before) < 5)
    true.should == ((t2_after-t2_before) < 5)
  end

end


================================================
FILE: spec/spec_helper.rb
================================================
require File.expand_path(File.dirname(__FILE__) + "/../lib/ticgit-ng")
require 'fileutils'
require 'logger'
require 'tempfile'

TICGITNG_HISTORY = StringIO.new

module TicGitNGSpecHelper

=begin
tempdir -
  test => "content"
  subdir -
    testfile => "content2"
=end
  def setup_new_git_repo prefix='ticgit-ng-gitdir-'
    tempdir = Dir.mktmpdir prefix
    Dir.chdir(tempdir) do
      git = Git.init
      new_file('test', 'content')
      Dir.mkdir('subdir')
      new_file('subdir/testfile', 'content2')
      git.add
      git.commit('first commit')
    end
    tempdir
  end

  def test_opts
    tempdir = Dir.mktmpdir 'ticgit-ng-ticdir-'
    logger = Logger.new(Tempfile.new('ticgit-ng-log-'))
    { :tic_dir => tempdir, :logger => logger, :init => true }
  end


  def new_file(name, contents)
    File.open(name, 'w') do |f|
      f.puts contents
    end
  end

  def format_expected(string)
    string.enum_for(:each_line).map{|line| line.strip }
  end

  def cli(path, *args, &block)
    TICGITNG_HISTORY.truncate 0
    TICGITNG_HISTORY.rewind

    ticgitng = TicGitNG::CLI.new(args.flatten, path, TICGITNG_HISTORY)
    ticgitng.parse_options!
    ticgitng.execute!

    replay_history(&block)
  rescue SystemExit => error
    replay_history(&block)
  end

  def replay_history
    TICGITNG_HISTORY.rewind
    return unless block_given?

    while line = TICGITNG_HISTORY.gets
      yield(line.strip)
    end
  end
    
    def read_line_of filename 
        File.open(filename, "r").each_line do |line|
          return line
        end
    end

      def time_skew
          Time.now.to_i + rand(1000)
      end

end



##
# rSpec Hash additions.
#
# From
#   * http://wincent.com/knowledge-base/Fixtures_considered_harmful%3F
#   * Neil Rahilly

class Hash

  ##
  # Filter keys out of a Hash.
  #
  #   { :a => 1, :b => 2, :c => 3 }.except(:a)
  #   => { :b => 2, :c => 3 }

  def except(*keys)
    self.reject { |k,v| keys.include?(k || k.to_sym) }
  end

  ##
  # Override some keys.
  #
  #   { :a => 1, :b => 2, :c => 3 }.with(:a => 4)
  #   => { :a => 4, :b => 2, :c => 3 }

  def with(overrides = {})
    self.merge overrides
  end

  ##
  # Returns a Hash with only the pairs identified by +keys+.
  #
  #   { :a => 1, :b => 2, :c => 3 }.only(:a)
  #   => { :a => 1 }

  def only(*keys)
    self.reject { |k,v| !keys.include?(k || k.to_sym) }
  end
end


================================================
FILE: spec/ticgit_spec.rb
================================================
require File.dirname(__FILE__) + "/spec_helper"

describe TicGitNG do
  include TicGitNGSpecHelper

  before(:all) do
    @path = setup_new_git_repo
    @orig_test_opts = test_opts
    @ticgitng = TicGitNG.open(@path, @orig_test_opts)
  end

  after(:all) do
    Dir.glob(File.expand_path("~/.ticgit-ng/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("~/.ticgit/-tmp*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
    Dir.glob(File.expand_path("/tmp/ticgit-ng-*")).each {|file_name| FileUtils.rm_r(file_name, {:force=>true,:secure=>true}) }
  end

  it "Should only create a new branch when 'ti init' is called" do
    git_dir_2=        setup_new_git_repo
    git_opts_2=       test_opts
    git_opts_2[:init]=false

    #With :init set to false, the default when calling ti
    lambda { ticgitng_2=TicGitNG.open(git_dir_2, git_opts_2) }.should raise_error SystemExit

    #with :init set to true, the default for TicGitNGSpecHelper.test_opts(), the branch should be created without error
    lambda { ticgitng=TicGitNG.open( @path, @orig_test_opts )}.should_not raise_error SystemExit

  end

  it "should create a new branch if it's not there" do
    br = @ticgitng.git.branches.map { |b| b.name }
    br.should include('ticgit')
  end

  it "should find an existing ticgit-ng branch if it's there" do
    tg = TicGitNG.open(@path, test_opts)
    @ticgitng.git.branches.size.should eql(tg.git.branches.size)
  end

  it "should find the .git directory if it's there" do
    @ticgitng.git.dir.path.should eql(@path)
  end

  it "should look for the .git directory until it finds it" do
    tg = TicGitNG.open(File.join(@path, 'subdir'), @orig_test_opts)
    tg.git.dir.path.should eql(@path)
  end

  it "should add a .hold file to a new branch" do
    @ticgitng.in_branch{ File.file?('.hold').should == true }
  end

end


================================================
FILE: ticgit-ng.gemspec
================================================
lib= File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)

require './lib/ticgit-ng'

Gem::Specification.new do |s|
  s.name      = "TicGit-ng"
  s.version   = TicGitNG::VERSION
  s.platform  = Gem::Platform::RUBY
  s.date      = Date.today.to_s
  s.authors   = ["Scott Chacon", "Jeff Welling"]
  s.email     = ["Jeff.Welling@gmail.com"]
  s.homepage  = "https://github.com/jeffWelling/ticgit"
  s.summary   = "Git based distributed ticketing system"
  s.description="TicGit-ng is a simple ticketing system, roughly similar to the Lighthouse model, that is based in git."

  s.rubyforge_project         = "ticgit-ng"

  s.add_dependency "git"
  s.add_development_dependency "rspec"
  s.files       = Dir.glob("{bin,lib}/**/*") + %w( LICENSE_MIT LICENSE_GPL README.mkd )
  s.executables = ['ti', 'ticgitweb']
  s.require_path= 'lib'
end
Download .txt
gitextract_jah_79j_/

├── .gitignore
├── .rvmrc
├── LICENSE_GPL
├── LICENSE_MIT
├── README.mkd
├── Rakefile
├── bin/
│   ├── ti
│   └── ticgitweb
├── development.mkd
├── examples/
│   └── post-commit
├── lib/
│   ├── ticgit-ng/
│   │   ├── attachment.rb
│   │   ├── base.rb
│   │   ├── cli.rb
│   │   ├── command/
│   │   │   ├── assign.rb
│   │   │   ├── attach.rb
│   │   │   ├── checkout.rb
│   │   │   ├── comment.rb
│   │   │   ├── help.rb
│   │   │   ├── init.rb
│   │   │   ├── list.rb
│   │   │   ├── milestone.rb
│   │   │   ├── new.rb
│   │   │   ├── points.rb
│   │   │   ├── recent.rb
│   │   │   ├── show.rb
│   │   │   ├── state.rb
│   │   │   ├── sync.rb
│   │   │   └── tag.rb
│   │   ├── command.rb
│   │   ├── comment.rb
│   │   ├── ticket.rb
│   │   └── version.rb
│   └── ticgit-ng.rb
├── note/
│   ├── IMPLEMENT
│   ├── NOTES
│   ├── OUTPUT
│   └── TODO
├── spec/
│   ├── attachments_spec.rb
│   ├── base_spec.rb
│   ├── base_ticket_revparse_spec.rb
│   ├── cache_spec.rb
│   ├── cli_spec.rb
│   ├── merging_spec.rb
│   ├── scalability_spec.rb
│   ├── spec_helper.rb
│   └── ticgit_spec.rb
└── ticgit-ng.gemspec
Download .txt
SYMBOL INDEX (189 symbols across 24 files)

FILE: lib/ticgit-ng.rb
  type Git (line 21) | module Git
    class Lib (line 22) | class Lib
      method config_get (line 23) | def config_get(name)
  type TicGitNG (line 40) | module TicGitNG
    function open (line 51) | def self.open(git_dir, options = {})
    class OpenStruct (line 55) | class OpenStruct < ::OpenStruct
      method to_hash (line 56) | def to_hash

FILE: lib/ticgit-ng/attachment.rb
  type TicGitNG (line 1) | module TicGitNG
    class Attachment (line 2) | class Attachment
      method initialize (line 7) | def initialize( fname )
      method create (line 25) | def self.create raw_fname, ticket, time

FILE: lib/ticgit-ng/base.rb
  type TicGitNG (line 1) | module TicGitNG
    class NoRepoFound (line 2) | class NoRepoFound < StandardError;end
    class Base (line 3) | class Base
      method initialize (line 11) | def initialize(git_dir, opts = {})
      method find_repo (line 108) | def find_repo(dir)
      method save_state (line 118) | def save_state
      method load_state (line 128) | def load_state
      method ticket_new (line 142) | def ticket_new(title, options = {}, time=nil)
      method reset_ticgitng (line 150) | def reset_ticgitng
      method ticket_comment (line 156) | def ticket_comment(comment, ticket_id = nil)
      method ticket_list (line 166) | def ticket_list(options = {})
      method ticket_show (line 259) | def ticket_show(ticket_id = nil)
      method ticket_recent (line 269) | def ticket_recent(ticket_id = nil)
      method ticket_revparse (line 278) | def ticket_revparse(ticket_id)
      method ticket_tag (line 295) | def ticket_tag(tag, ticket_id = nil, options = OpenStruct.new)
      method ticket_change (line 308) | def ticket_change(new_state, ticket_id = nil)
      method ticket_assign (line 319) | def ticket_assign(new_assigned = nil, ticket_id = nil)
      method ticket_points (line 328) | def ticket_points(new_points = nil, ticket_id = nil)
      method ticket_checkout (line 337) | def ticket_checkout(ticket_id)
      method tic_states (line 346) | def tic_states
      method sync_tickets (line 350) | def sync_tickets(repo='origin', push=true, verbose=true )
      method tickets (line 366) | def tickets
      method read_tickets (line 370) | def read_tickets
      method init_ticgitng_branch (line 394) | def init_ticgitng_branch(ticgitng_branch = false)
      method in_branch (line 414) | def in_branch(branch_exists = true)
      method new_file (line 438) | def new_file(name, contents)
      method which_branch? (line 442) | def which_branch?
      method reset_cache (line 455) | def reset_cache
      method needs_reset? (line 467) | def needs_reset? cache_mtime, gitlog_mtime
      method ticket_attach (line 471) | def ticket_attach filename, ticket_id=nil, time=nil
      method ticket_get_attachment (line 483) | def ticket_get_attachment file_id=nil, new_filename=nil, ticket_id=nil

FILE: lib/ticgit-ng/cli.rb
  type TicGitNG (line 6) | module TicGitNG
    class CLI (line 7) | class CLI
      method execute (line 8) | def self.execute
      method parse (line 12) | def self.parse(args)
      method initialize (line 22) | def initialize(args, path = '.', out = $stdout)
      method execute! (line 44) | def execute!
      method parse_options! (line 69) | def parse_options! #:nodoc:
      method usage (line 86) | def usage(args = nil)
      method get_editor_message (line 97) | def get_editor_message(comments = nil)
      method ticket_show (line 112) | def ticket_show(t, more=nil)
      method reset_window_width (line 178) | def reset_window_width
      method try_using (line 187) | def try_using(mask)
      method try_windows (line 197) | def try_windows
      method windows_terminal_size (line 203) | def windows_terminal_size
      method use_fallback (line 219) | def use_fallback
      method window_lines (line 224) | def window_lines
      method window_cols (line 228) | def window_cols
      method just (line 234) | def just(value, size = 10, side = :left)
      method just (line 246) | def just(value, size = 10, side = :left)
      method just_common (line 259) | def just_common(value, size, side)
      method puts (line 268) | def puts(*strings)

FILE: lib/ticgit-ng/command.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      function register (line 6) | def self.register(mod_name, doc, *commands)
      function get (line 28) | def self.get(command)
      function usage (line 34) | def self.usage(action, args)
      function default_usage (line 40) | def self.default_usage(o)
      function parser (line 55) | def self.parser(action, &block)

FILE: lib/ticgit-ng/command/assign.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Assign (line 11) | module Assign
        function parser (line 12) | def parser(opts)
        function execute (line 24) | def execute
        function handle_ticket_assign (line 27) | def handle_ticket_assign

FILE: lib/ticgit-ng/command/attach.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Attach (line 20) | module Attach
        function parser (line 21) | def parser(opts)
        function execute (line 39) | def execute

FILE: lib/ticgit-ng/command/checkout.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Checkout (line 3) | module Checkout
        function parser (line 4) | def parser(opts)
        function execute (line 8) | def execute

FILE: lib/ticgit-ng/command/comment.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Comment (line 3) | module Comment
        function parser (line 4) | def parser(opts)
        function execute (line 21) | def execute

FILE: lib/ticgit-ng/command/help.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Help (line 8) | module Help
        function parser (line 9) | def parser(opts)
        function execute (line 12) | def execute

FILE: lib/ticgit-ng/command/init.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Init (line 3) | module Init
        function parser (line 4) | def parser o
        function execute (line 7) | def execute

FILE: lib/ticgit-ng/command/list.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type List (line 4) | module List
        function parser (line 5) | def parser(o)
        function execute (line 45) | def execute

FILE: lib/ticgit-ng/command/milestone.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Milestone (line 8) | module Milestone
        function parser (line 9) | def parser(opts)

FILE: lib/ticgit-ng/command/new.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type New (line 3) | module New
        function parser (line 4) | def parser(opts)
        function execute (line 11) | def execute

FILE: lib/ticgit-ng/command/points.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Points (line 7) | module Points
        function parser (line 8) | def parser(opts)
        function execute (line 12) | def execute

FILE: lib/ticgit-ng/command/recent.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Recent (line 3) | module Recent
        function parser (line 4) | def parser(opts)
        function execute (line 8) | def execute

FILE: lib/ticgit-ng/command/show.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Show (line 3) | module Show
        function parser (line 4) | def parser(opts)
        function execute (line 12) | def execute

FILE: lib/ticgit-ng/command/state.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type State (line 3) | module State
        function parser (line 4) | def parser(opts)
        function execute (line 8) | def execute
        function valid_state? (line 32) | def valid_state?(state)
        function available_states (line 36) | def available_states
        function joined_states (line 40) | def joined_states

FILE: lib/ticgit-ng/command/sync.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Sync (line 3) | module Sync
        function parser (line 4) | def parser(opts)
        function execute (line 16) | def execute

FILE: lib/ticgit-ng/command/tag.rb
  type TicGitNG (line 1) | module TicGitNG
    type Command (line 2) | module Command
      type Tag (line 3) | module Tag
        function parser (line 4) | def parser(opts)
        function execute (line 11) | def execute

FILE: lib/ticgit-ng/comment.rb
  type TicGitNG (line 1) | module TicGitNG
    class Comment (line 2) | class Comment
      method initialize (line 5) | def initialize( c, user, time=nil )
      method read (line 13) | def self.read( base, file_name, sha )

FILE: lib/ticgit-ng/ticket.rb
  type TicGitNG (line 1) | module TicGitNG
    class Ticket (line 2) | class Ticket
      method initialize (line 9) | def initialize(base, options = {})
      method create (line 28) | def self.create(base, title, options = {}, time=nil)
      method open (line 36) | def self.open(base, ticket_name, ticket_hash, options = {})
      method parse_ticket_name (line 85) | def self.parse_ticket_name(name)
      method save_new (line 92) | def save_new
      method clean_string (line 140) | def self.clean_string(string)
      method add_comment (line 144) | def add_comment(comment)
      method add_attach (line 158) | def add_attach( base, filename, time=nil )
      method get_attach (line 180) | def get_attach file_id=nil, new_filename=nil
      method change_state (line 239) | def change_state(new_state)
      method change_assigned (line 256) | def change_assigned(new_assigned)
      method change_points (line 274) | def change_points(new_points)
      method add_tag (line 288) | def add_tag(tag)
      method remove_tag (line 319) | def remove_tag(tag)
      method path (line 339) | def path
      method comment_name (line 343) | def comment_name(email)
      method email (line 347) | def email
      method assigned_name (line 351) | def assigned_name
      method create_ticket_name (line 355) | def self.create_ticket_name(title, time=nil)
      method create_attachment_name (line 359) | def create_attachment_name( attachment_name, time=nil )
      method == (line 371) | def ==(ticket2)

FILE: lib/ticgit-ng/version.rb
  type TicGitNG (line 1) | module TicGitNG

FILE: spec/spec_helper.rb
  type TicGitNGSpecHelper (line 8) | module TicGitNGSpecHelper
    function setup_new_git_repo (line 16) | def setup_new_git_repo prefix='ticgit-ng-gitdir-'
    function test_opts (line 29) | def test_opts
    function new_file (line 36) | def new_file(name, contents)
    function format_expected (line 42) | def format_expected(string)
    function cli (line 46) | def cli(path, *args, &block)
    function replay_history (line 59) | def replay_history
    function read_line_of (line 68) | def read_line_of filename
    function time_skew (line 74) | def time_skew
  class Hash (line 89) | class Hash
    method except (line 97) | def except(*keys)
    method with (line 107) | def with(overrides = {})
    method only (line 117) | def only(*keys)
Condensed preview — 47 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (196K chars).
[
  {
    "path": ".gitignore",
    "chars": 23,
    "preview": "*.gem\n*.swp\nrdoc/\npkg/\n"
  },
  {
    "path": ".rvmrc",
    "chars": 32,
    "preview": "rvm use --create default@ticgit\n"
  },
  {
    "path": "LICENSE_GPL",
    "chars": 35466,
    "preview": "This license applies ONLY to code authored by Jeff Welling. All\nother code contributions until now have been under the M"
  },
  {
    "path": "LICENSE_MIT",
    "chars": 1509,
    "preview": "The MIT License\n\nPortions, Copyright (c) 2008 Scott Chacon\nOther portions, Copyright (c) 2011 Jeff Welling\nOther portion"
  },
  {
    "path": "README.mkd",
    "chars": 21283,
    "preview": "## TicGit-ng ##\n\nThis project provides a ticketing system built on Git that is kept in a\nseparate branch in your project"
  },
  {
    "path": "Rakefile",
    "chars": 848,
    "preview": "require 'rubygems'\nrequire 'rake'\nrequire 'rake/clean'\nrequire 'rake/rdoctask'\nrequire 'rspec/core/rake_task'\n\nCLEAN.inc"
  },
  {
    "path": "bin/ti",
    "chars": 426,
    "preview": "#!/usr/bin/env ruby\nrequire 'rubygems'\nrequire 'fileutils'\n\n# Add the library from the source tree to the front of the l"
  },
  {
    "path": "bin/ticgitweb",
    "chars": 7234,
    "preview": "#!/usr/bin/env ruby\n\n# starts a sinatra based web server that provides an interface to \n# your ticgit tickets\n# \n# some "
  },
  {
    "path": "development.mkd",
    "chars": 1178,
    "preview": "## Development ##\n\nThis document describes workflows currently used for various tasks (and other shenanigans if necessar"
  },
  {
    "path": "examples/post-commit",
    "chars": 848,
    "preview": "#!/usr/bin/env ruby\n\nrequire 'tempfile'\n\n\ncommit_log   = `git log -1`.chomp\nm, commit_id = * commit_log.match(/commit\\W*"
  },
  {
    "path": "lib/ticgit-ng/attachment.rb",
    "chars": 2318,
    "preview": "module TicGitNG\n    class Attachment\n        attr_reader :user, :added, :filename, :sha, :attachment_name\n        attr_r"
  },
  {
    "path": "lib/ticgit-ng/base.rb",
    "chars": 15785,
    "preview": "module TicGitNG\n  class NoRepoFound < StandardError;end\n  class Base\n\n    attr_reader :git, :logger\n    attr_reader :tic"
  },
  {
    "path": "lib/ticgit-ng/cli.rb",
    "chars": 8033,
    "preview": "require 'ticgit-ng'\nrequire 'ticgit-ng/command'\n\n# used Cap as a model for this - thanks Jamis\n\nmodule TicGitNG\n  class "
  },
  {
    "path": "lib/ticgit-ng/command/assign.rb",
    "chars": 1456,
    "preview": "module TicGitNG\n  module Command\n    # Assigns a ticket to someone\n    #\n    # Usage:\n    # ti assign             (assig"
  },
  {
    "path": "lib/ticgit-ng/command/attach.rb",
    "chars": 1888,
    "preview": "module TicGitNG\n    module Command\n        # Attach a file to a ticket\n        #\n        # Usage:\n        # ti attach   "
  },
  {
    "path": "lib/ticgit-ng/command/checkout.rb",
    "chars": 232,
    "preview": "module TicGitNG\n  module Command\n    module Checkout\n      def parser(opts)\n        opts.banner = \"ti checkout [ticid]\"\n"
  },
  {
    "path": "lib/ticgit-ng/command/comment.rb",
    "chars": 1160,
    "preview": "module TicGitNG\n  module Command\n    module Comment\n      def parser(opts)\n        opts.banner = \"Usage: ti comment [tic"
  },
  {
    "path": "lib/ticgit-ng/command/help.rb",
    "chars": 653,
    "preview": "module TicGitNG\n  module Command\n    # Shows help for ticgit or a particular command\n    #\n    # Usage:\n    # ti help   "
  },
  {
    "path": "lib/ticgit-ng/command/init.rb",
    "chars": 528,
    "preview": "module TicGitNG\n  module Command\n    module Init\n      def parser o\n        o.banner= \"Usage: ti init\"\n      end\n      d"
  },
  {
    "path": "lib/ticgit-ng/command/list.rb",
    "chars": 2222,
    "preview": "module TicGitNG\n  module Command\n    # List tickets\n    module List\n      def parser(o)\n        o.banner = \"Usage: ti li"
  },
  {
    "path": "lib/ticgit-ng/command/milestone.rb",
    "chars": 797,
    "preview": "module TicGitNG\n  module Command\n    # tic milestone\n    # tic milestone migration1 (list tickets)\n    # tic milestone -"
  },
  {
    "path": "lib/ticgit-ng/command/new.rb",
    "chars": 1422,
    "preview": "module TicGitNG\n  module Command\n    module New\n      def parser(opts)\n        opts.banner = \"Usage: ti new [options]\"\n "
  },
  {
    "path": "lib/ticgit-ng/command/points.rb",
    "chars": 562,
    "preview": "module TicGitNG\n  module Command\n    # Assigns points to a ticket\n    #\n    # Usage:\n    # ti points {1} {points}   (ass"
  },
  {
    "path": "lib/ticgit-ng/command/recent.rb",
    "chars": 837,
    "preview": "module TicGitNG\n  module Command\n    module Recent\n      def parser(opts)\n        opts.banner = 'Usage: ti recent'\n     "
  },
  {
    "path": "lib/ticgit-ng/command/show.rb",
    "chars": 418,
    "preview": "module TicGitNG\n  module Command\n    module Show\n      def parser(opts)\n        opts.banner = \"Usage: ti show [--full] ["
  },
  {
    "path": "lib/ticgit-ng/command/state.rb",
    "chars": 1095,
    "preview": "module TicGitNG\n  module Command\n    module State\n      def parser(opts)\n        opts.banner = \"Usage: ti state [ticid] "
  },
  {
    "path": "lib/ticgit-ng/command/sync.rb",
    "chars": 1110,
    "preview": "module TicGitNG\n  module Command\n    module Sync\n      def parser(opts)\n        opts.banner = \"Usage: ti sync [options]\""
  },
  {
    "path": "lib/ticgit-ng/command/tag.rb",
    "chars": 710,
    "preview": "module TicGitNG\n  module Command\n    module Tag\n      def parser(opts)\n        opts.banner = \"Usage: ti tag [tic_id] [op"
  },
  {
    "path": "lib/ticgit-ng/command.rb",
    "chars": 2598,
    "preview": "module TicGitNG\n  module Command\n    COMMANDS = {}\n    DOC = {}\n\n    def self.register(mod_name, doc, *commands)\n      a"
  },
  {
    "path": "lib/ticgit-ng/comment.rb",
    "chars": 428,
    "preview": "module TicGitNG\n  class Comment\n    attr_accessor :base, :user, :added, :comment\n\n    def initialize( c, user, time=nil "
  },
  {
    "path": "lib/ticgit-ng/ticket.rb",
    "chars": 12087,
    "preview": "module TicGitNG\n  class Ticket\n\n    attr_reader :base, :opts\n    attr_accessor :ticket_id, :ticket_name\n    attr_accesso"
  },
  {
    "path": "lib/ticgit-ng/version.rb",
    "chars": 43,
    "preview": "module TicGitNG\n  VERSION = '1.0.2.18'\nend\n"
  },
  {
    "path": "lib/ticgit-ng.rb",
    "chars": 1594,
    "preview": "require 'fileutils'\nrequire 'logger'\nrequire 'optparse'\nrequire 'ostruct'\nrequire 'set'\nrequire 'yaml'\nrequire 'pp'\n\n# A"
  },
  {
    "path": "note/IMPLEMENT",
    "chars": 871,
    "preview": "~/.ticgit/HEAD -> branch name\n~/.ticgit/CHECKOUT -> current ticket\n~/.ticgit/USER -> schacon / email\n\nticgit/master\n\n  o"
  },
  {
    "path": "note/NOTES",
    "chars": 1972,
    "preview": "\n* store the tickets (stories, cards, bugs) - in a subdir of the repo, or a branch?\n\n* merge strategy - if in branch, we"
  },
  {
    "path": "note/OUTPUT",
    "chars": 2010,
    "preview": "OUTPUT\n==========\n\n> tic recent\n\n1 34j238\tthis one is important   03/05  comment added\n2 3kd898  anther bug             "
  },
  {
    "path": "note/TODO",
    "chars": 363,
    "preview": "link to another ticket (child tickets)\n\nMerge\n\nlink to a git object\n\nWeb UI\n\nTicGit goes up directories until it finds ."
  },
  {
    "path": "spec/attachments_spec.rb",
    "chars": 18474,
    "preview": "require File.dirname(__FILE__) + \"/spec_helper\"\n\ndescribe TicGitNG::Attachment do\n  include TicGitNGSpecHelper\n\n  before"
  },
  {
    "path": "spec/base_spec.rb",
    "chars": 11141,
    "preview": "require File.dirname(__FILE__) + \"/spec_helper\"\n\ndescribe TicGitNG::Base do\n  include TicGitNGSpecHelper\n\n  before(:all)"
  },
  {
    "path": "spec/base_ticket_revparse_spec.rb",
    "chars": 3107,
    "preview": "require File.dirname(__FILE__) + \"/spec_helper\"\n\ndescribe TicGitNG::Base do\n  include TicGitNGSpecHelper\n\n  before(:each"
  },
  {
    "path": "spec/cache_spec.rb",
    "chars": 1604,
    "preview": "require File.dirname(__FILE__) + \"/spec_helper\"\nrequire 'pp'\n\ndescribe TicGitNG do\n  include TicGitNGSpecHelper\n  includ"
  },
  {
    "path": "spec/cli_spec.rb",
    "chars": 7477,
    "preview": "require File.dirname(__FILE__) + \"/spec_helper\"\n\ndescribe TicGitNG::CLI do\n  include TicGitNGSpecHelper\n\n  before(:each)"
  },
  {
    "path": "spec/merging_spec.rb",
    "chars": 6893,
    "preview": "require File.dirname(__FILE__) + \"/spec_helper\"\nrequire 'pp'\n\ndescribe TicGitNG do\n  include TicGitNGSpecHelper\n\n  befor"
  },
  {
    "path": "spec/scalability_spec.rb",
    "chars": 1967,
    "preview": "require File.dirname(__FILE__) + \"/spec_helper\"\n\ndescribe TicGitNG::Base do\n  include TicGitNGSpecHelper\n\n  before(:each"
  },
  {
    "path": "spec/spec_helper.rb",
    "chars": 2374,
    "preview": "require File.expand_path(File.dirname(__FILE__) + \"/../lib/ticgit-ng\")\nrequire 'fileutils'\nrequire 'logger'\nrequire 'tem"
  },
  {
    "path": "spec/ticgit_spec.rb",
    "chars": 1923,
    "preview": "require File.dirname(__FILE__) + \"/spec_helper\"\n\ndescribe TicGitNG do\n  include TicGitNGSpecHelper\n\n  before(:all) do\n  "
  },
  {
    "path": "ticgit-ng.gemspec",
    "chars": 860,
    "preview": "lib= File.expand_path('../lib/', __FILE__)\n$:.unshift lib unless $:.include?(lib)\n\nrequire './lib/ticgit-ng'\n\nGem::Speci"
  }
]

About this extraction

This page contains the full source code of the jeffWelling/ticgit GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 47 files (183.5 KB), approximately 48.2k tokens, and a symbol index with 189 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!