pax_global_header00006660000000000000000000000064133702230720014511gustar00rootroot0000000000000052 comment=d86a0c1ffd8db519a1e8d56b3d972fdd8a7f4818 stgit-0.19/000077500000000000000000000000001337022307200125745ustar00rootroot00000000000000stgit-0.19/.coveragerc000066400000000000000000000001111337022307200147060ustar00rootroot00000000000000[run] source = stgit branch = True parallel = True data_file = .coverage stgit-0.19/.git_archival.txt000066400000000000000000000000261337022307200160450ustar00rootroot00000000000000ref-names: tag: v0.19 stgit-0.19/.gitattributes000066400000000000000000000000371337022307200154670ustar00rootroot00000000000000.git_archival.txt export-subst stgit-0.19/.gitignore000066400000000000000000000001771337022307200145710ustar00rootroot00000000000000build dist MANIFEST patches-* *-stamp release.sh snapshot.sh stgit-completion.bash ChangeLog .tox htmlcov/ .coverage .DS_Store stgit-0.19/.mailmap000066400000000000000000000004171337022307200142170ustar00rootroot00000000000000# This list is used by various git commands to fix a few botched name # translations in the StGIT repository. Bryan Larsen Bryan Larsen Karl Wiberg Paolo 'Blaisorblade' Giarrusso stgit-0.19/.travis.yml000066400000000000000000000020001337022307200146750ustar00rootroot00000000000000group: travis_latest language: python cache: pip matrix: include: - python: '2.6' env: MAKE_TARGET=test - python: '2.7' env: MAKE_TARGET=coverage-test - python: 'pypy' env: MAKE_TARGET=test - python: '3.3' env: MAKE_TARGET=test - python: '3.4' env: MAKE_TARGET=test - python: '3.5' env: MAKE_TARGET=test - python: '3.6' env: MAKE_TARGET=test - python: '3.7' env: MAKE_TARGET=coverage-test dist: xenial - python: 'pypy3' env: MAKE_TARGET=test - python: '3.8-dev' env: MAKE_TARGET=test dist: xenial - python: 'nightly' dist: xenial env: MAKE_TARGET=test allow_failures: - python: '3.8-dev' - python: 'nightly' - python: '2.6' install: - if [ $MAKE_TARGET = coverage-test ]; then pip install coveralls; fi - git describe --tags --abbrev=4 || git pull --unshallow --tags script: - make $MAKE_TARGET after_success: - if [ $MAKE_TARGET = coverage-test ]; then coveralls; fi stgit-0.19/AUTHORS000066400000000000000000000003111337022307200136370ustar00rootroot00000000000000Catalin Marinas http://www.procode.org/about.html Karl Wiberg http://www.treskal.com/kalle/ Peter P Waskiewicz Jr stgit-0.19/COPYING000066400000000000000000000431121337022307200136300ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. 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 convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This 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 Library General Public License instead of this License. stgit-0.19/Documentation/000077500000000000000000000000001337022307200154055ustar00rootroot00000000000000stgit-0.19/Documentation/.gitignore000066400000000000000000000000761337022307200174000ustar00rootroot00000000000000*.html *.pdf *.[1-9] *.xml stg-*.txt doc.dep command-list.txt stgit-0.19/Documentation/Makefile000066400000000000000000000040551337022307200170510ustar00rootroot00000000000000COMMANDS = $(shell $(PYTHON) ../stg-build --commands) COMMANDS_TXT = $(patsubst %,stg-%.txt,$(COMMANDS)) MAN1_TXT= stg.txt $(COMMANDS_TXT) DOC_HTML=$(patsubst %.txt,%.html,$(MAN1_TXT)) ARTICLES = tutorial DOC_HTML += $(patsubst %,%.html,$(ARTICLES)) DOC_PDF += $(patsubst %,%.pdf,$(ARTICLES)) DOC_MAN1=$(patsubst %.txt,%.1,$(MAN1_TXT)) prefix?=$(HOME) htmldir?=$(prefix)/share/doc/stgit mandir?=$(prefix)/share/man man1dir=$(mandir)/man1 # DESTDIR= ASCIIDOC=asciidoc --unsafe ASCIIDOC_EXTRA = INSTALL?=install # # Please note that there is a minor bug in asciidoc. # The version after 6.0.3 _will_ include the patch found here: # http://marc.theaimsgroup.com/?l=git&m=111558757202243&w=2 # # Until that version is released you may have to apply the patch # yourself - yes, all 6 characters of it! # all: html man html: $(DOC_HTML) pdf: $(DOC_PDF) $(DOC_HTML) $(DOC_MAN1): asciidoc.conf man: man1 man1: $(DOC_MAN1) install: man $(INSTALL) -d -m755 $(DESTDIR)$(man1dir) $(INSTALL) -m644 $(DOC_MAN1) $(DESTDIR)$(man1dir) install-html: html $(INSTALL) -d -m755 $(DESTDIR)$(htmldir) $(INSTALL) -m644 $(DOC_HTML) $(DESTDIR)$(htmldir) # # Determine "include::" file references in asciidoc files. # doc.dep : $(wildcard *.txt) build-docdep.perl rm -f $@+ $@ perl ./build-docdep.perl >$@+ mv $@+ $@ -include doc.dep clean: rm -f *.xml *.html *.pdf *.1 doc.dep $(COMMANDS_TXT) command-list.txt ALL_PY = $(shell find ../stgit -name '*.py') $(COMMANDS_TXT): $(ALL_PY) $(PYTHON) ../stg-build --asciidoc $(basename $(subst stg-,,$@)) > $@ command-list.txt: $(ALL_PY) $(PYTHON) ../stg-build --cmd-list > $@ %.html : %.txt $(ASCIIDOC) -b xhtml11 -d manpage -f asciidoc.conf $(ASCIIDOC_EXTRA) $< %.1 : %.xml xmlto -m callouts.xsl man $< %.xml : %.txt $(ASCIIDOC) -b docbook -d manpage -f asciidoc.conf $< %.pdf: %.xml xmlto pdf $< # special formatting rules tutorial.html : %.html : %.txt $(ASCIIDOC) -b xhtml11 -d article -a toc -f tutorial.conf \ $(ASCIIDOC_EXTRA) $< tutorial.xml : %.xml : %.txt $(ASCIIDOC) -b docbook -d article -f tutorial.conf $< stgit-0.19/Documentation/SubmittingPatches000066400000000000000000000401721337022307200207710ustar00rootroot00000000000000IMPORTANT: The StGit mailing list is no longer available due to the shutdown of the gna.org website. Until a decision is made on setting up a new mailing list, please send patches to catalin.marinas@gmail.com or via the project page at https://github.com/ctmarinas/stgit. Checklist (and a short version for the impatient): Commits: - Make commits of logical units. - Check for unnecessary whitespace with "git diff --check" before committing. - Do not check in commented out code or unneeded files. - Provide a meaningful commit message. - The first line of the commit message should be a short description and should skip the full stop. - If you want your work included in StGit, add a "Signed-off-by: Your Name " line to the commit message (or just use the option "-s" when committing) to confirm that you agree to the Developer's Certificate of Origin. - Make sure that you have tests for the bug you are fixing. - Make sure that the test suite passes after your commit. Patch: - Preferably use "stg mail" to send patches. The first time, it's a good idea to try to mail the patches to yourself to see that everything works. - Do not PGP sign your patch. - Do not attach your patch, but read in the mail. body, unless you cannot teach your mailer to leave the formatting of the patch alone. - Be careful doing cut & paste into your mailer, not to corrupt whitespaces. - Provide additional information (which is unsuitable for the commit message) between the "---" and the diffstat. (The -E option to stg mail lets you edit the message before you send it out.) - If you change, add, or remove a command line option or make some other user interface change, the associated documentation should be updated as well. - If your name is not writable in ASCII, make sure that you send off a message in the correct encoding. - Send the patch to the list (TBD) and the maintainer (catalin.marinas@gmail.com) if (and only if) the patch is ready for inclusion. Long version: 1. Make separate commits for logically separate changes. Unless your patch is really trivial, you should not be sending out a patch that was generated between your working tree and your commit head. Instead, always make a commit with complete commit message and generate a series of patches from your repository. It is a good discipline. Describe the technical detail of the change(s). If your description starts to get too long, that's a sign that you probably need to split up your commit to finer grained pieces. Oh, another thing. I am picky about whitespaces. Please run git diff --check on your changes before you commit. 2. Generate your patch using Git tools out of your commits. Git based diff tools (Git, Cogito, and StGit included) generate unidiff which is the preferred format. You do not have to be afraid to use -M option to "git diff" and friends, if your patch involves file renames. The receiving end can handle them just fine. Please make sure your patch does not include any extra files which do not belong in a patch submission. Make sure to review your patch after generating it, to ensure accuracy. Before sending out, please make sure it cleanly applies to the "master" branch head. If you are preparing a work based on some other branch, that is fine, but please mark it as such. 3. Sending your patches. StGit patches should be sent to the StGit mailing list (TBD), and preferably CCed to the StGit maintainer (catalin.marinas@gmail.com). The recipients need to be able to read and comment on the changes you are submitting. It is important for a developer to be able to "quote" your changes, using standard e-mail tools, so that they may comment on specific portions of your code. For this reason, all patches should be submitted "inline". WARNING: Be wary of your MUAs word-wrap corrupting your patch. Do not cut-n-paste your patch; you can lose tabs that way if you are not careful. It is a common convention to prefix your subject line with [StGit PATCH]. This lets people easily distinguish patches to StGit from other e-mail discussions and patches meant for Git itself. Use of additional markers after PATCH and the closing bracket to mark the nature of the patch is also encouraged. E.g. [PATCH/RFC] is often used when the patch is not ready to be applied but it is for discussion, [PATCH v2], [PATCH v3] etc. are often seen when you are sending an update to what you have previously sent. "stg mail" command follows the best current practice to format the body of an e-mail message. At the beginning of the patch should come your commit message, ending with the Signed-off-by: lines, and a line that consists of three dashes, followed by the diffstat information and the patch itself. If you are forwarding a patch from somebody else, optionally, at the beginning of the e-mail message just before the commit message starts, you can put a "From:" line to name that person. You often want to add additional explanation about the patch, other than the commit message itself. Place such "cover letter" material between the three dash lines and the diffstat. If you have comments about a whole series of patches, you can include them in a separate cover mail message (the -e option to stg mail). Do not attach the patch as a MIME attachment, compressed or not. Do not let your e-mail client send quoted-printable. Do not let your e-mail client send format=flowed which would destroy whitespaces in your patches. Many popular e-mail applications will not always transmit a MIME attachment as plain text, making it impossible to comment on your code. A MIME attachment also takes a bit more time to process. This does not decrease the likelihood of your MIME-attached change being accepted, but it makes it more likely that it will be postponed. Exception: If your mailer is mangling patches then someone may ask you to re-send them using MIME, that is OK. Do not PGP sign your patch, at least for now. Most likely, your maintainer or other people on the list would not have your PGP key and would not bother obtaining it anyway. Your patch is not judged by who you are; a good patch from an unknown origin has a far better chance of being accepted than a patch from a known, respected origin that is done poorly or does incorrect things. 4. Sign your work To improve tracking of who did what, we've borrowed the "sign-off" procedure from the Git and Linux kernel projects on patches that are being emailed around. Although StGit is a lot smaller project it is a good discipline to follow it. The sign-off is a simple line at the end of the explanation for the patch, which certifies that you wrote it or otherwise have the right to pass it on as a open-source patch. The rules are pretty simple: if you can certify the below: Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. then you just add a line saying Signed-off-by: Random J Developer This line can be automatically added by StGit by any command that accepts the --sign option. Notice that you can place your own Signed-off-by: line when forwarding somebody else's patch with the above rules for D-C-O. Indeed you are encouraged to do so. Do not forget to place an in-body "From: " line at the beginning to properly attribute the change to its true author (see (2) above). Also notice that a real name is used in the Signed-off-by: line. Please don't hide your real name. Some people also put extra tags at the end. "Acked-by:" says that the patch was reviewed by a person who is more familiar with the issues and the area the patch attempts to modify. "Tested-by:" says the patch was tested by the person and found to have the desired effect. ------------------------------------------------ MUA specific hints Some of patches I receive or pick up from the list share common patterns of breakage. Please make sure your MUA is set up properly not to corrupt whitespaces. Here are two common ones I have seen: * Empty context lines that do not have _any_ whitespace. * Non empty context lines that have one extra whitespace at the beginning. One test you could do yourself if your MUA is set up correctly is: * Send the patch to yourself, exactly the way you would, except To: and Cc: lines, which would not contain the list and maintainer address. * Save that patch to a file in UNIX mailbox format. Call it say a.patch. * Try to apply to the tip of the "master" branch from the public repository: $ git fetch http://repo.or.cz/stgit.git master:test-apply $ git checkout test-apply $ git reset --hard $ stg init $ stg import -M a.patch If it does not apply correctly, there can be various reasons. * Your patch itself does not apply cleanly. That is _bad_ but does not have much to do with your MUA. Please rebase the patch appropriately. * Your MUA corrupted your patch; "stg import" would complain that the patch does not apply. * Check the imported patch with e.g. "stg show". If it isn't exactly what you would want to see in the commit log message, it is very likely that the maintainer would end up hand editing the log message when he applies your patch. Things like "Hi, this is my first patch.\n", if you really want to put in the patch e-mail, should come after the three-dash line that signals the end of the commit message. Pine ---- (Johannes Schindelin) I don't know how many people still use pine, but for those poor souls it may be good to mention that the quell-flowed-text is needed for recent versions. ... the "no-strip-whitespace-before-send" option, too. AFAIK it was introduced in 4.60. (Linus Torvalds) And 4.58 needs at least this. --- diff-tree 8326dd8350be64ac7fc805f6563a1d61ad10d32c (from e886a61f76edf5410573e92e38ce22974f9c40f1) Author: Linus Torvalds Date: Mon Aug 15 17:23:51 2005 -0700 Fix pine whitespace-corruption bug There's no excuse for unconditionally removing whitespace from the pico buffers on close. diff --git a/pico/pico.c b/pico/pico.c --- a/pico/pico.c +++ b/pico/pico.c @@ -219,7 +219,9 @@ PICO *pm; switch(pico_all_done){ /* prepare for/handle final events */ case COMP_EXIT : /* already confirmed */ packheader(); +#if 0 stripwhitespace(); +#endif c |= COMP_EXIT; break; (Daniel Barkalow) > A patch to SubmittingPatches, MUA specific help section for > users of Pine 4.63 would be very much appreciated. Ah, it looks like a recent version changed the default behavior to do the right thing, and inverted the sense of the configuration option. (Either that or Gentoo did it.) So you need to set the "no-strip-whitespace-before-send" option, unless the option you have is "strip-whitespace-before-send", in which case you should avoid checking it. Thunderbird ----------- (A Large Angry SCM) Here are some hints on how to successfully submit patches inline using Thunderbird. This recipe appears to work with the current [*1*] Thunderbird from Suse. The following Thunderbird extensions are needed: AboutConfig 0.5 http://aboutconfig.mozdev.org/ External Editor 0.7.2 http://globs.org/articles.php?lng=en&pg=8 1) Prepare the patch as a text file using your method of choice. 2) Before opening a compose window, use Edit->Account Settings to uncheck the "Compose messages in HTML format" setting in the "Composition & Addressing" panel of the account to be used to send the patch. [*2*] 3) In the main Thunderbird window, _before_ you open the compose window for the patch, use Tools->about:config to set the following to the indicated values: mailnews.send_plaintext_flowed => false mailnews.wraplength => 0 4) Open a compose window and click the external editor icon. 5) In the external editor window, read in the patch file and exit the editor normally. 6) Back in the compose window: Add whatever other text you wish to the message, complete the addressing and subject fields, and press send. 7) Optionally, undo the about:config/account settings changes made in steps 2 & 3. [Footnotes] *1* Version 1.0 (20041207) from the MozillaThunderbird-1.0-5 rpm of Suse 9.3 professional updates. *2* It may be possible to do this with about:config and the following settings but I haven't tried, yet. mail.html_compose => false mail.identity.default.compose_html => false mail.identity.id?.compose_html => false (Lukas Sandström) There is a script in contrib/thunderbird-patch-inline which can help you include patches with Thunderbird in an easy way. To use it, do the steps above and then use the script as the external editor. Gnus ---- '|' in the *Summary* buffer can be used to pipe the current message to an external program, and this is a handy way to drive "git am". However, if the message is MIME encoded, what is piped into the program is the representation you see in your *Article* buffer after unwrapping MIME. This is often not what you would want for two reasons. It tends to screw up non ASCII characters (most notably in people's names), and also whitespaces (fatal in patches). Running 'C-u g' to display the message in raw form before using '|' to run the pipe can work this problem around. KMail ----- This should help you to submit patches inline using KMail. 1) Prepare the patch as a text file. 2) Click on New Mail. 3) Go under "Options" in the Composer window and be sure that "Word wrap" is not set. 4) Use Message -> Insert file... and insert the patch. 5) Back in the compose window: add whatever other text you wish to the message, complete the addressing and subject fields, and press send. Gmail ----- Submitting properly formatted patches via Gmail is simple now that IMAP support is available. First, edit your ~/.gitconfig to specify your account settings: [imap] folder = "[Gmail]/Drafts" host = imaps://imap.gmail.com user = user@gmail.com pass = p4ssw0rd port = 993 sslverify = false Next, ensure that your Gmail settings are correct. In "Settings" the "Use Unicode (UTF-8) encoding for outgoing messages" should be checked. Once your commits are ready to send to the mailing list, run the following command to send the patch emails to your Gmail Drafts folder. $ git format-patch -M --stdout origin/master | git imap-send Go to your Gmail account, open the Drafts folder, find the patch email, fill in the To: and CC: fields and send away! stgit-0.19/Documentation/asciidoc.conf000066400000000000000000000047271337022307200200440ustar00rootroot00000000000000[attributes] asterisk=* plus=+ caret=^ startsb=[ endsb=] tilde=~ ifdef::backend-docbook[] ifndef::docbook-xsl-172[] # "unbreak" docbook-xsl v1.68 for manpages. v1.69 works with or without this. # v1.72 breaks with this because it replaces dots not in roff requests. [listingblock] {title} ifdef::doctype-manpage[] .ft C endif::doctype-manpage[] | ifdef::doctype-manpage[] .ft endif::doctype-manpage[] {title#} endif::docbook-xsl-172[] endif::backend-docbook[] ifdef::doctype-manpage[] ifdef::backend-docbook[] [header] template::[header-declarations] {mantitle} {manvolnum} StGit {stgit_version} StGit Manual {manname} {manpurpose} endif::backend-docbook[] endif::doctype-manpage[] ## linkman: macro # # Usage: linkman:command[manpage-section] # # Note, {0} is the manpage section, while {target} is the command. # # Show link as: (
); if section is defined, else just # show the command. ifdef::backend-docbook[] [linkman-inlinemacro] {0%{target}} {0#} {0#{target}{0}} {0#} endif::backend-docbook[] ifdef::backend-xhtml11[] [linkman-inlinemacro] {target}{0?({0})} endif::backend-xhtml11[] ## linkstg: macro # # Usage: linkstg:command[] # # Show StGit link as: stg-(1) in man pages, stg in # html. ifdef::backend-docbook[] [linkstg-inlinemacro] stg-{target}1 endif::backend-docbook[] ifdef::backend-xhtml11[] [linkstg-inlinemacro] stg {target} endif::backend-xhtml11[] ## linkstgsub: macro # # Usage: linkstgsub:command[] # # Show StGit link as: . ifdef::backend-docbook[] [linkstgsub-inlinemacro] {target} endif::backend-docbook[] ifdef::backend-xhtml11[] [linkstgsub-inlinemacro] {target} endif::backend-xhtml11[] [macros] # regexen to match macro templates above (?Plinkman):(?P\w+)\[(?P\d+)]= (?Plinkstgsub):(?P\w+)\[]= (?Plinkstg):(?P\w+)\[]= stgit-0.19/Documentation/build-docdep.perl000077500000000000000000000020311337022307200206230ustar00rootroot00000000000000#!/usr/bin/perl my %include = (); my %included = (); for my $text (<*.txt>) { open I, '<', $text || die "cannot read: $text"; while () { if (/^include::/) { chomp; s/^include::\s*//; s/\[\]//; $include{$text}{$_} = 1; $included{$_} = 1; } } close I; } # Do we care about chained includes??? my $changed = 1; while ($changed) { $changed = 0; while (my ($text, $included) = each %include) { for my $i (keys %$included) { # $text has include::$i; if $i includes $j # $text indirectly includes $j. if (exists $include{$i}) { for my $j (keys %{$include{$i}}) { if (!exists $include{$text}{$j}) { $include{$text}{$j} = 1; $included{$j} = 1; $changed = 1; } } } } } } while (my ($text, $included) = each %include) { if (! exists $included{$text} && (my $base = $text) =~ s/\.txt$//) { my ($suffix) = '1'; if ($base eq 'git') { $suffix = '7'; # yuck... } print "$base.html $base.$suffix : ", join(" ", keys %$included), "\n"; } } stgit-0.19/Documentation/callouts.xsl000066400000000000000000000020411337022307200177600ustar00rootroot00000000000000 .sp .br stgit-0.19/Documentation/stg.txt000066400000000000000000000131071337022307200167450ustar00rootroot00000000000000stg(1) ====== Yann Dirson NAME ---- stg - Manage stacks of patches using the Git content tracker SYNOPSIS -------- [verse] 'stg' [--version | --help] 'stg' [--help | --help] 'stg' [COMMAND OPTIONS] [ARGS] DESCRIPTION ----------- StGit (Stacked Git) is an application that provides a convenient way to maintain a 'patch stack' on top of a Git branch: * The topmost (most recent) commits of a branch are given names. Such a named commit is called a 'patch'. * After making changes to the worktree, you can incorporate the changes into an existing patch; this is called 'refreshing'. You may refresh any patch, not just the topmost one. * You can 'pop' a patch: temporarily putting it aside, so that the patch below it becomes the topmost patch. Later you may 'push' it onto the stack again. Pushing and popping can be used to reorder patches. * You can easily 'rebase' your patch stack on top of any other Git commit. (The 'base' of a patch stack is the most recent Git commit that is not an StGit patch.) For example, if you started making patches on top of someone else's branch, and that person publishes an updated branch, you can take all your patches and apply them on top of the updated branch. * As you would expect, changing what is below a patch can cause that patch to no longer apply cleanly -- this can occur when you reorder patches, rebase patches, or refresh a non-topmost patch. StGit uses Git's rename-aware three-way merge capability to automatically fix up what it can; if it still fails, it lets you manually resolve the conflict just like you would resolve a merge conflict in Git. * The patch stack is just some extra metadata attached to regular Git commits, so you can continue to use most Git tools along with StGit. Typical uses ~~~~~~~~~~~~ Tracking branch:: Tracking changes from a remote branch, while maintaining local modifications against that branch, possibly with the intent of sending some patches upstream. You can modify your patch stack as much as you want, and when your patches are finally accepted upstream, the permanent recorded Git history will contain just the final sequence of patches, and not the messy sequence of edits that produced them. + Commands of interest in this workflow are e.g. linkstgsub:rebase[] and linkstgsub:mail[]. Development branch:: Even if you have no "upstream" to send patches to, you can use StGit as a convenient way to modify the recent history of a Git branch. For example, instead of first committing change 'A', then change 'B', and then 'A2' to fix 'A' because it wasn't quite right, you could incorporate the fix directly into 'A'. This way of working results in a much more readable Git history than if you had immortalized every misstep you made on your way to the right solution. + Commands of interest in this workflow are e.g. linkstgsub:uncommit[], which can be used to move the patch stack base downwards -- i.e., turn Git commits into StGit patches after the fact -- and linkstgsub:commit[], its inverse. For more information, see link:tutorial.html[the tutorial]. Specifying patches ~~~~~~~~~~~~~~~~~~ Many StGit commands take references to StGit patches as arguments. Patches in the stack are identified with short names, each of which must be unique in the stack. Patches in the current branch are simply referred to by their name. Some commands allow you to specify a patch in another branch of the repository; this is done by prefixing the patch name with the branch name and a colon (e.g. +otherbranch:thatpatch+). Specifying commits ~~~~~~~~~~~~~~~~~~ Some StGit commands take Git commits as arguments. StGit accepts all commit expressions that Git does; and in addition, a patch name (optionally prefixed by a branch name and a colon) is allowed in this context. The usual Git modifiers $$^$$ and $$~$$ are also allowed; e.g., +abranch:apatch~2+ is the grandparent of the commit that is the patch +apatch+ on branch +abranch+. Instead of a patch name, you can say +$${base}$$+ to refer to the stack base (the commit just below the bottommost patch); so, +abranch:$${base}$$+ is the base of the stack in branch +abranch+. If you need to pass a given StGit reference to a Git command, linkstg:id[] will convert it to a Git commit id for you. OPTIONS ------- The following generic option flags are available. Additional options are available for (and documented with) the different subcommands. --version:: Prints the StGit version, as well as version of other components used, such as Git and Python. --help:: Prints the synopsis and a list of all subcommands. If an StGit subcommand is given, prints the synposis for that subcommand. STGIT COMMANDS -------------- We divide StGit commands in thematic groups, according to the primary type of object they create or change. ifdef::backend-docbook[] Here is a short description of each command. A more detailed description is available in individual command manpages. Those manpages are named 'stg-(1)'. endif::backend-docbook[] include::command-list.txt[] CONFIGURATION MECHANISM ----------------------- StGit uses the same configuration mechanism as Git. See linkman:git[7] for more details. TEMPLATES --------- A number of StGit commands make use of template files to provide useful default texts to be edited by the user. These +.tmpl+ template files are searched in the following directories: . +$GITDIR/+ (in practice, the +.git/+ directory in your repository) . +$HOME/.stgit/templates/+ . +/usr/share/stgit/templates/+ stgit-0.19/Documentation/tutorial.conf000066400000000000000000000000561337022307200201200ustar00rootroot00000000000000[titles] underlines="##","==","--","~~","^^" stgit-0.19/Documentation/tutorial.txt000066400000000000000000001110601337022307200200100ustar00rootroot00000000000000StGit tutorial ============== StGit is a command-line application that provides functionality similar to link:http://savannah.nongnu.org/projects/quilt/[Quilt] (i.e. pushing/popping patches to/from a stack), but using Git instead of +diff+ and +patch+. StGit stores its patches in a Git repository as normal Git commits, and provides a number of commands to manipulate them in various ways. This tutorial assumes you are already familiar with the basics of Git (for example, branches, commits, and conflicts). For more information on Git, see linkman:git[1] or link:http://git.or.cz/[the Git home page]. Help ==== For a full list of StGit commands: $ stg help For quick help on individual subcommands: $ stg help For more extensive help on a subcommand: $ man stg- (The documentation is also available in link:stg.html[HTML format].) Getting started =============== StGit is not a stand-alone program -- it operates on a Git repository that you have already created, using +git init+ or +git clone+. So get one of those; if you don't have one at hand, try for example $ git clone git://repo.or.cz/stgit.git $ cd stgit Before you can create StGit patches, you have to run linkstg:init[]: $ stg init This initializes the StGit metadata for the current branch. (So if you want to have StGit patches in another branch too, you need to run +stg init+ again in that branch.) NOTE: As a shortcut, linkstg:clone[] will run +git clone+ followed by +stg init+ for you. Creating a patch ---------------- Now we're ready to create our first patch: $ stg new my-first-patch This will create a patch called +my-first-patch+, and open an editor to let you edit the patch's commit message. (If you don't give a name on the command line, StGit will make one up based on the first line of the commit message.) This patch is empty, as linkstg:show[] will tell you: $ stg show But it won't stay that way for long! Open one of the files in your favorite text editor, change something, and save. You now have some local changes in your tree: $ stg status M stgit/main.py Then linkstgsub:refresh[] the patch: $ stg refresh And voilà -- the patch is no longer empty: $ stg show commit 3de32068c600d40d8af2a9cf1f1c762570ae9610 Author: Audrey U. Thor Date: Sat Oct 4 16:10:54 2008 +0200 Tell the world that I've made a patch diff --git a/stgit/main.py b/stgit/main.py index e324179..6398958 100644 --- a/stgit/main.py +++ b/stgit/main.py @@ -171,6 +171,7 @@ def _main(): sys.exit(ret or utils.STGIT_SUCCESS) def main(): + print 'My first patch!' try: _main() finally: (I'm assuming you're already familiar with link:http://en.wikipedia.org/wiki/Diff#Unified_format[unified diff] patches like this from Git, but it's really quite simple; in this example, I've added the +$$print 'My first patch!'$$+ line to the file +stgit/main.py+, at around line 171.) Since the patch is also a regular Git commit, you can also look at it with regular Git tools such as linkman:gitk[]. Creating another patch ---------------------- We want to make another improvement, so let's create a new patch for it: $ echo 'Audrey U. Thor' > AUTHORS $ stg new credit --message 'Give me some credit' $ stg refresh Note that we can give the commit message on the command line, and that it doesn't matter whether we run linkstg:new[] before or after we edit the files. So now we have two patches: $ stg series --description + my-first-patch # This is my first patch > credit # Give me some credit linkstg:series[] lists the patches from bottom to top; +$$+$$+ means that a patch is 'applied', and +>+ that it is the 'current', or topmost, patch. If we want to make further changes to the topmost patch, we just edit the files and run +stg refresh+. But what if we wanted to change +my-first-patch+? The simplest way is to linkstgsub:pop[] the +credit+ patch, so that +my-first-patch+ becomes topmost again: $ stg pop credit Checking for changes in the working directory ... done Popping patch "credit" ... done Now at patch "my-first-patch" $ stg series --description > my-first-patch # This is my first patch - credit # Give me some credit linkstg:series[] now shows that +my-first-patch+ is topmost again, which means that linkstg:refresh[] will update it with any changes we make. The minus sign says that +credit+ is 'unapplied' -- this means that it's been temporarily put aside. If you look at the +AUTHORS+ file, you'll see that our change to it is gone; and tools such as linkman:gitk[] will not show it, because it's been edited out of the Git history. But it's just one linkstg:push[] command away from being restored: $ stg push credit Checking for changes in the working directory ... done Fast-forwarded patch "credit" Now at patch "credit" NOTE: You can omit the patch name argument to linkstg:push[] and linkstg:pop[]. If you do, you will push the next unapplied patch, and pop the topmost patch, respectively. NOTE: There are at least two more ways to update a non-topmost patch. One is to use linkstg:refresh[] with the +$$--patch$$+ flag, the other to create a new patch for the update and then merge it into the other patch with linkstg:squash[]. Keeping commit messages up to date ---------------------------------- Since StGit is all about creating readable Git history (or a readable patch series, which is essentially the same thing), one thing you'll want to pay attention to is the commit messages of your patches. linkstg:new[] asks you for a commit message when you create a new patch, but as time goes by and you refresh the patch again and again, chances are that the original commit message isn't quite correct anymore. Fortunately, editing the commit message is very easy: $ stg edit In addition to linkstg:edit[], you can also give the +$$--edit$$+ flag to linkstg:refresh[] -- that way, you get to change the commit message and update the patch at the same time. Use whichever feels most natural to you. NOTE: linkstg:edit[] has a +$$--diff$$+ flag, which gives you the diff text and not just the commit message in your editor. Be aware, though, that if you change the diff so that it no longer applies, the edit will be saved to a file instead of being carried out. If you're not comfortable editing diffs, just treat +$$--diff$$+ as a way to get to 'see' the diff while you edit the commit message. If the patch changes considerably, it might even deserve a new name. linkstg:rename[] is your friend there. Conflicts --------- Normally, when you pop a patch, change something, and then later push it again, StGit sorts out everything for you automatically. For example, let's create two patches that modify different files: $ stg clone http://repo.or.cz/stgit.git stgit $ cd stgit $ stg new first --message 'First patch' $ echo '- Do something' >> TODO $ stg refresh $ stg new second --message 'Second patch' $ echo '- Install something' >> INSTALL $ stg refresh then pop them both: $ stg pop --all and then push them in the opposite order: $ stg push second first $ stg series + second > first StGit had no problems reordering these patches for us, since they didn't touch the same file. But it would have worked just fine even if they had touched the same file, as long as they didn't change the same part of the file. But what if they did? Let's find out. $ stg pop Checking for changes in the working directory ... done Popping patch "first" ... done Now at patch "second" $ echo '- Do something else' >> TODO $ stg refresh Now, both patches add a new line at the end of +TODO+. So what happens when we try to have them both applied? $ stg push Pushing patch "first" ... CONFLICT (content): Merge conflict in TODO Error: The merge failed during "push". Revert the operation with "stg undo". stg push: 1 conflict(s) StGit is telling us that it couldn't figure out how to push +first+ on top of +second+, now that they both modify +TODO+. We can take a look at the situation with linkstg:status[]: $ stg status C TODO As we were told by linkstg:push[], the conflict is in the file +TODO+. (If the patch was bigger and touched multiple files, they would all be listed here; prefixed with +C+ if they had conflicts, and +M+ if StGit managed to automatically resolve everything in the file.) At this point, we have two options: 1. Undo the failed merge with linkstg:undo[]. (Remember to use the +$$--hard$$+ flag, since the unresolved conflict means the worktree is not clean.) 2. Manually resolve the conflict (editing the file directly followed by +git add+ or using +git mergetool+.) To resolve the conflict, open +TODO+ in your favorite editor. It ends like this: ---------------------------------------------------------------------- - numeric shortcuts for naming patches near top (eg. +1, -2) - (config?) parameter for number of patches included by "series -s" <<<<<<< current:TODO - Do something else ======= - Do something >>>>>>> patched:TODO ---------------------------------------------------------------------- The 'conflict markers' +<<<<<<<+, +=======+, and +>>>>>>>+ indicate which lines were already there (+current+) and which were added by the patch (+patched+). Edit the file so that it looks like it should; in this case, we want something like this: ---------------------------------------------------------------------- - numeric shortcuts for naming patches near top (eg. +1, -2) - (config?) parameter for number of patches included by "series -s" - Do something - Do something else ---------------------------------------------------------------------- Note that ``looks like it should'' includes removing the conflict markers. Now that we've resolved the conflict, we just need to tell StGit about it: $ git add TODO $ stg status M TODO +TODO+ is listed as being modified, not in conflict. And we know from before how to deal with modified files: $ stg refresh The conflict is now resolved. We can see that +first+ now looks a little different; it no longer adds a line at the end of the file: $ stg show commit 8e3ae5f6fa6e9a5f831353524da5e0b91727338e Author: Audrey U. Thor Date: Sun Oct 5 14:43:42 2008 +0200 First patch diff --git a/TODO b/TODO index 812d236..4ef3841 100644 --- a/TODO +++ b/TODO @@ -24,4 +24,5 @@ The future, when time allows or if someone else does them: they have scripts for moving the changes in one to the others) - numeric shortcuts for naming patches near top (eg. +1, -2) - (config?) parameter for number of patches included by "series -s" +- Do something - Do something else Workflow: Development branch ============================ One common use of StGit is to ``polish'' a Git branch before you publish it for others to see. Such history falsification can often be a 'good' thing -- when you (or someone else) needs to look at what you did six months later, you are not really interested in all the false starts and the steps needed to corect them. What you want is the final solution, presented in a way that makes it easy to read and understand. Of course, there are limits. Editing the last few days' worth of history is probably a good idea; editing the last few months' probably isn't. A rule of thumb might be to not mess with history old enough that you don't remember the details anymore. And rewriting history that you have published for others to see (and base their own work on) usually just makes everyone more confused, not less. So, let's take a concrete example. Say that you're hacking on StGit, and have made several Git commits as your work progressed, with commit messages such as ``Improve the snarfle cache'', ``Remove debug printout'', ``New snarfle cache test'', ``Oops, spell function name correctly'', ``Fix documentation error'', and ``More snarfle cache''. Now, this is the actual history, but for obvious reasons, this isn't the kind of history you'd ideally want to find when you six months from now try to figure out exactly where that elusive snarfle cache bug was introduced. So let's turn this into the history we can be proud of. The first step is to make StGit patches out of all those Git commits: $ stg uncommit --number 6 Uncommitting 6 patches ... Now at patch "more-snarfle-cache" done $ stg series --description + improve-the-snarfle-cache # Improve the snarfle cache + remove-debug-printout # Remove debug printout + new-snarfle-cache-test # New snarfle cache test + oops-spell-function-name-corre # Oops, spell function name correctly + fix-documentation-error # Fix documentation error > more-snarfle-cache # More snarfle cache As you can see, linkstg:uncommit[] adds StGit metadata to the last few Git commits, turning them into StGit patches so that we can do stuff with them. NOTE: With the +$$--number$$+ flag, linkstg:uncommit[] uncommits that many commits and generates names for them based on their commit messages. If you like, you can instead list the patch names you want on the command line. At this point, there are a number of things we could do: * Continue developing, and take advantage of e.g. linkstg:goto[] or +stg refresh $$--patch$$+ to stick updates in the right patch to begin with. * Use e.g. linkstg:float[], linkstg:sink[], linkstg:push[], and linkstg:pop[] to reorder patches. * Use linkstg:squash[] to merge two or more patches into one. linkstgsub:squash[] pushes and pops so that the patches to be merged are consecutive and unrelated patches aren't in the way, then makes one big patch out of the patches to be merged, and finally pushes the other patches back. + Of course, as always when there is pushing involved, there is the possibility of conflicts. If a push results in a conflict, the operation will be halted, and we'll be given the option of either resolving the conflict or undoing. Once we feel that the history is as good as it's going to get, we can remove the StGit metadata, turning the patches back into regular Git commits again: $ stg commit --all TIP: linkstg:commit[] can also commit specific patches (named on the command line), leaving the rest alone. This can be used to retire patches as they mature, while keeping the newer and more volatile patches as patches. Workflow: Tracking branch ========================= In the 'Development branch' workflow described above, we didn't have to worry about other people; we're working on our branch, they are presumably working on theirs, and when the time comes and we're ready to publish our branch, we'll probably end up merging our branch with those other peoples'. That's how Git is designed to work. Or rather, one of the ways Git is designed to work. An alternative, popular in e.g. the Linux kernel community (for which Git was originally created), is that contributors send their patches by e-mail to a mailing list. Others read the patches, try them out, and provide feedback; often, the patch author is asked to send a new and improved version of the patches. Once the project maintainer is satisfied that the patches are good, she'll 'apply' them to a branch and publish it. StGit is ideally suited for the process of creating patches, mailing them out for review, revising them, mailing them off again, and eventually getting them accepted. Getting patches upstream ------------------------ We've already covered how to clone a Git repository and start writing patches. As for the next step, there are two commands you might use to get patches out of StGit: linkstg:mail[] and linkstg:export[]. linkstg:export[] will export your patches to a filesystem directory as one text file per patch, which can be useful if you are going to send the patches by something other than e-mail. Most of the time, though, linkstg:mail[] is what you want. NOTE: Git comes with tools for sending commits via e-mail. Since StGit patches are Git commits, you can use the Git tools if you like them better for some reason. NOTE: For exporting single patches -- as opposed to a whole bunch of them -- you could also use linkstg:show[] or linkstg:diff[]. Mailing a patch is as easy as this: $ stg mail --to recipient@example.com You can list one or more patches, or ranges of patches. Each patch will be sent as a separate mail, with the first line of the commit message as subject line. Try mailing patches to yourself to see what the result looks like. NOTE: linkstg:mail[] uses +sendmail+ on your computer to send the mails. If you don't have +sendmail+ properly set up, you can instruct it to use any SMTP server with the +$$--smtp-server$$+ flag. There are many command-line options to control exactly how mails are sent, as well as a message template you can modify if you want. The man page has all the details; I'll just mention two more here. +$$--edit-cover$$+ will open an editor and let you write an introductory message; all the patch mails will then be sent as replies to this 'cover message'. This is usually a good idea if you send more than one patch, so that reviewers can get a quick overview of the patches you sent. +$$--edit-patches$$+ will let you edit each patch before it is sent. You can change anything, but note that you are only editing the outgoing mail, not the patch itself; if you want to make changes to the patch, you probably want to use the regular StGit commands to do so. What this 'is' useful for, though, is to add notes for the patch recipients: ---------------------------------------------------------------------- From: Audrey U. Thor Subject: [PATCH] First line of the commit message The rest of the commit message --- Everything after the line with the three dashes and before the diff is just a comment, and not part of the commit message. If there's anything you want the patch recipients to see, but that shouldn't be recorded in the history if the patch is accepted, write it here. stgit/main.py | 1 + 1 files changed, 1 insertions(+), 0 deletions(-) diff --git a/stgit/main.py b/stgit/main.py index e324179..6398958 100644 --- a/stgit/main.py +++ b/stgit/main.py @@ -171,6 +171,7 @@ def _main(): sys.exit(ret or utils.STGIT_SUCCESS) def main(): + print 'My first patch!' try: _main() finally: ---------------------------------------------------------------------- Rebasing a patch series ----------------------- While you are busy writing, submitting, and revising your patch series, other people will be doing the same thing. As a result, even though you started writing your patches on top of what was the latest history at the time, your stack base will grow ever more out of date. When you clone a repository, $ stg clone http://repo.or.cz/stgit.git stgit you initially get one local branch, +master+. You also get a number of 'remote' branches, one for each branch in the repository you cloned. In the case of the StGit repository, these are +remotes/origin/stable+, +remotes/origin/master+, and +remotes/origin/proposed+. +remotes+ means that it's not a local branch, just a snapshot of a branch in another repository; and +origin+ is the default name for the first remote repository (you can set up more; see the man page for +git remote+). Right after cloning, +master+ and +remotes/origin/master+ point at the same commit. When you start writing patches, +master+ will advance, and always point at the current topmost patch, but +remotes/origin/master+ will stay the same because it represents the master branch in the repository you cloned from -- your 'upstream' repository. Unless you are the only one working on the project, however, the upstream repository will not stay the same forever. New commits will be added to its branches; to update your clone, run $ git remote update This will update all your remote branches, but won't touch your local branches. To get the latest changes into your local +master+ branch, use linkstg:rebase[]: $ stg rebase remotes/origin/master This command will do three things: 1. Pop all patches, so that your local branch (+master+, in this example) points at the stack base. This is the same commit that +remotes/origin/master+ pointed at at the time you started writing your patches. 2. Set the stack base to the given commit (the current, updated value of +remotes/origin/master+). 3. Push the patches that were popped in the first step. The end result is that your patches are now applied on top of the latest version of +remotes/origin/master+. The primary reason for rebasing is to reduce the amount of conflicts between your work and others'. If one of your patches changes the same part of the same file as a patch someone else has written, you will get a conflict when you run linkstg:rebase[] the next time after the other person's patch has been accepted upstream. It is almost always less work to rebase often and resolve these one at a time, rather than a whole lot at once. After all, you have to rebase eventually; if you mail out patches that are based on an outdated branch, everyone who tries to apply them has to resolve the conflicts instead. There are more effective ways to get popular. When your patches are accepted ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If and when some or all of your patches are accepted upstream, you update and rebase just like usual -- but be sure to use the +$$--merged$$+ flag to linkstg:rebase[]: $ git remote update $ stg rebase --merged remotes/origin/master This flag makes the rebase operation better at detecting that your patches have been merged, at some cost in performance. The patches that had been merged will still be present in your patch stack after the rebase, but they will be empty, since the change they added is now already present in the stack base. Run linkstg:clean[] to get rid of such empty patches if you don't want them hanging around: $ stg clean Importing patches ----------------- While you are busy producing patches, there's hopefully someone -- the 'maintainer' -- at the other end who recieves them and 'applies' them to her Git tree, which is then published for all (or parts of) the world to see. It's perfectly fine for this person to not have the foggiest idea what StGit is. In that case, she'll probably apply your patches with something like +git am+, and everything will just work, exactly as if you'd used Git to send those patches. But she might be an StGit user too, in which case she might use linkstg:import[]. There are basically four kinds if stuff you can import with linkstg:import[]: 1. A patch in a file. 2. Several files containing one patch each, and a 'series' file listing those other files in the correct order. 3. An e-mail containing a single patch. 4. A mailbox file (in standard Unix +mbox+ format) containing multiple e-mails with one patch in each. Importing a plain patch ~~~~~~~~~~~~~~~~~~~~~~~ Importing a plain patch, such as produced by e.g. GNU +diff+, +git diff+, +git show+, linkstg:diff[], or linkstg:show[], is very easy. Just say $ stg import my-patch and you'll have a new patch at the top of your stack. If you don't give a file name on the command line, linkstg:import[] will read the patch from its standard input -- in other words, you can pipe a patch to it directly from the command that produces it. By default, the new patch's name will be taken from the file name, and its commit message and author info will be taken from the beginning of the patch, if they are there. However, there are command line switches to override all of these things; see the man page for details. Importing several patches at once ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Some programs -- among them linkstg:export[] -- will create a bunch of files with one patch in each, and a 'series' file (often called +series+) listing the other files in the correct order. Give +$$--series$$+ and the name of the series file to linkstg:import[], and it will import all the patches for you, in the correct order. Importing a patch from an e-mail ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Importing a patch from an e-mail is simple too: $ stg import --mail my-mail The e-mail should be in standard Git mail format (which is what e.g. linkstg:mail[] produces) -- that is, with the patch in-line in the mail, not attached. The authorship info is taken from the mail headers, and the commit message is read from the 'Subject:' line and the mail body. If you don't give a file name, the mail will be read from the standard input. This means that, if your mail reader supports it, you can pipe a mail directly to +stg import $$--mail$$+ and the patch will be applied. Importing a mailbox full of patches ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Finally, in case importing one patch at a time is too much work, linkstg:import[] also accepts an entire Unix +mbox+-format mailbox, either on the command line or on its standard input; just use the +$$--mbox$$+ flag. Each mail should contain one patch, and is imported just like with +$$--mail$$+. Mailboxes full of patches are produced by e.g. linkstg:mail[] with the +$$--mbox$$+ flag, but most mail readers can produce them too, meaning that you can copy all the patch mails you want to apply to a separate mailbox, and then import them all in one go. Other stuff that needs to be placed somewhere ============================================= Undo ---- TODO:: undo, redo, log, reset Interoperating with Git ----------------------- TODO:: * git commit + repair * git reset HEAD~n + repair * don't do git rebase or git merge, because it won't work Patch stuff ----------- TODO:: This section needs revising. I've only fixed the formatting. Most of it should go under "Workflow: Tracking branch" As mentioned in the introduction, StGit stores modifications to your working tree in the form of Git commits. This means if you want to apply your changes to a tree not managed by Git, or send your changes to someone else in e-mail, you need to convert your StGit patches into normal textual diffs that can be applied with the GNU patch command. linkstg:diff[] is a powerful way to generate and view textual diffs of patches managed by StGit. To view a diff of the topmost patch: $ stg diff -r / Observe that this does not show any changes in the working directory that have not been saved by a linkstgsub:refresh[]. To view just the changes you've made since the last refresh, use: $ stg diff -r /top If you want to see the changes made by the patch combined with any unsaved changes in the working directory, try: $ stg diff -r /bottom You can also show the changes to any patch in your stack with: $ stg diff -r / Use this command to view all the changes in your stack up through the current patch: $ stg diff -r base linkstg:diff[] supports a number of other features that are very useful. Be sure to take a look at the help information for this command. To convert your StGit patches into patch files: $ stg export [--range=[[:]]] [] linkstg:export[] supports options to automatically number the patches (+-n+) or add the +.diff+ extension (+-d+). If you don't tell linkstgsub:export[] where to put the patches, it will create directory named +patch-+ in your current directory, and store the patches there. To e-mail a patch or range of patches: $ stg mail [--to=...] (--all | --range=[[:]] | ) linkstg:mail[] has a lot of options, so read the output of +stg mail -h+ for more information. You can also import an existing GNU diff patch file as a new StGit patch with a single command. linkstg:import[] will automatically parse through the patch file and extract a patch description. Use: $ stg import [] This is the equivalent of $ stg new $ patch -i $ stg refresh -e Sometimes the patch file won't apply cleanly. In that case, linkstg:import[] will leave you with an empty StGit patch, to which you then apply the patch file by hand using "patch -i" and your favorite editor. To merge a GNU diff file (defaulting to the standard input) into the topmost patch: $ stg fold [] This command supports a +$$--threeway$$+ option which applies the patch onto the bottom of the topmost one and performs a three-way merge. Templates --------- TODO:: This section needs revising. I've only fixed the formatting. linkstg:export[] and linkstg:mail[] use templates for generating the patch files or e-mails. The default templates are installed under +/share/stgit/templates/+ and, combined with the extra options available for these commands, should be enough for most users. The template format uses the standard Python string formatting rules. The variables available are listed in the the manual pages for each command. linkstg:mail[] can also send an initial 'cover' e-mail for which there is no default template. The +/share/stgit/examples/firstmail.tmpl+ file can be used as an example. A default description for new patches can be defined in the +.git/ patchdescr.tmpl+ file. This is useful for things like signed-off-by lines. Emacs ===== StGit comes with an Emacs mode, +stgit-mode+, supporting Emacs versions 22 and later. To start using it, add the +stgit/contrib+ directory to your Emacs load-path and run +(require 'stgit)+. For example, you can add the following to your +.emacs+ file: ---------------------------------------------------------------------- (add-to-list 'load-path "/path/to/stgit/contrib") (require 'stgit) ---------------------------------------------------------------------- Start +stgit-mode+ using +M-x stgit+ and select the directory where the source code you want to use StGit on can be found. If StGit has not been initialized in this directory yet, you will need to run +M-x stgit-init+ before you continue. The +stgit-mode+ buffer (usually named +$$*stgit*$$+) has the following layout: ---------------------------------------------------------------------- Branch: name-of-branch + The first applied patch + Another applied patch > The topmost patch Index Work Tree - An unapplied patch - Another unapplied patch -- ---------------------------------------------------------------------- The above means that the active branch name is +name-of-branch+ and it contains five patches, three of which are applied. The git index and working tree contain no (modified) files. Basic Commands -------------- To get help, press +h+. This opens a new buffer which lists all commands supported in +stgit-mode+. Also, if you have the menu bar enabled (toggled using +M-x menu-bar-mode+), a new menu entry called +StGit+ will appear, from which you can run several StGit commands. As the menu should be self-explanatory, the rest of this tutorial will focus on available keyboard commands. Move the point (cursor) between lines using +C-p+ and +C-n+, or between patches using +p+ and +n+. You can linkstgsub:undo[] and linkstgsub:redo[] StGit commands using +C-/+ and +C-c C-/+, respectively. Creating New Patches -------------------- If you want to create a new patch, first make some changes that should go into it. As you save a file which is Git-controlled, it will appear as a modification in the +Work Tree+ section: ---------------------------------------------------------------------- Work Tree Modified foo.txt ---------------------------------------------------------------------- To create a new patch based on the changes in the index or, if it contains no changes, the working tree, press +c+. This opens a new buffer where you can enter the patch description. When you are done, press +C-c C-c+. Your new patch will now show up in the +$$*stgit*$$+ buffer, and the working tree will no longer contain any modifications: ---------------------------------------------------------------------- + The topmost patch > First line of your new description Index Work Tree ---------------------------------------------------------------------- As you make additional changes in your files, and want to include them in the topmost patch, press +r+, which runs linkstg:refresh[]. If you want to add the changes to a patch which is not topmost, move the point to the line of that patch and press +C-u r+. Inspecting Patches ------------------ To see what a particular patch contains, you can move the point (cursor) to the line of that patch, and press +RET+ (Enter). This will "expand" the patch and show which files it changes: ---------------------------------------------------------------------- + My patch Modified foo.txt Deleted bar.c ---------------------------------------------------------------------- You can press +=+, which will show the diff of that patch or file in a new buffer. With a prefix argument (+C-u =+), the diff will not show changes in whitespace. To visit (open) a modified file in another Emacs window, press +o+ on that line. +RET+ will visit it in the current window. Changing the Patch Series ------------------------- You can linkstgsub:push[] and linkstgsub:pop[] patches using +>+ (pushes the topmost unapplied patch onto the stack) and +<+ (pops the topmost applied patch off the stack). By moving the point to a particular patch and pressing +P+ (+S-p+) you either (if it already was applied) pop that patch off the stack, or (if it was unapplied) push it onto the stack. You can move patches by first marking one or more using +m+. Then, move the point to where in the series you want these patches to move, and press +M+. Use +DEL+ or +u+ to remove a mark. You can also combine (linkstgsub:squash[]) two or more patches by marking them and pressing +S+ (+S-s+). This will open a new buffer where you can edit the patch description of the new, combined, patch. When done, press +C-c C-c+, and the topmost of the marked patches will be replaced in the stack by one combined patch. You can linkstgsub:delete[] a patch by moving to its line and pressing +D+. If you press +C-u D+, the contents of the patch will be spilled to the index. To linkstgsub:edit[] the description of a patch, press +e+. This opens the patch description in a new buffer. Press +C-c C-c+ when you are done editing the patch. These operations may result in merge conflicts; more about that later. Patch Names ----------- By default, the patch description is shown but not the patch names. You can toggle showing the names using +t n+. To rename a patch, press +C-c C-r+. Showing Committed Patches ------------------------- Sometimes it is convenient to be able to investigate already committed patches. Toggle showing these using +t h+. With a prefix argument, you can set how many to show; e.g., +7 t h+ will show seven already committed patches. Using the Index and Working Tree -------------------------------- You can move a changed file between the index and the working tree using +i+. This is useful if your working tree contains a number of changes and you want to create or refresh a patch using only some of the changed files. Once you have the correct set of files in the index, use +c+ to create or +r+ to refresh patches using only the files in the index. If you want to revert a change in either the index or the working tree, move the point to that line and press +U+. If you press +U+ on the +Index+ or +Work Tree+ lines, all the changes in the index or working tree will be reverted. Branches -------- You can switch to another linkstgsub:branch[] by pressing +B+. If you type the name of a branch that does not exist, you will be asked whether to create one. The new branch will be based off the current +HEAD+. Use +C-c C-b+ to linkstgsub:rebase[] the current branch. It will default to rebasing to the +git config+ setting for +branch._branch_.stgit.parentbranch+. Merge Conflicts --------------- If an operation resulted in a merge conflict, the files with conflicts will show as +Unmerged+ in the +$$*stgit*$$+ buffer. To handle the conflicts, you can linkstgsub:undo[] the operation that caused the conflict using +C-u C-/+. Note the +C-u+ prefix, which will tell the undo operation to continue despite the index or working tree containing changes. If you instead want to resovle the changes, you must first edit the files with conflicts to make sure they are in the correct state. Once you have done this, press +R+ on the line of that file, which will remove the +Unmerged+ flag. Once all conflicts have been resolved, you can continue working as normal, for example by refreshing the patch that had the conflict. To investigate the reason of conflicts, you can use the +d b+, +d o+, and +d t+ commands to, respectively, show the diffs against the merge base, our branch, or their branch. +d c+ shows a combined diff. See linkman:git-diff[1] for more information about these commands. A more powerful tool to resolve conflicts is the Emacs +smerge-mode+. To start using it to resolve a conflict, press +d m+. It is outside the scope of this tutorial to explain how to use it, but press +q+ to leave +smerge-mode+. stgit-0.19/INSTALL000066400000000000000000000012251337022307200136250ustar00rootroot00000000000000For basic installation: $ make all doc ;# as yourself $ make install install-doc ;# as yourself By default, the above command installs StGIT in the $HOME/{bin,lib,share} directories. For a different location, use the prefix option. $ make prefix=/usr all doc #; as yourself # make prefix=/usr install install-doc #; as root Issues of note: - StGit requires git version 1.6.1 or later. (Specifically, it needs a git that includes commit 140b378d: "Teach git diff-tree --stdin to diff trees".) - To build and install the documentation, you need to have the asciidoc/xmlto toolchain. The default build target ("make all") does _not_ build them. stgit-0.19/MANIFEST.in000066400000000000000000000010141337022307200143260ustar00rootroot00000000000000include README Makefile MANIFEST.in AUTHORS COPYING INSTALL TODO include RELEASENOTES include stg-build include stg-prof include stg-dbg include templates/*.tmpl include examples/*.tmpl include examples/gitconfig include contrib/*.sh include contrib/stg-* include contrib/Makefile include contrib/stgit.el recursive-include contrib/vim *.vim include t/t*.sh t/t*/* t/Makefile t/README include Documentation/*.txt Documentation/Makefile Documentation/*.conf include Documentation/build-docdep.perl Documentation/callouts.xsl stgit-0.19/Makefile000066400000000000000000000027211337022307200142360ustar00rootroot00000000000000prefix ?= $(HOME) DESTDIR ?= / PYTHON ?= python export DESTDIR PYTHON TEST_PATCHES ?= .. all: $(PYTHON) setup.py build install: $(PYTHON) setup.py install --prefix=$(prefix) --root=$(DESTDIR) --force doc: $(MAKE) -C Documentation all install-doc: $(MAKE) -C Documentation install install-html: $(MAKE) -C Documentation install-html test: $(PYTHON) setup.py build $(MAKE) -C t all test_patches: for patch in $$(stg series --noprefix $(TEST_PATCHES)); do \ stg goto $$patch && $(MAKE) test || break; \ done coverage: coverage-test coverage-report coverage-test: $(PYTHON) -m coverage run setup.py build COVERAGE_PROCESS_START=$(PWD)/.coveragerc $(MAKE) -C t all $(PYTHON) -m coverage combine $$(find . -name '.coverage.*') coverage-report: $(PYTHON) -m coverage html --title="stgit coverage" $(PYTHON) -m coverage report @echo "HTML coverage report: file://$(PWD)/htmlcov/index.html" clean: for dir in Documentation t; do \ $(MAKE) -C $$dir clean; \ done rm -rf build rm -rf dist rm -f stgit/*.pyc rm -rf stgit/__pycache__ rm -f stgit/builtin_version.py rm -f stgit/commands/*.pyc rm -rf stgit/commands/__pycache__ rm -f stgit/commands/cmdlist.py rm -f stgit/lib/*.pyc rm -rf stgit/lib/__pycache__ rm -f TAGS tags rm -f MANIFEST rm -f stgit-completion.bash tags: ctags -R stgit/* TAGS: ctags -e -R stgit/* .PHONY: all install doc install-doc install-html test test_patches \ coverage coverage-test coverage-report clean tags TAGS stgit-0.19/README000066400000000000000000000014031337022307200134520ustar00rootroot00000000000000StGit is a Python application providing similar functionality to Quilt (i.e. pushing/popping patches to/from a stack) on top of Git. These operations are performed using Git commands and the patches are stored as Git commit objects, allowing easy merging of the StGit patches into other repositories using standard Git functionality. Note that StGit is not an SCM interface on top of Git and it expects a previously initialised Git repository (unless it is cloned using StGit directly). For standard SCM operations, use plain Git commands. For the latest version see http://www.procode.org/stgit/ For a tutorial see http://www.procode.org/stgit/doc/tutorial.html Bugs or feature requests should be raised on the StGit project page: https://github.com/ctmarinas/stgit. stgit-0.19/RELEASENOTES000066400000000000000000000026001337022307200144060ustar00rootroot00000000000000 Stacked Git 0.19 released ------------------------- StGit is a Python application providing functionality similar to Quilt (i.e. pushing/popping patches to/from a stack) on top of Git. These operations are performed using Git commands, and the patches are stored as Git commit objects, allowing easy merging of the StGit patches into other repositories using standard Git functionality. Download: https://github.com/ctmarinas/stgit/archive/v0.19.tar.gz Main repository: https://repo.or.cz/stgit.git Project homepage: http://www.procode.org/stgit/ Issue tracker: https://github.com/ctmarinas/stgit/issues The main changes since release 0.18: - Python 3 support. StGit supports Python 2.6, 2.7, 3.3, 3.4, 3.5, 3.6, and 3.7. PyPy interpreters are also supported. - Submodules are now ignored when checking if working tree is clean. Submodules are also not included by default when refreshing a patch. - Config booleans are now parsed similarly to git-config. - contrib/stgit.el is now licenced with GPLv2. - Repair handling of emails with utf-8 bodies containing latin-1 characters. Also correctly decode email headers containing quoted encoded words. - StGit's version is now correct/available the release archive. - Add continuous integration (travis-ci) and code coverage (coveralls) support. - Many new test cases were added. stgit-0.19/TODO000066400000000000000000000016111337022307200132630ustar00rootroot00000000000000The TODO list before 1.0: - Convert the remaining commands to the new infrastructure. Commands not converted yet: branch patches pull rebase repair unhide files fold import mail pick rename show sync diff - More regression tests - Go through the design of the UI and make sure there's nothing hard to change in there that we'll regret later. - Write a user guide. I'm thinking a document on the order of 10-30 pages that'll explain why one would want to use StGit, and how. - Make sure the rest of the documentation is in good shape. - Release 1.0 The future, when time allows or if someone else does them: - Patch dependency tracking - Multiple heads in a patch - useful for forking a patch, synchronising with other patches (diff format or in other repositories) - Numeric shortcuts for naming patches near top (eg. +1, -2) stgit-0.19/contrib/000077500000000000000000000000001337022307200142345ustar00rootroot00000000000000stgit-0.19/contrib/.gitignore000066400000000000000000000000061337022307200162200ustar00rootroot00000000000000*.elc stgit-0.19/contrib/Makefile000066400000000000000000000005451337022307200157000ustar00rootroot00000000000000EMACS = emacs ELC = stgit.elc INSTALL ?= install INSTALL_ELC = $(INSTALL) -m 644 prefix ?= $(HOME) emacsdir = $(prefix)/share/emacs/site-lisp RM ?= rm -f all: $(ELC) install: all $(INSTALL) -d $(DESTDIR)$(emacsdir) $(INSTALL_ELC) $(ELC:.elc=.el) $(ELC) $(DESTDIR)$(emacsdir) %.elc: %.el $(EMACS) -batch -f batch-byte-compile $< clean:; $(RM) $(ELC) stgit-0.19/contrib/release/000077500000000000000000000000001337022307200156545ustar00rootroot00000000000000stgit-0.19/contrib/release/README000066400000000000000000000002051337022307200165310ustar00rootroot00000000000000This directory contains some of the scripts used for updating the public StGIT repository and releasing snapshots and main versions. stgit-0.19/contrib/release/post-update000077500000000000000000000011221337022307200200430ustar00rootroot00000000000000#!/bin/sh # # An example hook script to prepare a packed repository for use over # dumb transports. # # To enable this hook, make this file executable by "chmod +x post-update". git repack -d git update-server-info # FTP upload lftp ftp://your-ftp-site/stgit.git -u username,password -e " \ set ftp:list-empty-ok yes; \ echo Uploading objects; \ mirror -RLecv objects objects; \ echo Uploading refs; \ mirror -RLecv refs refs; \ echo Uploading info; \ mirror -RLecv info info; \ echo Uploading description; \ put description -o description; \ echo Uploading HEAD; \ put HEAD -o HEAD; \ exit" stgit-0.19/contrib/release/release.sh000077500000000000000000000014641337022307200176400ustar00rootroot00000000000000#!/bin/sh # # Makes a release set -e #UPLOAD=false UPLOAD=true VERSION=$(./stg --version | grep "Stacked GIT" | sed -e "s/Stacked GIT //") TARBALL=dist/stgit-$VERSION.tar.gz BINRPM=dist/stgit-$VERSION-1.noarch.rpm SRCRPM=dist/stgit-$VERSION-1.src.rpm DEBPKG=../stgit_$VERSION-0_all.deb git rev-list --pretty HEAD > ChangeLog rm -f MANIFEST # source distribution python setup.py sdist gpg --detach-sign $TARBALL # build the binary distributions python setup.py bdist_rpm dpkg-buildpackage -rfakeroot -b # Upload $UPLOAD && echo Uploading... $UPLOAD && lftp ftp://your-ftp-site/stgit -u username,password -e " \ set ftp:list-empty-ok yes; \ echo Uploading $TARBALL; \ put $TARBALL; \ echo Uploading $BINRPM; \ put $BINRPM; \ echo Uploading $SRCRPM; \ put $SRCRPM; \ echo Uploading $DEBPKG; \ put $DEBPKG; \ exit" stgit-0.19/contrib/release/snapshot.sh000077500000000000000000000007421337022307200200550ustar00rootroot00000000000000#!/bin/sh # # Builds a daily snapshot VERSION=`date "+%Y%m%d"` SNAPSHOT=dist/stgit-$VERSION.tar.gz git rev-list --pretty HEAD > ChangeLog mv stgit/version.py stgit/version.py- echo "version = '$VERSION'" > stgit/version.py rm -f MANIFEST python setup.py sdist rm stgit/version.py mv stgit/version.py- stgit/version.py # Upload lftp ftp://your-ftp-site/stgit/snapshots -u username,password -e " \ set ftp:list-empty-ok yes; \ echo Uploading $SNAPSHOT; \ put $SNAPSHOT; \ exit" stgit-0.19/contrib/stg-cvs000077500000000000000000000116411337022307200155530ustar00rootroot00000000000000#!/bin/bash set -e # stg-cvs - helper script to manage a mixed cvs/stgit working copy. # Allows quick synchronization of a cvs mirror branch (does not try to # reconstruct patchsets, creates "jumbo" commits), and commits stgit # patches to CVS. # Copyright (c) 2007 Yann Dirson # Subject to the GNU GPL, version 2. # NOTES # - you want to add a "CVS" line to .git/info/exclude # - you may want to add a ".git" line to the top .cvsignore # BRANCH INIT # - ensure the cvs wc is clean (eg. with "cvsco") # $ git init # $ echo CVS >> .git/info/exclude # $ git add . # $ git commit -m "Initial import." # $ git branch -m master cvs # $ stg branch -c master cvs # $ git config branch.master.stgit.parentbranch cvs (0.12.1 and earlier only) # $ git config branch.cvs.description "CVS $(cat CVS/Root) $(cat CVS/Repository) $(cat CVS/Tag 2>/dev/null | echo HEAD)" # $ git config branch.master.description "Changes for $(cat CVS/Repository) $(cat CVS/Tag 2>/dev/null | echo HEAD)" # LIMITATIONS # - this is only a proof-of-concept prototype # - lacks an "init" command (see above) # - "commit" does not ensure the base is uptodate before trying to # commit (but hey, it's CVS ;): better "stg-cvs pull" first # - "commit" can only commit a single patch # - not much robustness here # - still no support for files removed in cvs (should catch "no # longer in the repository" message) # - this only deals with CVS but could surely be extended to any other # VCS # - lacks synchronisation of .cvsignore <-> .gitignore # - no support for filenames with spaces (stg lacks --zero output format) # - git commit is too chatty when it finds nothing to commit # - lacks a "quick cvs commit" feature # DESIGN FLAWS # - while fetching, if a file change was not git update-index'd when # cvs-update'd (eg. because of a stg-cvs bug), it is not seen on further # fetches until it changes again, since we scan "cvs update" output. # This yields possible inconsistencies with CVS. # - similarly, any conflict while cvs-updating (whether due to illegal # changes to the cvs-mirror-branch, or due to files added to cvs but # already-existing in working copy, or to directory moves inside the # cvs repository, or ) has to be dealt with by hand (although # the situation is better here: cvs sees the conflict on subsequent tries) # - bad/no support for cvsutils: # - stg push/pop operations confuse cvsu because of timestamp changes # - cvspurge/cvsco would nuke .git => does not make it easy to ensure # synchronisation # - should use a separate workspace for cvs branch like tailor does # - confused by cvs keyword substitution usage() { [ "$#" = 0 ] || echo "ERROR: $*" echo "Usage: $(basename $0) " echo " commands: $(do_commands)" exit 1 } do_commands() { echo $(grep '^[a-z-]*)' $0 | cut -d')' -f1) } do_fetch() { local return=0 local path local parent="$1" local branch="$2" # record changes from cvs into index stg branch "$parent" || exit $? cvs -fq update -dP | grep -v '^\? ' | tee /dev/tty | while read status path; do if [ -e "$path" ]; then git update-index --add "$path" || exit $? else git update-index --remove "$path" || exit $? fi # cvs update: `FELIN1_PEP/src/java/com/sagem/felin/ui/widget/PEPRifStateIcon.java' is no longer in the repository done # create commit if git commit -m "stg-cvs sync"; then : else return=$? fi # back to branch stg branch "$branch" || exit $? return $return } cvs_add_dir() { local parent=$(dirname "$1") if [ ! -e "$parent/CVS" ]; then cvs_add_dir "$parent" fi cvs add "$1" } # get context branch=$(stg branch) parent=$(git config "branch.${branch}.stgit.parentbranch") || usage "no declared parent for '$branch' - set branch.${branch}.stgit.parentbranch" # extract command [ "$#" -ge 1 ] || usage command="$1" shift case "$command" in fetch) do_fetch "$parent" "$branch" ;; pull) if do_fetch "$parent" "$branch"; then # update # --merged stg rebase "$parent" stg clean --applied fi ;; commit) # sanity asserts [ $(stg applied | wc -l) = 1 ] || usage "you don't have exactly one patch applied" # context patch=$(stg top) # adds stg files | grep ^A | cut -c3- | while read file; do parent=$(dirname "$file") if [ ! -e "$parent/CVS" ]; then cvs_add_dir "$parent" fi cvs -f add "$file" done # removes stg files | grep ^D | cut -c3- | xargs -r cvs -f remove # commit stg files --bare | xargs -r cvs -fq commit \ -F ".git/patches/$branch/patches/$patch/description" # sync the parent branch stg branch "$parent" git cherry-pick "patches/${branch}/${patch}" stg branch "${branch}" # update # --merged stg rebase "$parent" stg clean --applied ;; _commands) # hint for bash-completion people :) do_commands ;; *) usage "unknown command '$command'" ;; esac stgit-0.19/contrib/stg-dispatch000077500000000000000000000020171337022307200165540ustar00rootroot00000000000000#!/bin/sh set -e # stg-dispatch - percollates files matching a pattern down to another patch. # It does the same job as stg-fold-files-from (and makes use of it to # do so), but from the patch containing the changes to migrate, # instead of doing so from the target patch. # usage: stg-dispatch [-n] [-#[-][,]...] # Copyright (c) 2007 Yann Dirson # Subject to the GNU GPL, version 2. die() { echo >&2 "$(basename $0) error: $*" exit 1 } noact=0 if [ "x$1" = "x-n" ]; then noact=1 shift fi TOPATCH="$1" shift stg series --applied --noprefix | grep "^$TOPATCH\$" >/dev/null || die "cannot dispatch to unapplied patch '$TOPATCH'" CURRENTPATCH=$(stg top) [ "x$TOPATCH" != "x$CURRENTPATCH" ] || die "dispatching to current patch ($CURRENTPATCH) makes no sense" if [ $noact = 1 ]; then stg-fold-files-from "$CURRENTPATCH" -n "$@" else stg goto "$TOPATCH" stg-fold-files-from "$CURRENTPATCH" "$@" stg refresh stg goto "$CURRENTPATCH" fi stgit-0.19/contrib/stg-fold-files-from000077500000000000000000000021431337022307200177420ustar00rootroot00000000000000#!/bin/bash set -e # stg-fold-files-from - picks changes to one file from another patch. # Only supports picking from one file pattern, but allows to select any range # of hunks from the file, using the -# flag to filterdiff. # Use together with "filterdiff --annotate" in your diff pager, to # identify hunk numbers easily. # Use "-O -U" to get finer hunk granularity for -#. # usage: stg-fold-files-from [-n] [-O ] [-#[-][,]...] # Copyright (c) 2006-2007 Yann Dirson # Subject to the GNU GPL, version 2. PATCH="$1" shift filtercmd=cat hunks= foldflags= showflags=() noact=0 while [ "$#" -gt 0 ]; do case "$1" in -\#*) hunks="$1" ;; -t) foldflags="-t" ;; -n) noact=1 ;; -O) showflags+=(-O "$2"); shift ;; -*) { echo >&2 "unknown flag '$1'"; exit 1; } ;; *) break ;; esac shift done [ "$#" = 1 ] || { echo >&2 "supports one file only"; exit 1; } getpatch() { stg show "${showflags[@]}" "$PATCH" | filterdiff -p1 $hunks -i "$1" } if [ $noact = 1 ]; then getpatch "$1" else getpatch "$1" | stg fold $foldflags fi stgit-0.19/contrib/stg-gitk000077500000000000000000000043711337022307200157200ustar00rootroot00000000000000#!/bin/sh set -e # stg-gitk - helper script to graphically display an StGIT stack # Displays given branches and stacks, without getting disturbed by # patch logs. # LIMITATIONS: # - no support for spaces in branch names # Copyright (c) 2007 Yann Dirson # Subject to the GNU GPL, version 2. helptext="Usage: $(basename $0) [--refs] [|--all] [-- ]" usage() { echo >&2 "$helptext" exit 1 } allbranches=0 refsonly=0 branches='' while [ "$#" -gt 0 ]; do case "$1" in --refs) refsonly=1 ;; --all) allbranches=1 ;; --help) echo "$helptext"; exit 0 ;; --) shift; break ;; --*) usage ;; *) branches="$branches $1" ;; esac shift done # Now any remaining stuff in $@ are additional options for gitk if [ $allbranches = 1 ] && [ "$branches" != "" ]; then usage fi GIT_DIR=$(git rev-parse --git-dir) GIT_DIR_SPKIPLEN=$(printf "$GIT_DIR/X" | wc -c) refdirs='' if [ $allbranches = 1 ]; then refdirs="$GIT_DIR/refs" else # default to current branch if [ "$branches" == "" ]; then branches="$(stg branch)" fi if [ "$branches" == "" ]; then echo >&2 "ERROR: cannot find current branch." exit 1 fi # expand patches for each named branch for b in $branches; do if [ -e "$GIT_DIR/refs/patches/$b" ]; then # StGIT branch: show all patches refdirs="$refdirs $GIT_DIR/refs/heads/$b $GIT_DIR/refs/patches/$b" elif [ -e "$GIT_DIR/refs/heads/$b" ]; then # other GIT branch refdirs="$refdirs $GIT_DIR/refs/heads/$b" elif [ $(git for-each-ref "refs/$b" | wc -l) != 0 ]; then # other ref refdirs="$refdirs $(git for-each-ref --format="$GIT_DIR/%(refname)" "refs/$b")" else echo >&2 "ERROR: no such ref '$b'" usage fi done fi printrefs() { find $refdirs -type f -not -name '*.log' | cut -c${GIT_DIR_SPKIPLEN}- } if [ $refsonly = 1 ]; then printrefs elif grep -q -- --argscmd $(which gitk); then # This gitk supports --argscmd. # Let's use a hack to pass --all, which was consumed during command-line parsing if [ $allbranches = 1 ]; then gitk --argscmd="$0 --refs --all" "$@" else gitk --argscmd="$0 --refs $branches" "$@" fi else # This gitk does not support --argscmd, just compute refs onces gitk $(printrefs) "$@" fi stgit-0.19/contrib/stg-k000077500000000000000000000017371337022307200152170ustar00rootroot00000000000000#!/bin/sh set -e # stg-k - execute given StGIT command while preserving local changes # Uses a temporary patch to save local changes, then execute the given # command, and restore local changes from the saved patch. In # essence, "stg-k pop" is a "stg pop -k" that works better, hence its # name. # CAVEATS: # - this script relies on the operation to run ignoring hidden # patches, so in 0.12 (where "stg push" can push an hidden patch) # "stg-k push" will fail midway, albeit with no information loss - # you'll just have to finish manually. This is fixed in 0.13 # - running this script to pop all patches in the stack fails, since # stg-unnew does not support this case. # Copyright (c) 2007 Yann Dirson # Subject to the GNU GPL, version 2. stg new __local -m " - local changes (internal patch)" stg refresh stg pop # avoid bad interactions like "stg-k push" not behaving as expected stg hide __local stg "$@" stg unhide __local stg push __local stg-unnew stgit-0.19/contrib/stg-mdiff000077500000000000000000000020311337022307200160360ustar00rootroot00000000000000#!/bin/bash set -e # stg-mdiff - display meta-diffs, ie. diffs of diffs # Main use: show evolutions of a patch. # eg. stg-mdiff foo@stable foo # stg-mdiff foo 012345567ABCD # sha1 for "foo" as integrated upstream # Copyright (c) 2007 Yann Dirson # Subject to the GNU GPL, version 2. usage() { echo "Usage: [-o ] [-O ] $(basename $0) ..[]| ..[]|" exit 1 } diffopts= subdiffopts= while [ "$#" -gt 0 ]; do case "$1" in -o) diffopts="$2"; shift ;; -O) subdiffopts="-O $2"; shift ;; -*) usage ;; *) break ;; esac shift done if [ "$#" != 2 ]; then usage fi if [ -z "$diffopts" ]; then diffopts="-u" fi case "$1" in *..*) cmd1="stg diff $subdiffopts -r" ;; *) cmd1="stg show $subdiffopts" ;; esac case "$2" in *..*) cmd2="stg diff $subdiffopts -r" ;; *) cmd2="stg show $subdiffopts" ;; esac colordiff $diffopts \ -I '^index [0-9a-b]*..[0-9a-b]*' \ -I '^@@ .* @@' \ <($cmd1 "$1") <($cmd2 "$2") | less -RFX stgit-0.19/contrib/stg-show000077500000000000000000000010521337022307200157330ustar00rootroot00000000000000#!/bin/bash set -e # stg-show - unlike "stg show", just "git show" with knowledge of stg refs # Ex: # stg-show --color-words -- files # Copyright (c) 2007 Yann Dirson # Subject to the GNU GPL, version 2. command=(git show) # subsitute git id's for stg ones until -- endofpatches=0 while [ "$#" -gt 0 ]; do case "$1" in --) endofpatches=1; break ;; -*) command+=("$1"); shift ;; *) command+=( $(stg id "$1" 2>/dev/null || echo "$1") ); shift ;; esac done # append remaining args command+=("$@") eval "${command[@]}" stgit-0.19/contrib/stg-show-old000077500000000000000000000005121337022307200165070ustar00rootroot00000000000000#!/bin/sh set -e # stg-show-old - mini helper to look at the previous version of a # patch (current one by default) # Copyright (c) 2006-2007 Yann Dirson # Subject to the GNU GPL, version 2. [ "$#" -le 1 ] || { echo >&2 "Usage: $(basename $0) []"; exit 1; } patch="$1" stg show "${patch}//top.old" stgit-0.19/contrib/stg-swallow000077500000000000000000000011541337022307200164460ustar00rootroot00000000000000#!/bin/sh set -e # stg-swallow - completely merge an unapplied patch into current one # Copyright (c) 2006-2007 Yann Dirson # Subject to the GNU GPL, version 2. # FIXME: # - should provide support for conflict solving ? [ "$#" = 1 ] || { echo >&2 "Usage: $(basename $0) "; exit 1; } patch="$1" stg pick --fold "$patch" stg refresh stg push "$patch" #stg clean "$patch" #stg pop; stg clean -u [ $(stg id "$patch//top") != $(stg id "$patch//bottom") ] || { echo >&2 "Assertion failed: patch '$patch' is not empty after swallowing, not deleting it."; exit 1; } stg delete "$patch" stgit-0.19/contrib/stg-unnew000077500000000000000000000006611337022307200161140ustar00rootroot00000000000000#!/bin/sh set -e # stg-unnew - sort of "reverse an 'stg new'" # Remove the current patch from the stack, keeping its contents as # uncommitted changes. # CAVEAT: running this script on the bottom-most patch fails, since # "stg pick --fold" does not allow this situation. # Copyright (c) 2007 Yann Dirson # Subject to the GNU GPL, version 2. patch=$(stg top) stg pop stg pick --fold $patch stg delete $patch stgit-0.19/contrib/stg-whatchanged000077500000000000000000000017441337022307200172400ustar00rootroot00000000000000#!/bin/bash set -e # stg-whatchanged - show a metadiff for the patch being modified, # especially when resolving a merge. # Copyright (c) 2006-2007 Yann Dirson # Subject to the GNU GPL, version 2. # FIXME: # - should only exclude hunk headers differing only in line offsets # - diff coloring should show changes in context lines differently than # changes in contents # - filter on ^index lines is a bit wide # - we should be able to ask diff to force a new hunk on "^@@ " to better # handle them # - we should always show the hunk header for any changes within a hunk # default to unified diff if [ "$#" = 0 ]; then set -- -u fi # Merges via "push" leave top=bottom so we must look at old patch # in this case (unlike, eg., "pick --fold") patchdir="$(git rev-parse --git-dir)/patches/$(stg branch)/patches/$(stg top)" case $(stg log | head -n1) in *push\(c\)*) former="//top.old" ;; *) former="//top" ;; esac stg-mdiff -o "$*" \ $former //bottom.. stgit-0.19/contrib/stgbashprompt.sh000077500000000000000000000007211337022307200174700ustar00rootroot00000000000000# modify PS1 to your preference and include this file in your bashrc # or copy to /etc/bash_completions.d. if [ "$PS1" ]; then function __prompt_git() { local git_dir ref br top; git_dir=$(git rev-parse --git-dir 2> /dev/null) || return ref=$(git symbolic-ref HEAD 2> /dev/null) || return br=${ref#refs/heads/} top=$(tail -n 1 $git_dir/patches/$br/applied 2>/dev/null) \ top=${top:-(none)} echo "[$top@$br]" } PS1='\u@\h:$(__prompt_git)\W\$ ' fi stgit-0.19/contrib/stgit.el000066400000000000000000003477341337022307200157320ustar00rootroot00000000000000;;; stgit.el --- major mode for StGit interaction ;; ;; Copyright (C) 2007-2013 David Kågedal ;; ;; Author: David Kågedal ;; Homepage: http://www.procode.org/stgit ;; Version: 0.17.1 ;; ;; This file 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 2, or (at your option) ;; any later version. ;; ;; This file 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 . ;;; Commentary: ;; ;; This is an interactive tool to interact with git branches using ;; StGit. ;; ;; StGit is a command-line tool providing similar functionality to ;; Quilt (i.e. pushing/popping patches to/from a stack) on top of Git. ;; These operations are performed using Git commands and the patches ;; are stored as Git commit objects, allowing easy merging of the ;; StGit patches into other repositories using standard Git ;; functionality. ;; ;; To start using the Emacs interface, run M-x stgit and select the ;; git repository you are working in. ;; ;; To get quick help about the available keybindings in the buffer, ;; press '?' ;;; Installation: ;; ;; To install: put this file on the load-path and place the following ;; in your .emacs file: ;; ;; (require 'stgit) ;; ;; To start: `M-x stgit' ;;; Code: (when (< emacs-major-version 22) (error "Emacs older than 22 is not supported by stgit.el")) (require 'git nil t) (require 'cl) (require 'comint) (require 'dired) (require 'ewoc) (require 'easymenu) (require 'format-spec) (defun stgit-set-default (symbol value) "Set default value of SYMBOL to VALUE using `set-default' and reload all StGit buffers." (set-default symbol value) (dolist (buf (buffer-list)) (with-current-buffer buf (when (derived-mode-p 'stgit-mode) (stgit-post-refresh buf :reload))))) (defgroup stgit nil "A user interface for the StGit patch maintenance tool." :group 'tools :link '(function-link stgit) :link '(url-link "http://www.procode.org/stgit/")) (defcustom stgit-default-show-worktree t "Set to non-nil to by default show the working tree in a new stgit buffer. Use \\\\[stgit-toggle-worktree] to toggle this \ setting in an already-started StGit buffer." :type 'boolean :group 'stgit :link '(variable-link stgit-show-worktree)) (defcustom stgit-default-show-unknown nil "Set to non-nil to by default show unknown files a new stgit buffer. Use \\\\[stgit-toggle-unknown] to toggle this \ setting in an already-started StGit buffer." :type 'boolean :group 'stgit :link '(variable-link stgit-show-unknown)) (defcustom stgit-default-show-ignored nil "Set to non-nil to by default show ignored files a new stgit buffer. Use \\\\[stgit-toggle-ignored] to toggle this \ setting in an already-started StGit buffer." :type 'boolean :group 'stgit :link '(variable-link stgit-show-ignored)) (defcustom stgit-default-show-patch-names t "If non-nil, default to showing patch names in a new stgit buffer. Use \\\\[stgit-toggle-patch-names] \ to toggle the this setting in an already-started StGit buffer." :type 'boolean :group 'stgit :link '(variable-link stgit-show-patch-names)) (defcustom stgit-default-show-committed nil "Set to nil to inhibit showing of historical git commits by default. Use \\\\[stgit-toggle-committed] \ to toggle this setting and to control how many commits are shown." :type 'boolean :group 'stgit :link '(variable-link stgit-default-committed-count) :link '(variable-link stgit-show-committed)) (defcustom stgit-default-committed-count 5 "The number of historical commits to show when `stgit-show-committed' is enabled." :type 'number :group 'stgit :link '(variable-link stgit-default-show-committed) :link '(variable-link stgit-committed-count)) (defcustom stgit-default-show-svn t "Set to non-nil to by default show subversion information in a new stgit buffer. Use \\\\[stgit-toggle-svn] to toggle this \ setting in an already-started StGit buffer." :type 'boolean :group 'stgit :link '(variable-link stgit-show-worktree)) (defcustom stgit-abbreviate-copies-and-renames t "If non-nil, abbreviate copies and renames as \"dir/{old -> new}/file\" instead of \"dir/old/file -> dir/new/file\"." :type 'boolean :group 'stgit :set 'stgit-set-default) (defcustom stgit-find-copies-harder nil "Try harder to find copied files when listing patches. When not nil, runs git diff-tree with the --find-copies-harder flag, which reduces performance." :type 'boolean :group 'stgit :set 'stgit-set-default) (defcustom stgit-show-worktree-mode 'center "This variable controls where the \"Index\" and \"Work tree\" will be shown on in the buffer. It can be set to 'top (above all patches), 'center (show between applied and unapplied patches), and 'bottom (below all patches)." :type '(radio (const :tag "above all patches (top)" top) (const :tag "between applied and unapplied patches (center)" center) (const :tag "below all patches (bottom)" bottom)) :group 'stgit :link '(variable-link stgit-show-worktree) :set 'stgit-set-default) (defcustom stgit-patch-line-format "%s%m%-30n %e%d" "The format string used to format patch lines. The format string is passed to `format-spec' and the following format characters are recognized: %s - A '+', '-', '>' or space, depending on whether the patch is applied, unapplied, top, or something else. %m - An asterisk if the patch is marked, and a space otherwise. %n - The patch name. %e - The string \"(empty) \" if the patch is empty. %d - The short patch description. %D - The short patch description, or the patch name. When `stgit-show-patch-names' is non-nil, the `stgit-noname-patch-line-format' variable is used instead." :type 'string :group 'stgit :set 'stgit-set-default) (defcustom stgit-noname-patch-line-format "%s%m%e%D" "The alternate format string used to format patch lines. It has the same semantics as `stgit-patch-line-format', and the display can be toggled between the two formats using \ \\\\[stgit-toggle-patch-names]. The alternate form is used when the patch name is hidden." :type 'string :group 'stgit :set 'stgit-set-default) (defcustom stgit-file-line-format " %-11s %-2m %n %c" "The format string used to format file lines. The format string is passed to `format-spec' and the following format characters are recognized: %s - A string describing the status of the file. %m - Mode change information %n - The file name. %c - A description of file changes." :type 'string :group 'stgit :set 'stgit-set-default) (defcustom stgit-git-program "git" "The program used by `stgit-mode' to run git." :type 'string :group 'stgit) (defcustom stgit-stg-program "stg" "The program used by `stgit-mode' to run StGit." :type 'string :group 'stgit) (defgroup stgit-faces nil "Faces for `stgit-mode'." :group 'stgit) (defface stgit-branch-name-face '((t :inherit bold)) "The face used for the StGit branch name" :group 'stgit-faces) (defface stgit-top-patch-face '((((background dark)) (:weight bold :foreground "yellow")) (((background light)) (:weight bold :foreground "purple")) (t (:weight bold))) "The face used for the top patch names" :group 'stgit-faces) (defface stgit-applied-patch-face '((((background dark)) (:foreground "light yellow")) (((background light)) (:foreground "purple")) (t ())) "The face used for applied patch names" :group 'stgit-faces) (defface stgit-unapplied-patch-face '((((background dark)) (:foreground "gray80")) (((background light)) (:foreground "orchid")) (t ())) "The face used for unapplied patch names" :group 'stgit-faces) (defface stgit-committed-patch-face '((((background dark)) (:foreground "gray50")) (((background light)) (:foreground "gray50")) (t ())) "The face used for already committed patch names" :group 'stgit-faces) (defface stgit-description-face '((((background dark)) (:foreground "tan")) (((background light)) (:foreground "dark red"))) "The face used for StGit descriptions" :group 'stgit-faces) (defface stgit-index-work-tree-title-face '((((supports :slant italic)) :slant italic) (t :inherit bold)) "StGit mode face used for the \"Index\" and \"Work tree\" titles" :group 'stgit-faces) (defface stgit-unmerged-file-face '((((class color) (background light)) (:foreground "red" :bold t)) (((class color) (background dark)) (:foreground "red" :bold t))) "StGit mode face used for unmerged file status" :group 'stgit-faces) (defface stgit-unknown-file-face '((((class color) (background light)) (:foreground "goldenrod" :bold t)) (((class color) (background dark)) (:foreground "goldenrod" :bold t))) "StGit mode face used for unknown file status" :group 'stgit-faces) (defface stgit-ignored-file-face '((((class color) (background light)) (:foreground "grey60")) (((class color) (background dark)) (:foreground "grey40"))) "StGit mode face used for ignored files") (defface stgit-file-permission-face '((((class color) (background light)) (:foreground "green" :bold t)) (((class color) (background dark)) (:foreground "green" :bold t))) "StGit mode face used for permission changes." :group 'stgit-faces) (defface stgit-modified-file-face '((((class color) (background light)) (:foreground "purple")) (((class color) (background dark)) (:foreground "salmon"))) "StGit mode face used for modified file status" :group 'stgit-faces) (defun stgit (dir) "Manage StGit patches for the tree in DIR. See `stgit-mode' for commands available." (interactive "DDirectory: \n") (switch-to-stgit-buffer (git-get-top-dir dir)) (stgit-reload)) (defun stgit-assert-mode () "Signal an error if not in an StGit buffer." (assert (derived-mode-p 'stgit-mode) nil "Not an StGit buffer")) (unless (fboundp 'git-get-top-dir) (defun git-get-top-dir (dir) "Retrieve the top-level directory of a git tree." (let ((cdup (with-output-to-string (with-current-buffer standard-output (cd dir) (unless (eq 0 (call-process stgit-git-program nil t nil "rev-parse" "--show-cdup")) (error "Cannot find top-level git tree for %s" dir)))))) (expand-file-name (concat (file-name-as-directory dir) (car (split-string cdup "\n"))))))) (defun stgit-refresh-git-status (&optional dir) "If it exists, refresh the `git-status' buffer belonging to directory DIR or `default-directory'" (when (and (fboundp 'git-find-status-buffer) (fboundp 'git-refresh-status)) (let* ((top-dir (git-get-top-dir (or dir default-directory))) (git-status-buffer (and top-dir (git-find-status-buffer top-dir)))) (when git-status-buffer (with-current-buffer git-status-buffer (git-refresh-status)))))) (defun stgit-find-buffer (dir) "Return the buffer displaying StGit patches for DIR, or nil if none." (setq dir (file-truename (file-name-as-directory dir))) (let ((buffers (buffer-list))) (while (and buffers (not (with-current-buffer (car buffers) (and (eq major-mode 'stgit-mode) (string= (file-truename default-directory) dir))))) (setq buffers (cdr buffers))) (and buffers (car buffers)))) (defun switch-to-stgit-buffer (dir) "Switch to a (possibly new) buffer displaying StGit patches for DIR." (setq dir (file-name-as-directory dir)) (let ((buffer (stgit-find-buffer dir))) (switch-to-buffer (or buffer (create-stgit-buffer dir))))) (defstruct (stgit-patch (:conc-name stgit-patch->)) status name desc empty files-ewoc) (defun stgit-patch-display-name (patch) (let ((name (stgit-patch->name patch))) (case name (:index "Index") (:work "Work Tree") (t (symbol-name name))))) (defun stgit-insert-without-trailing-whitespace (text) "Insert TEXT in buffer using `insert', without trailing whitespace. A newline is appended." (unless (string-match "\\(.*?\\) *$" text) (error)) (insert (match-string 1 text) ?\n)) (defun stgit-line-format () "Return the current line format; one of `stgit-patch-line-format' and `stgit-noname-patch-line-format'" (if stgit-show-patch-names stgit-patch-line-format stgit-noname-patch-line-format)) (defun stgit-patch-pp (patch) (let* ((status (stgit-patch->status patch)) (start (point)) (name (stgit-patch->name patch)) (face (cdr (assq status stgit-patch-status-face-alist))) (fmt (stgit-line-format)) (spec (format-spec-make ?s (case status ('applied "+") ('top ">") ('unapplied "-") (t " ")) ?m (if (memq name stgit-marked-patches) "*" " ") ?n (propertize (stgit-patch-display-name patch) 'face face 'syntax-table (string-to-syntax "w")) ?e (if (stgit-patch->empty patch) "(empty) " "") ?d (propertize (or (stgit-patch->desc patch) "") 'face 'stgit-description-face) ?D (propertize (let ((desc (stgit-patch->desc patch))) (if (zerop (length desc)) (stgit-patch-display-name patch) desc)) 'face face))) (text (format-spec fmt spec))) (stgit-insert-without-trailing-whitespace text) (put-text-property start (point) 'entry-type 'patch) (when (memq name stgit-expanded-patches) (stgit-insert-patch-files patch)) (put-text-property start (point) 'patch-data patch))) (defun create-stgit-buffer (dir) "Create a buffer for showing StGit patches. Argument DIR is the repository path." (let ((buf (create-file-buffer (concat dir "*stgit*"))) (inhibit-read-only t)) (with-current-buffer buf (setq default-directory dir) (stgit-mode) (set (make-local-variable 'stgit-ewoc) (ewoc-create #'stgit-patch-pp "Branch:\n\n" "--\n" t)) (setq buffer-read-only t)) buf)) (def-edebug-spec stgit-capture-output (form body)) (defmacro stgit-capture-output (name &rest body) "Capture StGit output and, if there was any output, show it in a window at the end. Returns the result of the last form in BODY." (declare (debug ([&or stringp null] body)) (indent 1)) `(let ((output-buf (get-buffer-create ,(or name "*StGit output*"))) (stgit-dir default-directory) (inhibit-read-only t)) (set-buffer-major-mode output-buf) (with-current-buffer output-buf (buffer-disable-undo) (erase-buffer) (setq default-directory stgit-dir) (setq buffer-read-only t)) (prog1 (let ((standard-output output-buf)) ,@body) (with-current-buffer output-buf (set-buffer-modified-p nil) (setq buffer-read-only t) (if (< (point-min) (point-max)) (display-buffer output-buf t)))))) (defun stgit-make-run-args (args) "Return a copy of ARGS with its elements converted to strings." (mapcar (lambda (x) ;; don't use (format "%s" ...) to limit type errors (cond ((stringp x) x) ((integerp x) (number-to-string x)) ((symbolp x) (symbol-name x)) (t (error "Bad element in stgit-make-run-args args: %S" x)))) args)) (defvar stgit-inhibit-messages nil "Set to non-nil to inhibit messages when running `stg' commands. See also `stgit-message'.") (defun stgit-message (format-spec &rest args) "Call `message' on the arguments unless `stgit-inhibit-messages' is non-nil." (unless stgit-inhibit-messages (apply 'message format-spec args))) (defmacro stgit-show-task-message (message &rest body) "Display \"MESSAGE...\" before executing BODY and then display \"MESSAGE...done\" when done. MESSAGE will only be evaluated if necessary and no message will be shown if MESSAGE is nil. If `stgit-inhibit-messages' is non-nil, messages are suppressed. See also `stgit-message'. If MESSAGE is non-nil, BODY will be executed with `stgit-inhibit-messages' set to `t'. Returns the return value of BODY." (declare (indent 1) (debug (form body))) (let ((msg (make-symbol "msg"))) `(let ((,msg (and (not stgit-inhibit-messages) ,message))) (when ,msg (message "%s..." ,msg)) (prog1 (let ((stgit-inhibit-messages (or ,msg stgit-inhibit-messages))) ,@body) (when ,msg (message "%s...done" ,msg)))))) (defun stgit-run (&rest args) (setq args (stgit-make-run-args args)) (stgit-show-task-message (mapconcat #'identity `("Running" ,stgit-stg-program ,@args) " ") (apply 'call-process stgit-stg-program nil standard-output nil args))) (defun stgit-run-silent (&rest args) (let ((stgit-inhibit-messages t)) (apply 'stgit-run args))) (defun stgit-run-git (&rest args) (setq args (stgit-make-run-args args)) (stgit-show-task-message (mapconcat #'identity `("Running" ,stgit-git-program ,@args) " ") (apply 'call-process stgit-git-program nil standard-output nil args))) (defun stgit-run-git-silent (&rest args) (let ((stgit-inhibit-messages t)) (apply 'stgit-run-git args))) (defun stgit-index-empty-p () "Returns non-nil if the index contains no changes from HEAD." (zerop (stgit-run-git-silent "diff-index" "--cached" "--quiet" "HEAD"))) (defun stgit-work-tree-empty-p () "Returns non-nil if the work tree contains no changes from index." (zerop (stgit-run-git-silent "diff-files" "--quiet"))) (defvar stgit-did-advise nil "Set to non-nil if appropriate (non-stgit) git functions have been advised to update the stgit status when necessary.") (defconst stgit-allowed-branch-name-re ;; Disallow control characters, space, del, and "/:@^{}~" in ;; "/"-separated parts; parts may not start with a period (.) "^[^\0- ./:@^{}~\177][^\0- /:@^{}~\177]*\ \\(/[^\0- ./:@^{}~\177][^\0- /:@^{}~\177]*\\)*$" "Regular expression that (new) branch names must match.") (defun stgit-refresh-index () (when stgit-index-node (ewoc-invalidate (car stgit-index-node) (cdr stgit-index-node)))) (defun stgit-refresh-worktree () (when stgit-worktree-node (ewoc-invalidate (car stgit-worktree-node) (cdr stgit-worktree-node)))) (defun stgit-run-series-insert-index (ewoc) (setq index-node (cons ewoc (ewoc-enter-last ewoc (make-stgit-patch :status 'index :name :index :desc nil :empty nil))) worktree-node (cons ewoc (ewoc-enter-last ewoc (make-stgit-patch :status 'work :name :work :desc nil :empty nil))))) (defun stgit-get-position (&optional position) "Return `stgit-mode' position information at POSITION (point by default) that can be used to restore the point using `stgit-restore-position'." (let ((opoint (point))) (and position (goto-char position)) (prog1 (list (stgit-patch-name-at-point) (let ((f (stgit-patched-file-at-point))) (and f (stgit-file->file f))) (line-number-at-pos) (current-column)) (goto-char opoint)))) (defun stgit-restore-position (state) "Move point to the position in STATE, as returned by `stgit-get-position'." (destructuring-bind (patch file line column) state (unless (and patch (case (stgit-goto-patch patch file) ((t) (move-to-column column) t) ((:patch) t))) (goto-char (point-min)) (forward-line (1- line)) (move-to-column (if patch (stgit-goal-column) column))))) (defun stgit-get-window-state () "Return the state of the buffer and its windows. Use `stgit-restore-window-state' to restore the state." (list (current-buffer) (mapcar (lambda (window) (cons window (stgit-get-position (window-point window)))) (get-buffer-window-list (current-buffer) t t)) (stgit-get-position (point)) (let ((mark (mark))) (and mark (stgit-get-position mark))) mark-active transient-mark-mode)) (defun stgit-restore-window-state (state) "Restore the state of the stgit buffer and windows in STATE, as obtained from `stgit-get-window-state'." (destructuring-bind (buffer window-states buffer-state mark-state old-mark-active old-transient-mark-mode) state (with-current-buffer buffer (mapc (lambda (x) (let ((window (car x)) (state (cdr x))) (when (and (window-live-p window) (eq (window-buffer window) buffer)) (stgit-restore-position state) (set-window-point window (point))))) window-states) (let ((mark-point (when mark-state (stgit-restore-position mark-state) (point)))) (stgit-restore-position buffer-state) (if (and mark-point (null old-mark-active)) (set-marker (mark-marker) mark-point) (set-mark mark-point)) (setq mark-active old-mark-active transient-mark-mode old-transient-mark-mode))))) (defmacro stgit-save-excursion (&rest body) "Execute BODY and, for each window displaying the current buffer, move point and mark back to the file, patch, or line where they were." (declare (indent 0) (debug (body))) (let ((state (make-symbol "state"))) `(let ((,state (stgit-get-window-state)) deactivate-mark) ,@body (stgit-restore-window-state ,state)))) (defun stgit-svn-find-rev (sha1 hash) "Return the subversion revision corresponding to SHA1 as reported by git svn. Cached data is stored in HASH, which must have been created using (make-hash-table :test 'equal)." (let ((result (gethash sha1 hash t))) (when (eq result t) (let ((svn-rev (with-output-to-string (stgit-run-git-silent "svn" "find-rev" "--" sha1)))) (setq result (when (string-match "\\`[0-9]+" svn-rev) (string-to-number (match-string 0 svn-rev)))) (puthash sha1 result hash))) result)) (defun stgit-run-series (ewoc) (setq stgit-index-node nil stgit-worktree-node nil) (let (all-patchsyms base) (when (and stgit-show-committed (> stgit-committed-count 0) (setq base (condition-case nil (stgit-id "{base}") (error nil)))) (let* ((show-svn stgit-show-svn) (svn-hash stgit-svn-find-rev-hash) (nentries (format "-%s" stgit-committed-count))) (with-temp-buffer (let* ((standard-output (current-buffer)) (fmt (stgit-line-format)) (commit-abbrev (when (string-match "%-\\([0-9]+\\)n" fmt) (string-to-number (match-string 1 fmt)))) (exit-status (stgit-run-git-silent "--no-pager" "log" "--reverse" "--pretty=oneline" nentries base))) (goto-char (point-min)) (if (not (zerop exit-status)) (message "Failed to run git log") (while (not (eobp)) (unless (looking-at "\\([0-9a-f]+\\)\\(\\.\\.\\.\\)? \\(.*\\)") (error "Syntax error in output from git log")) (let* ((state 'committed) (name (match-string 1)) (desc (match-string 3)) (empty nil)) (when show-svn (let ((svn-rev (stgit-svn-find-rev name svn-hash))) (when svn-rev (setq desc (format "(r%s) %s" svn-rev desc))))) (and commit-abbrev (< commit-abbrev (length name)) (setq name (substring name 0 commit-abbrev))) (setq name (intern name)) (setq all-patchsyms (cons name all-patchsyms)) (ewoc-enter-last ewoc (make-stgit-patch :status state :name name :desc desc :empty empty))) (forward-line 1))))))) (let ((inserted-index (not stgit-show-worktree)) index-node worktree-node) (with-temp-buffer (let* ((standard-output (current-buffer)) (exit-status (stgit-run-silent "series" "--description" "--empty"))) (goto-char (point-min)) (if (not (zerop exit-status)) (cond ((looking-at "stg series: \\(.*\\)") (setq inserted-index t) (ewoc-set-hf ewoc (car (ewoc-get-hf ewoc)) (substitute-command-keys "-- not initialized; run \\[stgit-init]"))) ((looking-at ".*") (error "Error running stg: %s" (match-string 0)))) (while (not (eobp)) (unless (looking-at "\\([0 ]\\)\\([>+-]\\)\\( \\)\\([^ ]+\\) *[|#] \\(.*\\)") (error "Syntax error in output from stg series")) (let* ((state-str (match-string 2)) (state (cond ((string= state-str ">") 'top) ((string= state-str "+") 'applied) ((string= state-str "-") 'unapplied))) (name (intern (match-string 4))) (desc (match-string 5)) (empty (string= (match-string 1) "0"))) (unless inserted-index (when (or (eq stgit-show-worktree-mode 'top) (and (eq stgit-show-worktree-mode 'center) (eq state 'unapplied))) (setq inserted-index t) (stgit-run-series-insert-index ewoc))) (setq all-patchsyms (cons name all-patchsyms)) (ewoc-enter-last ewoc (make-stgit-patch :status state :name name :desc desc :empty empty))) (forward-line 1))))) (unless inserted-index (stgit-run-series-insert-index ewoc)) (setq stgit-index-node index-node stgit-worktree-node worktree-node stgit-marked-patches (intersection stgit-marked-patches all-patchsyms))))) (defun stgit-current-branch () "Return the name of the current branch." (substring (with-output-to-string (stgit-run-silent "branch")) 0 -1)) (defun stgit-reload (&optional description) "Update the contents of the StGit buffer. If DESCRIPTION is non-nil, it is displayed as a status message during the operation." (interactive) (stgit-assert-mode) (stgit-show-task-message description (let ((inhibit-read-only t)) (stgit-save-excursion (ewoc-filter stgit-ewoc #'(lambda (x) nil)) (ewoc-set-hf stgit-ewoc (concat "Branch: " (propertize (stgit-current-branch) 'face 'stgit-branch-name-face) "\n\n") (if stgit-show-worktree "--" (propertize (substitute-command-keys "--\n\"\ \\[stgit-toggle-worktree]\" shows the working tree\n") 'face 'stgit-description-face))) (stgit-run-series stgit-ewoc)) (stgit-refresh-git-status)))) (defconst stgit-file-status-code-strings (mapcar (lambda (arg) (cons (car arg) (propertize (cadr arg) 'face (car (cddr arg))))) '((add "Added" stgit-modified-file-face) (copy "Copied" stgit-modified-file-face) (delete "Deleted" stgit-modified-file-face) (modify "Modified" stgit-modified-file-face) (rename "Renamed" stgit-modified-file-face) (mode-change "Mode change" stgit-modified-file-face) (unmerged "Unmerged" stgit-unmerged-file-face) (unknown "Unknown" stgit-unknown-file-face) (ignore "Ignored" stgit-ignored-file-face))) "Alist of code symbols to description strings") (defconst stgit-patch-status-face-alist '((applied . stgit-applied-patch-face) (top . stgit-top-patch-face) (unapplied . stgit-unapplied-patch-face) (committed . stgit-committed-patch-face) (index . stgit-index-work-tree-title-face) (work . stgit-index-work-tree-title-face)) "Alist of face to use for a given patch status") (defun stgit-file-status-code-as-string (file) "Return stgit status code for FILE as a string" (let* ((code (assq (stgit-file->status file) stgit-file-status-code-strings)) (score (stgit-file->cr-score file))) (when code (if (and score (/= score 100)) (format "%s %s" (cdr code) (propertize (format "%d%%" score) 'face 'stgit-description-face)) (cdr code))))) (defun stgit-file-status-code (str &optional score) "Return stgit status code from git status string" (let ((code (assoc str '(("A" . add) ("C" . copy) ("D" . delete) ("I" . ignore) ("M" . modify) ("R" . rename) ("T" . mode-change) ("U" . unmerged) ("X" . unknown))))) (setq code (if code (cdr code) 'unknown)) (when (stringp score) (if (> (length score) 0) (setq score (string-to-number score)) (setq score nil))) (if score (cons code score) code))) (defconst stgit-file-type-strings '((#o100 . "file") (#o120 . "symlink") (#o160 . "subproject")) "Alist of names of file types") (defun stgit-file-type-string (type) "Return string describing file type TYPE (the high bits of file permission). Cf. `stgit-file-type-strings' and `stgit-file-type-change-string'." (let ((type-str (assoc type stgit-file-type-strings))) (or (and type-str (cdr type-str)) (format "unknown type %o" type)))) (defun stgit-file-type-change-string (old-perm new-perm) "Return string describing file type change from OLD-PERM to NEW-PERM. Cf. `stgit-file-type-string'." (let ((old-type (lsh old-perm -9)) (new-type (lsh new-perm -9))) (cond ((= old-type new-type) "") ((zerop new-type) "") ((zerop old-type) (if (= new-type #o100) "" (format "(%s)" (stgit-file-type-string new-type)))) (t (format "(%s -> %s)" (stgit-file-type-string old-type) (stgit-file-type-string new-type)))))) (defun stgit-file-mode-change-string (old-perm new-perm) "Return string describing file mode change from OLD-PERM to NEW-PERM. Cf. `stgit-file-type-change-string'." (setq old-perm (logand old-perm #o777) new-perm (logand new-perm #o777)) (if (or (= old-perm new-perm) (zerop old-perm) (zerop new-perm)) "" (let* ((modified (logxor old-perm new-perm)) (not-x-modified (logand (logxor old-perm new-perm) #o666))) (cond ((zerop modified) "") ((and (zerop not-x-modified) (or (and (eq #o111 (logand old-perm #o111)) (propertize "-x" 'face 'stgit-file-permission-face)) (and (eq #o111 (logand new-perm #o111)) (propertize "+x" 'face 'stgit-file-permission-face))))) (t (concat (propertize (format "%o" old-perm) 'face 'stgit-file-permission-face) (propertize " -> " 'face 'stgit-description-face) (propertize (format "%o" new-perm) 'face 'stgit-file-permission-face))))))) (defstruct (stgit-file (:conc-name stgit-file->)) old-perm new-perm copy-or-rename cr-score cr-from cr-to status file) (defun stgit-escape-file-name-p (name) "Return non-nil if NAME must be escaped." (save-match-data (string-match "[\t\n\"\\]" name))) (defun stgit-escape-file-name (name &optional no-quotes) "Escape NAME if necessary. If NO-QUOTES is non-nil, do not enclose the result in double quotes." (if (stgit-escape-file-name-p name) (concat (if no-quotes "" "\"") (mapconcat (lambda (c) (case c (?\t "\\t") (?\n "\\n") (?\" "\\\"") (?\\ "\\\\") (t (char-to-string c)))) name "") (if no-quotes "" "\"")) name)) (defun stgit-describe-copy-or-rename (file) (let* ((arrow (concat " " (propertize "->" 'face 'stgit-description-face) " ")) (esc-from (stgit-file->cr-from file)) (esc-to (stgit-file->cr-to file)) (quote "") from to common-head common-tail) (when (or (stgit-escape-file-name-p esc-from) (stgit-escape-file-name-p esc-to)) (setq esc-from (stgit-escape-file-name esc-from t) esc-to (stgit-escape-file-name esc-to t) quote "\"")) (when stgit-abbreviate-copies-and-renames (setq from (split-string esc-from "/") to (split-string esc-to "/")) (while (and from to (cdr from) (cdr to) (string-equal (car from) (car to))) (setq common-head (cons (car from) common-head) from (cdr from) to (cdr to))) (setq common-head (nreverse common-head) from (nreverse from) to (nreverse to)) (while (and from to (cdr from) (cdr to) (string-equal (car from) (car to))) (setq common-tail (cons (car from) common-tail) from (cdr from) to (cdr to))) (setq from (nreverse from) to (nreverse to))) (if (or common-head common-tail) (concat quote (if common-head (mapconcat #'identity common-head "/") "") (if common-head "/" "") (propertize "{" 'face 'stgit-description-face) (mapconcat #'identity from "/") arrow (mapconcat #'identity to "/") (propertize "}" 'face 'stgit-description-face) (if common-tail "/" "") (if common-tail (mapconcat #'identity common-tail "/") "") quote) (concat quote esc-from arrow esc-to quote)))) (defun stgit-file-pp (file) (let ((start (point)) (spec (format-spec-make ?s (stgit-file-status-code-as-string file) ?m (stgit-file-mode-change-string (stgit-file->old-perm file) (stgit-file->new-perm file)) ?n (if (stgit-file->copy-or-rename file) (stgit-describe-copy-or-rename file) (stgit-escape-file-name (stgit-file->file file))) ?c (propertize (stgit-file-type-change-string (stgit-file->old-perm file) (stgit-file->new-perm file)) 'face 'stgit-description-face)))) (stgit-insert-without-trailing-whitespace (format-spec stgit-file-line-format spec)) (add-text-properties start (point) (list 'entry-type 'file 'file-data file)))) (defun stgit-find-copies-harder-diff-arg () "Return the flag to use with `git-diff' depending on the `stgit-find-copies-harder' flag." (if stgit-find-copies-harder "--find-copies-harder" "-C")) (defun stgit-insert-ls-files (args file-flag) (let ((start (point))) (apply 'stgit-run-git (append '("ls-files" "--exclude-standard" "-z") args)) (goto-char start) (while (looking-at "\\([^\0]*\\)\0") (let ((name-len (- (match-end 0) (match-beginning 0)))) (insert ":0 0 0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 " file-flag "\0") (forward-char name-len))))) (defun stgit-process-files (callback) (goto-char (point-min)) (when (looking-at "[0-9A-Fa-f]\\{40\\}\0") (goto-char (match-end 0))) (while (looking-at ":\\([0-7]+\\) \\([0-7]+\\) [0-9A-Fa-f]\\{40\\} [0-9A-Fa-f]\\{40\\} ") (let ((old-perm (string-to-number (match-string 1) 8)) (new-perm (string-to-number (match-string 2) 8))) (goto-char (match-end 0)) (let ((file (cond ((looking-at "\\([CR]\\)\\([0-9]*\\)\0\\([^\0]*\\)\0\\([^\0]*\\)\0") (let* ((patch-status (stgit-patch->status patch)) (file-subexp (if (eq patch-status 'unapplied) 3 4)) (file (match-string file-subexp))) (make-stgit-file :old-perm old-perm :new-perm new-perm :copy-or-rename t :cr-score (string-to-number (match-string 2)) :cr-from (match-string 3) :cr-to (match-string 4) :status (stgit-file-status-code (match-string 1)) :file file))) ((looking-at "\\([ABD-QS-Z]\\)\0\\([^\0]*\\)\0") (make-stgit-file :old-perm old-perm :new-perm new-perm :copy-or-rename nil :cr-score nil :cr-from nil :cr-to nil :status (stgit-file-status-code (match-string 1)) :file (match-string 2)))))) (goto-char (match-end 0)) (funcall callback file))))) (defun stgit-insert-patch-files (patch) "Expand (show modification of) the patch PATCH after the line at point." (let* ((patchsym (stgit-patch->name patch)) (end (point-marker)) (args (list "-z" (stgit-find-copies-harder-diff-arg))) (ewoc (ewoc-create #'stgit-file-pp nil nil t)) (show-ignored stgit-show-ignored) (show-unknown stgit-show-unknown)) (set-marker-insertion-type end t) (setf (stgit-patch->files-ewoc patch) ewoc) (with-temp-buffer (let ((standard-output (current-buffer))) (apply 'stgit-run-git (cond ((eq patchsym :work) (let (standard-output) (stgit-run-git "update-index" "--refresh")) `("diff-files" "-0" ,@args)) ((eq patchsym :index) `("diff-index" ,@args "--cached" "HEAD")) (t `("diff-tree" ,@args "-r" ,(stgit-id patchsym))))) (when (and (eq patchsym :work)) (when show-ignored (stgit-insert-ls-files '("--ignored" "--others") "I")) (when show-unknown (stgit-insert-ls-files '("--directory" "--no-empty-directory" "--others") "X")) (sort-regexp-fields nil ":[^\0]*\0\\([^\0]*\\)\0" "\\1" (point-min) (point-max))) (stgit-process-files (lambda (file) (ewoc-enter-last ewoc file))) (unless (ewoc-nth ewoc 0) (ewoc-set-hf ewoc "" (concat " " (propertize "" 'face 'stgit-description-face) "\n"))))) (goto-char end))) (defun stgit-find-file-revision (file patchsym &optional other-window) (let ((filename (expand-file-name (concat (file-name-nondirectory file) ".~" (symbol-name patchsym) "~") (file-name-directory file)))) (let ((coding-system-for-read 'no-conversion) (coding-system-for-write 'no-conversion)) (with-temp-file filename (unless (zerop (stgit-run-git-silent "cat-file" "blob" (concat (if (eq patchsym :index) "" (stgit-id patchsym)) ":" file))) (error "git cat-file failed")))) (funcall (if other-window 'switch-to-buffer-other-window 'switch-to-buffer) (find-file-noselect filename)) (set (make-local-variable 'vc-parent-buffer) filename))) (defun stgit-find-file (&optional other-window this-rev) (let* ((file (or (stgit-patched-file-at-point) (error "No file at point"))) (filename (expand-file-name (stgit-file->file file))) (patchsym (stgit-patch-name-at-point))) (if (and this-rev (not (eq patchsym :work))) (stgit-find-file-revision (stgit-file->file file) (stgit-patch-name-at-point) other-window) (unless (file-exists-p filename) (error "File does not exist")) (funcall (if other-window 'find-file-other-window 'find-file) filename) (when (eq (stgit-file->status file) 'unmerged) (smerge-mode 1))))) (defun stgit-expand (&optional patches collapse) "Show the contents of marked patches, or the patch at point. See also `stgit-collapse'. Non-interactively, operate on PATCHES, and collapse instead of expand if COLLAPSE is not nil." (interactive (list (stgit-patches-marked-or-at-point t))) (stgit-assert-mode) (let ((patches-diff (funcall (if collapse #'intersection #'set-difference) patches stgit-expanded-patches))) (setq stgit-expanded-patches (if collapse (set-difference stgit-expanded-patches patches-diff) (append stgit-expanded-patches patches-diff))) (stgit-show-task-message (concat (if collapse "Collapsing" "Expanding") " " (if (= 1 (length patches-diff)) "patch" "patches")) (ewoc-map #'(lambda (patch) (memq (stgit-patch->name patch) patches-diff)) stgit-ewoc))) (move-to-column (stgit-goal-column))) (defun stgit-collapse (&optional patches) "Hide the contents of marked patches, or the patch at point. See also `stgit-expand'." (interactive (list (stgit-patches-marked-or-at-point t))) (stgit-assert-mode) (stgit-expand patches t)) (defun stgit-select-patch () (let ((patchname (stgit-patch-name-at-point))) (stgit-expand (list patchname) (memq patchname stgit-expanded-patches)))) (defun stgit-expand-directory (file) (let* ((patch (stgit-patch-at-point)) (ewoc (stgit-patch->files-ewoc patch)) (node (ewoc-locate ewoc)) (filename (stgit-file->file file)) (start (make-marker)) (end (make-marker))) (save-excursion (forward-line 1) (set-marker start (point)) (set-marker end (point)) (set-marker-insertion-type end t)) (assert (string-match "/$" filename)) ;; remove trailing "/" (setf (stgit-file->file file) (substring filename 0 -1)) (ewoc-invalidate ewoc node) (with-temp-buffer (let ((standard-output (current-buffer))) (stgit-insert-ls-files (list "--directory" "--others" "--no-empty-directory" "--" filename) "X") (stgit-process-files (lambda (f) (setq node (ewoc-enter-after ewoc node f)))))) (move-to-column (stgit-goal-column)) (let ((inhibit-read-only t)) (put-text-property start end 'patch-data patch)))) (defun stgit-select-file () (let* ((file (or (stgit-patched-file-at-point) (error "No file at point"))) (filename (stgit-file->file file))) (if (string-match "/$" filename) (stgit-expand-directory file) (stgit-find-file)))) (defun stgit-select () "With point on a patch, toggle showing files in the patch. With point on a file, open the associated file. Opens the target file for (applied) copies and renames." (interactive) (stgit-assert-mode) (case (get-text-property (point) 'entry-type) ('patch (stgit-select-patch)) ('file (stgit-select-file)) (t (error "No patch or file on line")))) (defun stgit-find-file-other-window (&optional this-rev) "Open file at point in other window. With prefix argument, open a buffer with that revision of the file." (interactive "p") (stgit-assert-mode) (stgit-find-file t (> this-rev 1))) (defun stgit-find-file-merge () "Open file at point and merge it using `smerge-ediff'." (interactive) (stgit-assert-mode) (stgit-find-file t) (let ((filename (file-name-nondirectory buffer-file-name))) (smerge-ediff (concat "*" filename " GIT*") (concat "*" filename " PATCH*")))) (defun stgit-quit () "Hide the stgit buffer." (interactive) (stgit-assert-mode) (bury-buffer)) (defun stgit-git-status () "Show status using `git-status'." (interactive) (stgit-assert-mode) (unless (fboundp 'git-status) (error "The stgit-git-status command requires git-status")) (let ((dir default-directory)) (save-selected-window (pop-to-buffer nil) (git-status dir)))) (defun stgit-goal-column () "Return goal column for the current line" (case (get-text-property (point) 'entry-type) ('patch 2) ('file 4) (t 0))) (defun stgit-next-line (&optional arg) "Move cursor vertically down ARG lines" (interactive "p") (stgit-assert-mode) (next-line arg) (move-to-column (stgit-goal-column))) (defun stgit-previous-line (&optional arg) "Move cursor vertically up ARG lines" (interactive "p") (stgit-assert-mode) (previous-line arg) (move-to-column (stgit-goal-column))) (defun stgit-next-patch (&optional arg) "Move cursor down ARG patches." (interactive "p") (stgit-assert-mode) (unless arg (setq arg 1)) (cond ((< arg 0) (stgit-previous-patch (- arg))) ((zerop arg) (move-to-column (stgit-goal-column))) (t (when (stgit-at-header-p) (ewoc-goto-node stgit-ewoc (ewoc-nth stgit-ewoc 0)) (setq arg (1- arg))) (ewoc-goto-next stgit-ewoc arg) (move-to-column goal-column)))) (defun stgit-previous-patch (&optional arg) "Move cursor up ARG patches." (interactive "p") (stgit-assert-mode) (unless arg (setq arg 1)) (cond ((< arg 0) (stgit-next-patch (- arg))) ((zerop arg) (move-to-column (stgit-goal-column))) ((stgit-at-header-p) (goto-char (point-min))) (t (let ((opatch (stgit-patch-at-point))) (when (stgit-patched-file-at-point) (setq arg (1- arg))) (ewoc-goto-prev stgit-ewoc arg) (unless (zerop arg) (when (eq opatch (stgit-patch-at-point)) (goto-char (point-min))))) (move-to-column (stgit-goal-column))))) (defun stgit-previous-patch-group (&optional arg) "Move to the previous group of patches. If ARG is non-nil, do this ARG times. If ARG is negative, move -ARG groups forward instead; cf. `stgit-next-patch-group'." (interactive "p") (stgit-assert-mode) (if (< arg 0) (stgit-previous-patch-group (- arg)) (while (and (not (bobp)) (> arg 0)) (stgit-previous-patch 1) (let* ((opoint (point)) (patch (stgit-patch-at-point)) (status (and patch (stgit-patch->status patch)))) (while (and (not (bobp)) (let* ((npatch (stgit-patch-at-point)) (nstatus (and npatch (stgit-patch->status npatch)))) (eq status nstatus))) (setq opoint (point)) (stgit-previous-patch 1)) (goto-char opoint)) (setq arg (1- arg))))) (defun stgit-next-patch-group (&optional arg) "Move to the next group of patches. If ARG is non-nil, do this ARG times. If ARG is negative, move -ARG groups backwards instead; cf. `stgit-previous-patch-group'." (interactive "p") (stgit-assert-mode) (if (< arg 0) (stgit-previous-patch-group (- arg)) (while (and (not (eobp)) (> arg 0)) (let* ((patch (stgit-patch-at-point)) (status (and patch (stgit-patch->status patch)))) (while (and (not (eobp)) (let* ((npatch (stgit-patch-at-point)) (nstatus (and npatch (stgit-patch->status npatch)))) (eq status nstatus))) (stgit-next-patch 1))) (setq arg (1- arg))))) (defvar stgit-mode-hook nil "Run after `stgit-mode' is setup.") (defvar stgit-mode-map nil "Keymap for StGit major mode.") (unless stgit-mode-map (let ((diff-map (make-sparse-keymap)) (toggle-map (make-sparse-keymap))) (mapc (lambda (arg) (define-key diff-map (car arg) (cdr arg))) '(("b" . stgit-diff-base) ("c" . stgit-diff-combined) ("m" . stgit-find-file-merge) ("o" . stgit-diff-ours) ("r" . stgit-diff-range) ("t" . stgit-diff-theirs))) (mapc (lambda (arg) (define-key toggle-map (car arg) (cdr arg))) '(("n" . stgit-toggle-patch-names) ("t" . stgit-toggle-worktree) ("h" . stgit-toggle-committed) ("i" . stgit-toggle-ignored) ("u" . stgit-toggle-unknown) ("s" . stgit-toggle-svn))) (setq stgit-mode-map (make-keymap)) (suppress-keymap stgit-mode-map) (mapc (lambda (arg) (define-key stgit-mode-map (car arg) (cdr arg))) `((" " . stgit-mark-down) ("m" . stgit-mark-down) ("\d" . stgit-unmark-up) ("u" . stgit-unmark-down) ("?" . stgit-help) ("h" . stgit-help) ("\C-p" . stgit-previous-line) ("\C-n" . stgit-next-line) ([up] . stgit-previous-line) ([down] . stgit-next-line) ("p" . stgit-previous-patch) ("n" . stgit-next-patch) ("\M-{" . stgit-previous-patch-group) ("\M-}" . stgit-next-patch-group) ([(control up)] . stgit-previous-patch-group) ([(control down)] . stgit-next-patch-group) ("s" . stgit-git-status) ("g" . stgit-reload-or-repair) ("r" . stgit-refresh) ("\C-c\C-r" . stgit-rename) ("e" . stgit-edit) ("M" . stgit-move-patches) ("S" . stgit-squash) ("N" . stgit-new) ("c" . stgit-new-and-refresh) ("\C-c\C-c" . stgit-commit) ("\C-c\C-u" . stgit-uncommit) ("U" . stgit-revert) ("R" . stgit-resolve-file) ("\r" . stgit-select) ("+" . stgit-expand) ("-" . stgit-collapse) ("o" . stgit-find-file-other-window) ("\C-o" . stgit-new-here) ([insertline] . stgit-new-here) ("i" . stgit-toggle-index) (">" . stgit-push-next) ("<" . stgit-pop-next) ("P" . stgit-push-or-pop) ("G" . stgit-goto) ("=" . stgit-diff) ("D" . stgit-delete) ([?\C-/] . stgit-undo) ("\C-_" . stgit-undo) ([?\C-c ?\C-/] . stgit-redo) ("\C-c\C-_" . stgit-redo) ("B" . stgit-branch) ("\C-c\C-b" . stgit-rebase) ("t" . ,toggle-map) ("d" . ,diff-map) ("q" . stgit-quit) ("!" . stgit-execute)))) (let ((at-unmerged-file '(let ((file (stgit-patched-file-at-point))) (and file (eq (stgit-file->status file) 'unmerged)))) (patch-collapsed-p '(lambda (p) (not (memq p stgit-expanded-patches))))) (easy-menu-define stgit-menu stgit-mode-map "StGit Menu" `("StGit" ["Reload" stgit-reload-or-repair :help "Reload StGit status from disk"] ["Repair" stgit-repair :keys "\\[universal-argument] \\[stgit-reload-or-repair]" :help "Repair StGit metadata"] "-" ["Undo" stgit-undo t] ["Redo" stgit-redo t] "-" ["Git status" stgit-git-status :active (fboundp 'git-status)] "-" ["New patch" stgit-new-and-refresh :help "Create a new patch from changes in index or work tree" :active (not (and (stgit-index-empty-p) (stgit-work-tree-empty-p)))] ["New empty patch" stgit-new :help "Create a new, empty patch"] ["(Un)mark patch" stgit-toggle-mark :label (if (memq (stgit-patch-name-at-point nil t) stgit-marked-patches) "Unmark patch" "Mark patch") :active (stgit-patch-name-at-point nil t)] ["Expand/collapse patch" (let ((patches (stgit-patches-marked-or-at-point))) (if (member-if ,patch-collapsed-p patches) (stgit-expand patches) (stgit-collapse patches))) :label (if (member-if ,patch-collapsed-p (stgit-patches-marked-or-at-point)) "Expand patches" "Collapse patches") :active (stgit-patches-marked-or-at-point)] ["Edit patch" stgit-edit :help "Edit patch comment" :active (stgit-patch-name-at-point nil t)] ["Rename patch" stgit-rename :active (stgit-patch-name-at-point nil t)] ["Push/pop patch" stgit-push-or-pop :label (if (subsetp (stgit-patches-marked-or-at-point nil t) (stgit-applied-patchsyms t)) "Pop patches" "Push patches")] ["Delete patches" stgit-delete :active (stgit-patches-marked-or-at-point nil t)] "-" ["Move patches" stgit-move-patches :active stgit-marked-patches :help "Move marked patch(es) to point"] ["Squash patches" stgit-squash :active (> (length stgit-marked-patches) 1) :help "Merge marked patches into one"] "-" ["Refresh top patch" stgit-refresh :active (not (and (stgit-index-empty-p) (stgit-work-tree-empty-p))) :help "Refresh the top patch with changes in index or work tree"] ["Refresh this patch" (stgit-refresh t) :keys "\\[universal-argument] \\[stgit-refresh]" :help "Refresh marked patch with changes in index or work tree" :active (and (not (and (stgit-index-empty-p) (stgit-work-tree-empty-p))) (stgit-patch-name-at-point nil t))] "-" ["Find file" stgit-select :active (eq (get-text-property (point) 'entry-type) 'file)] ["Open file" stgit-find-file-other-window :active (eq (get-text-property (point) 'entry-type) 'file)] ["Toggle file index" stgit-toggle-index :active (and (eq (get-text-property (point) 'entry-type) 'file) (memq (stgit-patch-name-at-point) '(:work :index))) :label (if (eq (stgit-patch-name-at-point) :work) "Move change to index" "Move change to work tree")] "-" ["Show diff" stgit-diff :active (get-text-property (point) 'entry-type)] ["Show diff for range of applied patches" stgit-diff-range :active (= (length stgit-marked-patches) 1)] ("Merge" :active (stgit-git-index-unmerged-p) ["Combined diff" stgit-diff-combined :active (memq (stgit-patch-name-at-point nil nil) '(:work :index))] ["Diff against base" stgit-diff-base :help "Show diff against the common base" :active (memq (stgit-patch-name-at-point nil nil) '(:work :index))] ["Diff against ours" stgit-diff-ours :help "Show diff against our branch" :active (memq (stgit-patch-name-at-point nil nil) '(:work :index))] ["Diff against theirs" stgit-diff-theirs :help "Show diff against their branch" :active (memq (stgit-patch-name-at-point nil nil) '(:work :index))] "-" ["Interactive merge" stgit-find-file-merge :help "Interactively merge the file" :active ,at-unmerged-file] ["Resolve file" stgit-resolve-file :help "Mark file conflict as resolved" :active ,at-unmerged-file] ) "-" ["Show index & work tree" stgit-toggle-worktree :style toggle :selected stgit-show-worktree] ["Show unknown files" stgit-toggle-unknown :style toggle :selected stgit-show-unknown :active stgit-show-worktree] ["Show ignored files" stgit-toggle-ignored :style toggle :selected stgit-show-ignored :active stgit-show-worktree] ["Show patch names" stgit-toggle-patch-names :style toggle :selected stgit-show-patch-names] ["Show recent commits" stgit-toggle-committed :style toggle :selected stgit-show-committed] ["Show subversion info" stgit-toggle-svn :style toggle :selected stgit-show-svn] "-" ["Switch branches" stgit-branch t :help "Switch to or create another branch"] ["Rebase branch" stgit-rebase t :help "Rebase the current branch"] "-" ["Customize StGit" (customize-group 'stgit)] )))) ;; disable tool bar editing buttons (put 'stgit-mode 'mode-class 'special) (defun stgit-mode () "Major mode for interacting with StGit. Start StGit using \\[stgit]. Basic commands: \\\ \\[stgit-help] Show this help text \\[stgit-quit] Hide the StGit buffer \\[describe-bindings] Show all key bindings \\[stgit-reload-or-repair] Reload the StGit buffer \\[universal-argument] \\[stgit-reload-or-repair] Repair StGit metadata \\[stgit-undo] Undo most recent StGit operation \\[stgit-redo] Undo recent undo \\[stgit-git-status] Run `git-status' (if available) \\[stgit-execute] Run an stg shell command Movement commands: \\[stgit-previous-line] Move to previous line \\[stgit-next-line] Move to next line \\[stgit-previous-patch] Move to previous patch \\[stgit-next-patch] Move to next patch \\[stgit-previous-patch-group] Move to previous patch group \\[stgit-next-patch-group] Move to next patch group \\[stgit-mark-down] Mark patch and move down \\[stgit-unmark-up] Unmark patch and move up \\[stgit-unmark-down] Unmark patch and move down Commands for patches: \\[stgit-select] Toggle showing changed files in patch \\[stgit-refresh] Refresh patch with changes in index or work tree \\[stgit-diff] Show the patch log and diff \\[stgit-expand] Show changes in marked patches \\[stgit-collapse] Hide changes in marked patches \\[stgit-new-and-refresh] Create a new patch from index or work tree \\[stgit-new] Create a new, empty patch \\[stgit-new-here] Create a new, empty patch before patch at point \\[stgit-rename] Rename patch \\[stgit-edit] Edit patch description \\[stgit-delete] Delete patch(es) \\[stgit-revert] Revert all changes in index or work tree \\[stgit-toggle-index] Toggle all changes between index and work tree \\[stgit-push-next] Push next patch onto stack \\[stgit-pop-next] Pop current patch from stack \\[stgit-push-or-pop] Push or pop marked patches \\[stgit-goto] Make patch at point current by popping or pushing \\[stgit-squash] Squash (meld together) patches \\[stgit-move-patches] Move marked patches to point \\[stgit-commit] Commit patch(es) \\[stgit-uncommit] Uncommit patch(es) Commands for files: \\[stgit-select] Open the file in this window \\[stgit-find-file-other-window] Open the file in another window \\[stgit-diff] Show the file's diff \\[stgit-toggle-index] Toggle change between index and work tree \\[stgit-revert] Revert changes to file Display commands: \\[stgit-toggle-patch-names] Toggle showing patch names \\[stgit-toggle-worktree] Toggle showing index and work tree \\[stgit-toggle-unknown] Toggle showing unknown files \\[stgit-toggle-ignored] Toggle showing ignored files \\[stgit-toggle-committed] Toggle showing recent commits \\[stgit-toggle-svn] Toggle showing subversion information Commands for diffs: \\[stgit-diff] Show diff of patch or file \\[stgit-diff-range] Show diff for range of patches \\[stgit-diff-base] Show diff against the merge base \\[stgit-diff-ours] Show diff against our branch \\[stgit-diff-theirs] Show diff against their branch With one prefix argument (e.g., \\[universal-argument] \\[stgit-diff]), \ ignore space changes. With two prefix arguments (e.g., \\[universal-argument] \ \\[universal-argument] \\[stgit-diff]), ignore all space changes. Commands for merge conflicts: \\[stgit-find-file-merge] Resolve conflicts using `smerge-ediff' \\[stgit-resolve-file] Mark unmerged file as resolved Commands for branches: \\[stgit-branch] Switch to or create another branch \\[stgit-rebase] Rebase the current branch Customization variables: `stgit-abbreviate-copies-and-renames' `stgit-default-show-ignored' `stgit-default-show-patch-names' `stgit-default-show-unknown' `stgit-default-show-worktree' `stgit-default-show-committed' `stgit-default-show-svn' `stgit-default-committed-count' `stgit-find-copies-harder' `stgit-show-worktree-mode' See also \\[customize-group] for the \"stgit\" group." (kill-all-local-variables) (buffer-disable-undo) (setq mode-name "StGit" major-mode 'stgit-mode goal-column 2) (use-local-map stgit-mode-map) (mapc (lambda (x) (set (make-local-variable (car x)) (cdr x))) `((list-buffers-directory . ,default-directory) (parse-sexp-lookup-properties . t) (stgit-expanded-patches . (:work :index)) (stgit-index-node . nil) (stgit-worktree-node . nil) (stgit-marked-patches . nil) (stgit-svn-find-rev-hash . ,(make-hash-table :test 'equal)) (stgit-committed-count . ,stgit-default-committed-count) (stgit-show-committed . ,stgit-default-show-committed) (stgit-show-ignored . ,stgit-default-show-ignored) (stgit-show-patch-names . ,stgit-default-show-patch-names) (stgit-show-svn . ,stgit-default-show-svn) (stgit-show-unknown . ,stgit-default-show-unknown) (stgit-show-worktree . ,stgit-default-show-worktree))) (set-variable 'truncate-lines 't) (add-hook 'after-save-hook 'stgit-update-stgit-for-buffer) (unless stgit-did-advise (stgit-advise) (setq stgit-did-advise t)) (run-hooks 'stgit-mode-hook)) (defun stgit-advise-funlist (funlist) "Add advice to the functions in FUNLIST so we can refresh the stgit buffers as the git status of files change." (mapc (lambda (sym) (when (fboundp sym) (eval `(defadvice ,sym (after stgit-update-stgit-for-buffer) (stgit-update-stgit-for-buffer :index))) (ad-activate sym))) funlist)) (defun stgit-advise () "Add advice to appropriate (non-stgit) git functions so we can refresh the stgit buffers as the git status of files change." (mapc (lambda (arg) (let ((feature (car arg)) (funlist (cdr arg))) (if (featurep feature) (stgit-advise-funlist funlist) (add-to-list 'after-load-alist `(,feature (stgit-advise-funlist (quote ,funlist))))))) ;; lists of ( ...) to be advised '((vc-git vc-git-rename-file vc-git-revert vc-git-register) (git git-add-file git-checkout git-revert-file git-remove-file) (dired dired-delete-file)))) (defvar stgit-pending-refresh-buffers nil "Alist of (`buffer' . `mode') of buffers that need to be refreshed. See `stgit-post-refresh' for the different values of `mode'.") (defun stgit-run-pending-refreshs () "Run all pending stgit buffer updates as posted by `stgit-post-refresh'." (let ((buffers stgit-pending-refresh-buffers) (stgit-inhibit-messages t)) (setq stgit-pending-refresh-buffers nil) (while buffers (let* ((elem (car buffers)) (buffer (car elem)) (mode (cdr elem))) (when (buffer-name buffer) (with-current-buffer buffer (stgit-save-excursion (if (eq mode :reload) (stgit-reload) (stgit-refresh-worktree) (when (eq mode :index) (stgit-refresh-index))))))) (setq buffers (cdr buffers))))) (defun stgit-post-refresh (buffer mode) "Update status in BUFFER when Emacs becomes idle. MODE specifies what to do: :work only update work tree :index update work tree and index :reload reload the entire buffer" (unless (memq mode '(:work :index :reload)) (error "Illegal refresh mode in stgit-post-refresh")) (unless stgit-pending-refresh-buffers (run-with-idle-timer 0.1 nil 'stgit-run-pending-refreshs)) (let ((elem (assq buffer stgit-pending-refresh-buffers))) (if elem ;; if buffer is already present, update its mode if necessary (let ((omode (cdr elem))) (when (case mode (:index (eq mode :work)) (:reload t)) (setcdr elem mode))) ;; new entry (setq stgit-pending-refresh-buffers (cons (cons buffer mode) stgit-pending-refresh-buffers))))) (defun stgit-update-stgit-for-buffer (&optional mode) "When Emacs becomes idle, update the status in any `stgit-mode' buffer that shows the status of the current buffer. MODE specifies how to update the buffer. See `stgit-post-refresh' for the different values MODE can have." (let* ((dir (cond ((derived-mode-p 'stgit-mode 'stgit-status-mode 'dired-mode) default-directory) (buffer-file-name (file-name-directory (expand-file-name buffer-file-name))))) (gitdir (and dir (condition-case nil (git-get-top-dir dir) (error nil)))) (buffer (and gitdir (stgit-find-buffer gitdir)))) (when buffer (stgit-post-refresh buffer (or mode :work))))) (defun stgit-add-mark (patchsym) "Mark the patch PATCHSYM." (setq stgit-marked-patches (cons patchsym stgit-marked-patches))) (defun stgit-remove-mark (patchsym) "Unmark the patch PATCHSYM." (setq stgit-marked-patches (delq patchsym stgit-marked-patches))) (defun stgit-clear-marks () "Unmark all patches." (setq stgit-marked-patches '())) (defun stgit-patch-at-point (&optional cause-error) (get-text-property (point) 'patch-data)) (defun stgit-patch-name-at-point (&optional cause-error types) "Return the patch name on the current line as a symbol. If CAUSE-ERROR is not nil, signal an error if none found. TYPES controls which types of commits and patches can be returned. If it is t, only allow stgit patches; if 'allow-committed, also allow historical commits; if nil, also allow work tree and index." (let ((patch (stgit-patch-at-point))) (and patch (memq (stgit-patch->status patch) (case types ((nil) nil) ((allow-committed) '(work index)) ((t) '(work index committed)) (t (error "Bad value")))) (setq patch nil)) (cond (patch (stgit-patch->name patch)) (cause-error (error "No patch on this line"))))) (defun stgit-patched-file-at-point () (get-text-property (point) 'file-data)) (defun stgit-patches-marked-or-at-point (&optional cause-error types) "Return the symbols of the marked patches, or the patch on the current line. If CAUSE-ERRROR is not nil, signal an error if none found. TYPES controls which types of commits and patches can be returned. If it is t, only allow stgit patches; if 'allow-committed, also allow historical commits; if nil, also allow work tree and index." (if stgit-marked-patches stgit-marked-patches (let ((patch (stgit-patch-name-at-point nil types))) (cond (patch (list patch)) (cause-error (error "No patches marked or at this line")) (t nil))))) (defun stgit-goto-patch (patchsym &optional file) "Move point to the line containing patch PATCHSYM and return t. If that patch cannot be found, do nothing and return nil. If the patch was found and FILE is not nil, instead move to that file's line and return t. If FILE cannot be found, stay on the line of PATCHSYM and return :patch." (let ((node (ewoc-nth stgit-ewoc 0)) result) (while (and node (not (eq (stgit-patch->name (ewoc-data node)) patchsym))) (setq node (ewoc-next stgit-ewoc node))) (cond ((and node file) (let* ((file-ewoc (stgit-patch->files-ewoc (ewoc-data node))) (file-node (ewoc-nth file-ewoc 0))) (while (and file-node (not (equal (stgit-file->file (ewoc-data file-node)) file))) (setq file-node (ewoc-next file-ewoc file-node))) (if file-node (progn (ewoc-goto-node file-ewoc file-node) (setq result t)) (ewoc-goto-node stgit-ewoc node) (setq result :patch)))) (node (ewoc-goto-node stgit-ewoc node) (setq result t))) (when result (move-to-column (stgit-goal-column))) result)) (defun stgit-init () "Run stg init to initialize the current branch for use with StGit." (interactive) (stgit-assert-mode) (unless (zerop (stgit-capture-output nil (stgit-run "init"))) (error "stg init failed")) (stgit-reload)) (defun stgit-toggle-mark () "Toggle mark on the patch under point." (interactive) (stgit-assert-mode) (if (memq (stgit-patch-name-at-point t t) stgit-marked-patches) (stgit-unmark) (stgit-mark))) (defun stgit-mark () "Mark the patch under point." (interactive) (stgit-assert-mode) (let* ((node (ewoc-locate stgit-ewoc)) (patch (ewoc-data node))) (case (stgit-patch->status patch) (work (error "Cannot mark the work tree")) (index (error "Cannot mark the index")) (committed (error "Cannot mark a committed patch"))) (stgit-add-mark (stgit-patch->name patch)) (let ((column (current-column))) (ewoc-invalidate stgit-ewoc node) (move-to-column column)))) (defun stgit-mark-down () "Mark the patch under point and move to the next patch." (interactive) (stgit-mark) (stgit-next-patch)) (defun stgit-unmark () "Remove mark from the patch on the current line." (interactive) (stgit-assert-mode) (let* ((node (ewoc-locate stgit-ewoc)) (patch (ewoc-data node))) (stgit-remove-mark (stgit-patch->name patch)) (let ((column (current-column))) (ewoc-invalidate stgit-ewoc node) (move-to-column column)))) (defun stgit-unmark-up () "Remove mark from the patch on the previous line." (interactive) (stgit-assert-mode) (stgit-previous-patch) (stgit-unmark)) (defun stgit-unmark-down () "Remove mark from the patch on the current line." (interactive) (stgit-assert-mode) (stgit-unmark) (stgit-next-patch)) (defun stgit-rename (name) "Rename the patch under point to NAME." (interactive (list (read-string "Patch name: " (symbol-name (stgit-patch-name-at-point t t))))) (stgit-assert-mode) (let ((old-patchsym (stgit-patch-name-at-point t t))) (unless (string-equal (symbol-name old-patchsym) name) (stgit-capture-output nil (stgit-run "rename" "--" old-patchsym name)) (let ((name-sym (intern name))) (when (memq old-patchsym stgit-expanded-patches) (setq stgit-expanded-patches (cons name-sym (delq old-patchsym stgit-expanded-patches)))) (when (memq old-patchsym stgit-marked-patches) (setq stgit-marked-patches (cons name-sym (delq old-patchsym stgit-marked-patches)))) (stgit-reload) (stgit-goto-patch name-sym))))) (defun stgit-reload-or-repair (repair) "Update the contents of the StGit buffer (`stgit-reload'). With a prefix argument, repair the StGit metadata if the branch was modified with git commands (`stgit-repair')." (interactive "P") (stgit-assert-mode) (if repair (stgit-repair) (stgit-reload))) (defun stgit-repair () "Run stg repair." (interactive) (stgit-assert-mode) (stgit-capture-output nil (stgit-run "repair")) (stgit-reload)) (defun stgit-available-branches (&optional all skip-current) "Returns a list of the names of the available stg branches as strings. If ALL is not nil, also return non-stgit branches. If SKIP-CURRENT is not nil, do not include the current branch." (let ((output (with-output-to-string (stgit-run "branch" "--list"))) (pattern (format "^%c\\s-+%c\\s-+\\(\\S-+\\)" (if skip-current ?\ ?.) (if all ?. ?s))) (start 0) result) (while (string-match pattern output start) (setq result (cons (match-string 1 output) result)) (setq start (match-end 0))) result)) (defun stgit-branch (branch) "Switch to or create branch BRANCH." (interactive (list (completing-read "Switch to branch: " (stgit-available-branches nil t)))) (stgit-assert-mode) (when (equal branch (stgit-current-branch)) (error "Branch is already current")) (let ((merge (not (and (stgit-index-empty-p) (stgit-work-tree-empty-p))))) (when (cond ((and merge (not (yes-or-no-p "Attempt to merge uncommitted changes? "))) nil) ((member branch (stgit-available-branches t)) (stgit-capture-output nil (apply 'stgit-run (append '("branch") (and merge '("--merge")) '("--") (list branch)))) t) ((not (string-match stgit-allowed-branch-name-re branch)) (error "Invalid branch name")) (merge (error "Cannot merge changes into a new branch")) ((yes-or-no-p (format "Create branch \"%s\"? " branch)) (let ((branch-point (completing-read "Branch from (default current branch): " (stgit-available-branches)))) (stgit-capture-output nil (apply 'stgit-run `("branch" "--create" "--" ,branch ,@(unless (zerop (length branch-point)) (list branch-point))))) t))) ;; Do not expand any (normal) patches in the new branch (setq stgit-expanded-patches (remove-if-not (lambda (p) (memq p '(:work :index))) stgit-expanded-patches)) (stgit-reload)))) (defun stgit-available-refs (&optional omit-stgit) "Returns a list of the available git refs. If OMIT-STGIT is not nil, filter out \"resf/heads/*.stgit\"." (let* ((output (with-output-to-string (stgit-run-git-silent "for-each-ref" "--format=%(refname)" "refs/tags" "refs/heads" "refs/remotes"))) (result (split-string output "\n" t))) (mapcar (lambda (s) (if (string-match "^refs/\\(heads\\|tags\\|remotes\\)/" s) (substring s (match-end 0)) s)) (if omit-stgit (delete-if (lambda (s) (string-match "^refs/heads/.*\\.stgit$" s)) result) result)))) (defun stgit-parent-branch () "Return the parent branch of the current stg branch as per git-config setting branch..stgit.parentbranch." (let ((output (with-output-to-string (stgit-run-git-silent "config" (format "branch.%s.stgit.parentbranch" (stgit-current-branch)))))) (when (string-match ".*" output) (match-string 0 output)))) (defun stgit-rebase (new-base) "Rebase the current branch to NEW-BASE. Interactively, first ask which branch to rebase to. Defaults to what git-config branch..stgit.parentbranch is set to." (interactive (list (completing-read "Rebase to: " (stgit-available-refs t) nil nil (stgit-parent-branch)))) (stgit-assert-mode) (stgit-capture-output nil (stgit-run "rebase" "--" new-base)) (stgit-reload)) (defun stgit-commit (count) "Run stg commit on (at most) COUNT commits. Interactively, the prefix argument is used as COUNT. A negative COUNT will uncommit using `stgit-uncommit' instead." (interactive "p") (stgit-assert-mode) (if (< count 0) (stgit-uncommit (- count)) (setq count (min count (length (stgit-applied-patches t)))) (stgit-capture-output nil (stgit-run "commit" "-n" count)) (stgit-reload))) (defun stgit-uncommit (count) "Run stg uncommit on COUNT commits. Interactively, the prefix argument is used as COUNT. A negative COUNT will commit using `stgit-commit' instead." (interactive "p") (stgit-assert-mode) (if (< count 0) (stgit-commit (- count)) (stgit-capture-output nil (stgit-run "uncommit" "-n" count)) (stgit-reload))) (defun stgit-neighbour-file () "Return the file name of the next file after point, or the previous file if point is at the last file within a patch." (let ((old-point (point)) neighbour-file) (and (zerop (forward-line 1)) (let ((f (stgit-patched-file-at-point))) (and f (setq neighbour-file (stgit-file->file f))))) (goto-char old-point) (unless neighbour-file (and (zerop (forward-line -1)) (let ((f (stgit-patched-file-at-point))) (and f (setq neighbour-file (stgit-file->file f))))) (goto-char old-point)) neighbour-file)) (defun stgit-unmerged-file-stages (file) "Returns list of the merge stages that contain FILE, which must be an unmerged file. Stage 1, the common ancestor, is 'ancestor. Stage 2, HEAD, is 'head. Stage 3, MERGE_HEAD, is 'merge-head." (let ((output (with-output-to-string (stgit-run-git-silent "ls-files" "-u" "-z" "--" (stgit-file->file file)))) stages start) (while (string-match "\\([0-7]*\\) \\([0-9A-Fa-f]\\{40\\}\\) \\([1-3]\\)\t\\([^\0]*\\)\0" output start) (setq stages (cons (elt [ancestor head merge-head] (1- (string-to-number (match-string 3 output)))) stages) start (match-end 0))) stages)) (defun stgit-revert-file () "Revert the file at point, which must be in the index or the working tree." (interactive) (stgit-assert-mode) (let* ((patched-file (or (stgit-patched-file-at-point) (error "No file on the current line"))) (patch-name (stgit-patch-name-at-point)) (file-status (stgit-file->status patched-file)) (rm-file (cond ((stgit-file->copy-or-rename patched-file) (stgit-file->cr-to patched-file)) ((eq file-status 'add) (stgit-file->file patched-file)))) (co-file (cond ((eq file-status 'rename) (stgit-file->cr-from patched-file)) ((not (memq file-status '(copy add unknown))) (stgit-file->file patched-file)))) (next-file (stgit-neighbour-file)) (rm-disk-file (when (memq file-status '(ignore unknown)) (stgit-file->file patched-file))) add-file) (unless (memq patch-name '(:work :index)) (error "No index or working tree file on this line")) (when (eq file-status 'unmerged) (let ((stages (stgit-unmerged-file-stages patched-file))) (if (memq 'head stages) (setq add-file (stgit-file->file patched-file)) (setq rm-file (stgit-file->file patched-file) co-file nil)))) (when (yes-or-no-p (cond (rm-disk-file (format "Delete %s? " rm-disk-file)) ((and rm-file co-file) "Revert 2 files? ") (t (format "Revert %s? " (or rm-file co-file))))) (when rm-disk-file (dired-delete-file rm-disk-file dired-recursive-deletes)) (stgit-capture-output nil (when rm-file (stgit-run-git "rm" "-f" "-q" "--" rm-file)) (when add-file (stgit-run-git "add" "--" add-file)) (when co-file (let ((rev (when (or (eq file-status 'unmerged) (eq patch-name :index)) '("HEAD")))) (apply #'stgit-run-git "checkout" `(,@rev "--" ,co-file))))) (stgit-reload) (stgit-goto-patch patch-name next-file)))) (defun stgit-revert () "Revert the change at point, which must be the index, the work tree, or a single change in either." (interactive) (stgit-assert-mode) (let ((patched-file (stgit-patched-file-at-point))) (if patched-file (stgit-revert-file) (let* ((patch-name (or (stgit-patch-name-at-point) (error "No patch or file at point"))) (patch-desc (case patch-name (:index "index") (:work "work tree") (t (error (substitute-command-keys "Use \\[stgit-delete] to delete a patch")))))) (when (if (eq patch-name :work) (stgit-work-tree-empty-p) (stgit-index-empty-p)) (error (format "There are no changes in the %s to revert" patch-desc))) (and (eq patch-name :index) (not (stgit-work-tree-empty-p)) (error "Cannot revert index as work tree contains unstaged changes")) (when (yes-or-no-p (format "Revert all changes in the %s? " patch-desc)) (if (eq patch-name :index) (stgit-run-git-silent "reset" "--hard" "-q") (stgit-run-git-silent "checkout" "--" ".")) (stgit-save-excursion (stgit-refresh-index) (stgit-refresh-worktree))))))) (defun stgit-resolve-file () "Resolve conflict in the file at point." (interactive) (stgit-assert-mode) (let* ((patched-file (stgit-patched-file-at-point)) (patch (stgit-patch-at-point)) (patch-name (and patch (stgit-patch->name patch))) (status (and patched-file (stgit-file->status patched-file)))) (unless (memq patch-name '(:work :index)) (error "No index or working tree file on this line")) (unless (eq status 'unmerged) (error "No conflict to resolve at the current line")) (stgit-capture-output nil (stgit-move-change-to-index (stgit-file->file patched-file))) (stgit-reload))) (defun stgit-push-or-pop-patches (do-push npatches) "Push (if DO-PUSH is not nil) or pop (if DO-PUSH is nil) NPATCHES patches, or all patches if NPATCHES is t." (stgit-assert-mode) (stgit-capture-output nil (apply 'stgit-run (if do-push "push" "pop") (if (eq npatches t) '("--all") (list "-n" npatches)))) (stgit-reload) (stgit-refresh-git-status)) (defun stgit-push-next (npatches) "Push the first unapplied patch. With numeric prefix argument, push that many patches." (interactive "p") (stgit-push-or-pop-patches t npatches)) (defun stgit-pop-next (npatches) "Pop the topmost applied patch. With numeric prefix argument, pop that many patches. If NPATCHES is t, pop all patches." (interactive "p") (stgit-push-or-pop-patches nil npatches)) (defun stgit-applied-patches (&optional only-patches) "Return a list of the applied patches. If ONLY-PATCHES is not nil, exclude index and work tree." (let ((states (if only-patches '(applied top) '(applied top index work))) result) (ewoc-map (lambda (patch) (when (memq (stgit-patch->status patch) states) (setq result (cons patch result))) nil) stgit-ewoc) result)) (defun stgit-applied-patchsyms (&optional only-patches) "Return a list of the symbols of the applied patches. If ONLY-PATCHES is not nil, exclude index and work tree." (mapcar #'stgit-patch->name (stgit-applied-patches only-patches))) (defun stgit-push-or-pop () "Push or pop the marked patches." (interactive) (stgit-assert-mode) (let* ((patchsyms (stgit-patches-marked-or-at-point t t)) (applied-syms (stgit-applied-patchsyms t)) (unapplied (set-difference patchsyms applied-syms))) (stgit-capture-output nil (apply 'stgit-run (if unapplied "push" "pop") "--" (stgit-sort-patches (if unapplied unapplied patchsyms))))) (stgit-reload)) (defun stgit-at-header-p () "Return non-nil if point is in the header area above all patches." (not (previous-single-property-change (point) 'patch-data))) (defun stgit-at-footer-p () "Return non-nil if point is in the footer area below all patches." (not (next-single-property-change (point) 'patch-data))) (defun stgit-goto-target () "Return the goto target at point: a patchsym, :top, or :bottom." (let ((patch (stgit-patch-at-point))) (cond (patch (case (stgit-patch->status patch) ((work index) nil) ((committed) :bottom) (t (stgit-patch->name patch)))) ((stgit-at-footer-p) :top) ((stgit-at-header-p) :bottom)))) (defun stgit-goto () "Go to the patch on the current line. Push or pop patches to make this patch topmost. Push or pop all patches if used on a line after or before all patches." (interactive) (stgit-assert-mode) (let ((patchsym (stgit-goto-target))) (unless patchsym (error "No patch to go to on this line")) (case patchsym (:top (stgit-push-or-pop-patches t t)) (:bottom (stgit-push-or-pop-patches nil t)) (t (stgit-capture-output nil (stgit-run "goto" "--" patchsym)) (stgit-reload))))) (defun stgit-id (patchsym) "Return the git commit id for PATCHSYM. If PATCHSYM is a keyword, returns PATCHSYM unmodified." (if (keywordp patchsym) patchsym (let ((result (with-output-to-string (stgit-run-silent "id" "--" patchsym)))) (unless (string-match "^\\([0-9A-Fa-f]\\{40\\}\\)$" result) (error "Cannot find commit id for %s" patchsym)) (match-string 1 result)))) (defun stgit-whitespace-diff-arg (arg) (when (numberp arg) (cond ((> arg 4) "--ignore-all-space") ((> arg 1) "--ignore-space-change")))) (defun stgit-show-patch (unmerged-stage ignore-whitespace) "Show the patch on the current line. UNMERGED-STAGE is the argument to `git-diff' that that selects which stage to diff against in the case of unmerged files." (let* ((space-arg (stgit-whitespace-diff-arg ignore-whitespace)) (patch-name (stgit-patch-name-at-point t)) (entry-type (get-text-property (point) 'entry-type)) (diff-desc (case entry-type ('file "diff") ('patch "patch") (t (error "No patch or file at point"))))) (stgit-show-task-message (concat "Showing " diff-desc) (stgit-capture-output (concat "*StGit " diff-desc "*") (case entry-type ('file (let* ((patched-file (stgit-patched-file-at-point)) (patch-id (let ((id (stgit-id patch-name))) (if (and (eq id :index) (eq (stgit-file->status patched-file) 'unmerged)) :work id))) (args (append (and space-arg (list space-arg)) (and (stgit-file->cr-from patched-file) (list (stgit-find-copies-harder-diff-arg))) (cond ((eq patch-id :index) '("--cached")) ((eq patch-id :work) (list unmerged-stage)) (t (list (concat patch-id "^") patch-id))) (and (eq (stgit-file->status patched-file) 'copy) '("--diff-filter=C")) '("--") (if (stgit-file->copy-or-rename patched-file) (list (stgit-file->cr-from patched-file) (stgit-file->cr-to patched-file)) (list (stgit-file->file patched-file)))))) (apply 'stgit-run-git "diff" args))) ('patch (let* ((patch-id (stgit-id patch-name))) (if (or (eq patch-id :index) (eq patch-id :work)) (apply 'stgit-run-git "diff" (stgit-find-copies-harder-diff-arg) (append (and space-arg (list space-arg)) (if (eq patch-id :index) '("--cached") (list unmerged-stage)))) (let ((args (append '("show" "-O" "--patch-with-stat") `("-O" ,(stgit-find-copies-harder-diff-arg)) (and space-arg (list "-O" space-arg)) '("--") (list (stgit-patch-name-at-point))))) (apply 'stgit-run args)))))) (with-current-buffer standard-output (goto-char (point-min)) (diff-mode)))))) (defmacro stgit-define-diff (name diff-arg &optional unmerged-action) `(defun ,name (&optional ignore-whitespace) ,(format "Show the patch on the current line. %sWith a prefix argument, ignore whitespace. With a prefix argument greater than four (e.g., \\[universal-argument] \ \\[universal-argument] \\[%s]), ignore all whitespace." (if unmerged-action (format "For unmerged files, %s.\n\n" unmerged-action) "") name) (interactive "p") (stgit-assert-mode) (stgit-show-patch ,diff-arg ignore-whitespace))) (stgit-define-diff stgit-diff "--ours" nil) (stgit-define-diff stgit-diff-ours "--ours" "diff against our branch") (stgit-define-diff stgit-diff-theirs "--theirs" "diff against their branch") (stgit-define-diff stgit-diff-base "--base" "diff against the merge base") (stgit-define-diff stgit-diff-combined "--cc" "show a combined diff") (defun stgit-diff-range (&optional ignore-whitespace) "Show diff for the range of patches between point and the marked patch. With a prefix argument, ignore whitespace. With a prefix argument greater than four (e.g., \\[universal-argument] \ \\[universal-argument] \\[stgit-diff-range]), ignore all whitespace." (interactive "p") (stgit-assert-mode) (unless (= (length stgit-marked-patches) 1) (error "Need exactly one patch marked")) (let* ((patches (stgit-sort-patches (cons (stgit-patch-name-at-point t 'allow-committed) stgit-marked-patches) t)) (first-patch (car patches)) (second-patch (if (cdr patches) (cadr patches) first-patch)) (whitespace-arg (stgit-whitespace-diff-arg ignore-whitespace)) (applied (stgit-applied-patchsyms t))) (unless (and (memq first-patch applied) (memq second-patch applied)) (error "Can only show diff range for applied patches")) (stgit-capture-output (format "*StGit diff %s..%s*" first-patch second-patch) (apply 'stgit-run-git "diff" "--patch-with-stat" (stgit-find-copies-harder-diff-arg) (append (and whitespace-arg (list whitespace-arg)) (list (format "%s^" (stgit-id first-patch)) (stgit-id second-patch)))) (with-current-buffer standard-output (goto-char (point-min)) (diff-mode))))) (defun stgit-move-change-to-index (file &optional force) "Copies the work tree state of FILE to index, using git add or git rm. If FORCE is not nil, use --force." (let ((op (if (or (file-exists-p file) (file-symlink-p file)) '("add") '("rm" "-q")))) (stgit-capture-output "*git output*" (apply 'stgit-run-git (append op (and force '("--force")) '("--") (list file)))))) (defun stgit-remove-change-from-index (file) "Unstages the change in FILE from the index" (stgit-capture-output "*git output*" (stgit-run-git "reset" "-q" "--" file))) (defun stgit-git-index-unmerged-p () (let (result) (with-output-to-string (setq result (not (zerop (stgit-run-git-silent "diff-index" "--cached" "--diff-filter=U" "--quiet" "HEAD"))))) result)) (defun stgit-assert-no-unmerged-changes () "Signal an error if there are any unmerged changes in the index." (when (stgit-git-index-unmerged-p) (error (substitute-command-keys "Resolve unmerged changes with \\[stgit-resolve-file] first")))) (defun stgit-file-toggle-index () "Move modified file in or out of the index. Leaves the point where it is, but moves the mark to where the file ended up. You can then jump to the file with \ \\[exchange-point-and-mark]." (interactive) (stgit-assert-mode) (let* ((patched-file (or (stgit-patched-file-at-point) (error "No file on the current line"))) (patched-status (stgit-file->status patched-file))) (when (eq patched-status 'unmerged) (error (substitute-command-keys "Use \\[stgit-resolve-file] to move an unmerged file to the index"))) (let* ((patch (stgit-patch-at-point)) (patch-name (stgit-patch->name patch)) (mark-file (if (eq patched-status 'rename) (stgit-file->cr-to patched-file) (stgit-file->file patched-file))) (point-file (if (eq patched-status 'rename) (stgit-file->cr-from patched-file) (stgit-neighbour-file)))) (cond ((eq patch-name :work) (stgit-move-change-to-index (stgit-file->file patched-file) (eq patched-status 'ignore))) ((eq patch-name :index) (stgit-remove-change-from-index (stgit-file->file patched-file))) (t (error "Can only move files between working tree and index"))) (stgit-save-excursion (stgit-refresh-worktree) (stgit-refresh-index)) (stgit-goto-patch (if (eq patch-name :index) :work :index) mark-file) (push-mark nil t t) (setq deactivate-mark t) (stgit-goto-patch patch-name point-file)))) (defun stgit-toggle-index () "Move change in or out of the index. Works on index and work tree, as well as files in either. Leaves the point where it is, but moves the mark to where the file ended up. You can then jump to the file with \ \\[exchange-point-and-mark]." (interactive) (stgit-assert-mode) (if (stgit-patched-file-at-point) (stgit-file-toggle-index) (let ((patch-name (stgit-patch-name-at-point))) (unless (memq patch-name '(:index :work)) (error "Can only move changes between working tree and index")) (stgit-assert-no-unmerged-changes) (if (if (eq patch-name :index) (stgit-index-empty-p) (stgit-work-tree-empty-p)) (message "No changes to be moved") (stgit-capture-output nil (if (eq patch-name :work) (stgit-run-git "add" "--update") (stgit-run-git "reset" "--mixed" "-q"))) (stgit-save-excursion (stgit-refresh-worktree) (stgit-refresh-index))) (stgit-goto-patch patch-name) (push-mark nil t t) (setq deactivate-mark t) (stgit-goto-patch (if (eq patch-name :index) :work :index))))) (defun stgit-edit () "Edit the patch on the current line." (interactive) (stgit-assert-mode) (let ((patchsym (stgit-patch-name-at-point t t)) (edit-buf (get-buffer-create "*StGit edit*")) (dir default-directory)) (log-edit 'stgit-confirm-edit t nil edit-buf) (set (make-local-variable 'stgit-edit-patchsym) patchsym) (setq default-directory dir) (let ((standard-output edit-buf)) (save-excursion (stgit-run-silent "edit" "--save-template=-" "--" patchsym))))) (defun stgit-confirm-edit () (interactive) (let ((file (make-temp-file "stgit-edit-"))) (write-region (point-min) (point-max) file) (stgit-capture-output nil (stgit-run "edit" "-f" file "--" stgit-edit-patchsym)) (with-current-buffer log-edit-parent-buffer (stgit-reload)))) (defun stgit-new-here (add-sign) "Create a new patch before the patch at point, asking for a commit message. With a prefix argument, include a \"Signed-off-by:\" line at the end of the patch description. This works like `stgit-new' followed by `stgit-move'." (interactive "P") (stgit-assert-mode) (let ((patch (stgit-patch-at-point t))) (case (stgit-patch->status patch) ((index work) (stgit-new add-sign)) ((applied top) (unless (and (stgit-index-empty-p) (stgit-work-tree-empty-p)) (error "Index and worktree must not contain any changes")) (stgit-new add-sign nil (stgit-patch->name patch))) (t (error "Can only be used on applied patches"))))) (defun stgit-new (add-sign &optional refresh sink-to) "Create a new patch, asking for a commit message. With a prefix argument, include a \"Signed-off-by:\" line at the end of the message. If REFRESH is non-nil, also refresh the patch after creating it. If SINK-TO is non-nil, sink the created patch to the patch with that name (a symbol)." (interactive "P") (stgit-assert-mode) (let ((edit-buf (get-buffer-create "*StGit edit*")) (dir default-directory)) (log-edit 'stgit-confirm-new t nil edit-buf) (setq default-directory dir) (set (make-local-variable 'stgit-refresh-after-new) refresh) (set (make-local-variable 'stgit-sink-to) sink-to) (when add-sign (save-excursion (let ((standard-output (current-buffer))) (stgit-run-silent "new" "--sign" "--save-template=-")))))) (defun stgit-confirm-new () (interactive) (let ((file (make-temp-file "stgit-edit-")) (refresh stgit-refresh-after-new) new-patch) (write-region (point-min) (point-max) file) (stgit-capture-output nil (stgit-run "new" "-f" file)) (let ((top (with-output-to-string (stgit-run "top")))) (when (string-match "\\`\\(.+\\)" top) (setq new-patch (intern (match-string 1 top))))) (when stgit-sink-to (stgit-run "sink" "-t" stgit-sink-to)) (with-current-buffer log-edit-parent-buffer (if refresh (stgit-refresh) (stgit-reload)) (stgit-goto-patch new-patch)))) (defun stgit-new-and-refresh (add-sign) "Create a new patch based on the current changes, asking for a commit message. With a prefix argument, include a \"Signed-off-by:\" line at the end of the patch. This works just like running `stgit-new' followed by `stgit-refresh'." (interactive "P") (stgit-assert-mode) (stgit-assert-no-unmerged-changes) (stgit-new add-sign t)) (defun stgit-create-patch-name (description) "Create a patch name from a long description" (let ((patch "")) (while (> (length description) 0) (cond ((string-match "\\`[a-zA-Z_-]+" description) (setq patch (downcase (concat patch (match-string 0 description)))) (setq description (substring description (match-end 0)))) ((string-match "\\` +" description) (setq patch (concat patch "-")) (setq description (substring description (match-end 0)))) ((string-match "\\`[^a-zA-Z_-]+" description) (setq description (substring description (match-end 0)))))) (cond ((= (length patch) 0) "patch") ((> (length patch) 20) (substring patch 0 20)) (t patch)))) (defun stgit-delete (patchsyms &optional spill-p) "Delete the patches in PATCHSYMS. Interactively, delete the marked patches, or the patch at point. With a prefix argument, or SPILL-P, spill the patch contents to the work tree and index." (interactive (list (stgit-patches-marked-or-at-point t t) current-prefix-arg)) (stgit-assert-mode) (unless patchsyms (error "No patches to delete")) (when (memq :index patchsyms) (error "Cannot delete the index")) (when (memq :work patchsyms) (error "Cannot delete the work tree")) (let ((npatches (length patchsyms))) (when (yes-or-no-p (format "Really delete %d patch%s%s? " npatches (if (= 1 npatches) "" "es") (if spill-p " (spilling contents to index)" ""))) (let ((args (append (when spill-p '("--spill")) '("--") patchsyms))) (stgit-capture-output nil (apply 'stgit-run "delete" args)) (stgit-reload))))) (defun stgit-move-patches-target () "Return the patchsym indicating a target patch for `stgit-move-patches'. This is either the first unmarked patch at or after point, or one of :top and :bottom if the point is after or before the applied patches." (save-excursion (let (result) (while (not result) (let ((patchsym (stgit-patch-name-at-point))) (cond ((memq patchsym '(:work :index)) (setq result :top)) (patchsym (if (memq patchsym stgit-marked-patches) (stgit-next-patch) (setq result patchsym))) ((re-search-backward "^>" nil t) (setq result :top)) (t (setq result :bottom))))) result))) (defun stgit-sort-patches (patchsyms &optional allow-duplicates) "Returns the list of patches in PATCHSYMS sorted according to their position in the patch series, bottommost first. PATCHSYMS must not contain duplicate entries, unless ALLOW-DUPLICATES is not nil." (let (sorted-patchsyms) (ewoc-map #'(lambda (patch) (let ((name (stgit-patch->name patch))) (when (memq name patchsyms) (setq sorted-patchsyms (cons name sorted-patchsyms)))) nil) stgit-ewoc) (setq sorted-patchsyms (nreverse sorted-patchsyms)) (unless allow-duplicates (unless (= (length patchsyms) (length sorted-patchsyms)) (error "Internal error"))) sorted-patchsyms)) (defun stgit-move-patches (patchsyms target-patch) "Move the patches in PATCHSYMS to below TARGET-PATCH. If TARGET-PATCH is :bottom or :top, move the patches to the bottom or top of the stack, respectively. Interactively, move the marked patches to where the point is." (interactive (list stgit-marked-patches (stgit-move-patches-target))) (stgit-assert-mode) (unless patchsyms (error "Need at least one patch to move")) (unless target-patch (error "Point not at a patch")) ;; need to have patchsyms sorted by position in the stack (let ((sorted-patchsyms (stgit-sort-patches patchsyms))) (stgit-capture-output nil (if (eq target-patch :top) (apply 'stgit-run "float" "--" sorted-patchsyms) (apply 'stgit-run "sink" (append (unless (eq target-patch :bottom) (list "--to" target-patch)) '("--") sorted-patchsyms))))) (stgit-reload)) (defun stgit-squash (patchsyms) "Squash the patches in PATCHSYMS. Interactively, squash the marked patches. Unless there are any conflicts, the patches will be merged into one patch, which will occupy the same spot in the series as the deepest patch had before the squash." (interactive (list stgit-marked-patches)) (stgit-assert-mode) (when (< (length patchsyms) 2) (error "Need at least two patches to squash")) (let ((stgit-buffer (current-buffer)) (edit-buf (get-buffer-create "*StGit edit*")) (dir default-directory) (sorted-patchsyms (stgit-sort-patches patchsyms))) (log-edit 'stgit-confirm-squash t nil edit-buf) (set (make-local-variable 'stgit-patchsyms) sorted-patchsyms) (setq default-directory dir) (let ((result (let ((standard-output edit-buf)) (save-excursion (apply 'stgit-run-silent "squash" "--save-template=-" "--" sorted-patchsyms))))) ;; stg squash may have reordered the patches or caused conflicts (with-current-buffer stgit-buffer (stgit-reload)) (unless (eq 0 result) (fundamental-mode) (rename-buffer "*StGit error*") (resize-temp-buffer-window) (switch-to-buffer-other-window stgit-buffer) (error "stg squash failed"))))) (defun stgit-confirm-squash () (interactive) (let ((file (make-temp-file "stgit-edit-"))) (write-region (point-min) (point-max) file) (stgit-capture-output nil (apply 'stgit-run "squash" "-f" file "--" stgit-patchsyms)) (with-current-buffer log-edit-parent-buffer (stgit-clear-marks) ;; Go to first marked patch and stay there (goto-char (point-min)) (re-search-forward (concat "^[>+-]\\*") nil t) (move-to-column goal-column) (let ((pos (point))) (stgit-reload) (goto-char pos))))) (defun stgit-help () "Display help for the StGit mode." (interactive) (describe-function 'stgit-mode)) (defun stgit-execute-process-sentinel (process sentinel) (let (old-sentinel stgit-buf) (with-current-buffer (process-buffer process) (setq old-sentinel old-process-sentinel stgit-buf stgit-buffer)) (and (memq (process-status process) '(exit signal)) (buffer-live-p stgit-buf) (with-current-buffer stgit-buf (stgit-reload))) (funcall old-sentinel process sentinel))) (defun stgit-execute-process-filter (process output) (with-current-buffer (process-buffer process) (let* ((old-point (point)) (pmark (process-mark process)) (insert-at (marker-position pmark)) (at-pmark (= insert-at old-point))) (goto-char insert-at) (insert-before-markers output) (comint-carriage-motion insert-at (point)) (set-marker pmark (point)) (unless at-pmark (goto-char old-point))))) (defun stgit-execute (&optional git-mode) "Prompt for an stg command to execute in a shell. The names of any marked patches or the patch at point are inserted in the command to be executed. With a prefix argument, or if GIT-MODE is non-nil, insert SHA1 sums of the marked patches instead, and prompt for a git command. If the command ends in an ampersand, run it asynchronously. When the command has finished, reload the stgit buffer." (interactive "P") (stgit-assert-mode) (let* ((patches (stgit-sort-patches (stgit-patches-marked-or-at-point nil 'allow-committed))) (patch-names (mapcar 'symbol-name patches)) (hyphens (find-if (lambda (s) (string-match "^-" s)) patch-names)) (program (if git-mode stgit-git-program stgit-stg-program)) (defaultcmd (concat program " " (and patch-names " ") (and hyphens patch-names "-- ") (mapconcat (if git-mode 'stgit-id 'identity) patch-names " "))) (cmd (read-from-minibuffer "Shell command: " (cons defaultcmd (+ (length program) 2)) nil nil 'shell-command-history)) (async (string-match "&[ \t]*\\'" cmd)) (buffer (get-buffer-create (if async "*Async Shell Command*" "*Shell Command Output*")))) ;; cannot use minibuffer as stgit-reload would overwrite it; if we ;; show the buffer, shell-command will not use the minibuffer (display-buffer buffer) (shell-command cmd) (if async (let ((old-buffer (current-buffer))) (with-current-buffer buffer (let ((process (get-buffer-process buffer))) (set (make-local-variable 'old-process-sentinel) (process-sentinel process)) (set (make-local-variable 'stgit-buffer) old-buffer) (set-process-filter process 'stgit-execute-process-filter) (set-process-sentinel process 'stgit-execute-process-sentinel)))) (with-current-buffer buffer (comint-carriage-motion (point-min) (point-max))) (shrink-window-if-larger-than-buffer (get-buffer-window buffer)) (stgit-reload)))) (defun stgit-undo-or-redo (redo hard) "Run stg undo or, if REDO is non-nil, stg redo. If HARD is non-nil, use the --hard flag." (stgit-assert-mode) (let ((cmd (if redo "redo" "undo"))) (stgit-capture-output nil (if arg (when (or (and (stgit-index-empty-p) (stgit-work-tree-empty-p)) (y-or-n-p (format "Hard %s may overwrite index/work tree changes. Continue? " cmd))) (stgit-run cmd "--hard")) (stgit-run cmd)))) (stgit-reload)) (defun stgit-undo (&optional arg) "Run stg undo. With prefix argument, run it with the --hard flag. See also `stgit-redo'." (interactive "P") (stgit-undo-or-redo nil arg)) (defun stgit-redo (&optional arg) "Run stg redo. With prefix argument, run it with the --hard flag. See also `stgit-undo'." (interactive "P") (stgit-undo-or-redo t arg)) (defun stgit-refresh (&optional arg) "Run stg refresh. If the index contains any changes, only refresh from index. With prefix argument, refresh the marked patch or the patch under point." (interactive "P") (stgit-assert-mode) (stgit-assert-no-unmerged-changes) (let ((patchargs (if arg (let ((patches (stgit-patches-marked-or-at-point t t))) (when (> (length patches) 1) (error "Too many patches marked")) (cons "-p" patches)) nil))) (unless (stgit-index-empty-p) (setq patchargs (cons "--index" patchargs))) (stgit-capture-output nil (apply 'stgit-run "refresh" patchargs)) (stgit-refresh-git-status)) (stgit-reload)) (defvar stgit-show-worktree nil "If nil, inhibit showing work tree and index in the stgit buffer. See also `stgit-show-worktree-mode'.") (defvar stgit-show-ignored nil "If nil, inhibit showing files ignored by git.") (defvar stgit-show-unknown nil "If nil, inhibit showing files not registered with git.") (defvar stgit-show-patch-names t "If nil, inhibit showing patch names.") (defvar stgit-show-committed nil "If nil, inhibit showing recent commits.") (defvar stgit-show-svn nil "If nil, inhibit showing git svn information.") (defvar stgit-committed-count nil "The number of recent commits to show.") (defmacro stgit-define-toggle-view (sym desc help) (declare (indent 1) (debug (symbolp stringp stringp))) (let* ((name (symbol-name sym)) (fun (intern (concat "stgit-toggle-" name))) (flag (intern (concat "stgit-show-" name)))) `(progn ;; make help-follow find the correct function (put (quote ,fun) 'definition-name 'stgit-define-toggle-view) (defun ,fun (&optional arg) ,help (interactive "P") (stgit-assert-mode) (setq ,flag (if arg (> (prefix-numeric-value arg) 0) (not ,flag))) (stgit-reload (concat (if ,flag "Showing" "Hiding") " " ,desc)))))) (stgit-define-toggle-view worktree "work tree and index" "Toggle the visibility of the work tree. With ARG, show the work tree if ARG is positive. Its initial setting is controlled by `stgit-default-show-worktree'. `stgit-show-worktree-mode' controls where on screen the index and work tree will show up.") (stgit-define-toggle-view ignored "ignored files" "Toggle the visibility of files ignored by git in the work tree. With ARG, show these files if ARG is positive. Its initial setting is controlled by `stgit-default-show-ignored'. Use \\[stgit-toggle-worktree] to show the work tree.") (stgit-define-toggle-view unknown "unknown files" "Toggle the visibility of files not registered with git in the work tree. With ARG, show these files if ARG is positive. Its initial setting is controlled by `stgit-default-show-unknown'. Use \\[stgit-toggle-worktree] to show the work tree.") (stgit-define-toggle-view patch-names "patch names" "Toggle the visibility of patch names. With ARG, show patch names if ARG is positive. The initial setting is controlled by `stgit-default-show-patch-names'.") (stgit-define-toggle-view svn "subversion revisions" "Toggle showing subversion information from git svn. With ARG, show svn information if ARG is positive. The initial setting is controlled by `stgit-default-show-svn'.") (defun stgit-toggle-committed (&optional arg) "Toggle the visibility of historical git commits. With ARG, set the number of commits to show to ARG, and disable them if ARG is zero. The initial setting is controlled by `stgit-default-show-committed'." (interactive "P") (stgit-assert-mode) (if (null arg) (setq stgit-show-committed (not stgit-show-committed)) (let ((n (prefix-numeric-value arg))) (setq stgit-show-committed (> n 0)) (setq stgit-committed-count n))) (stgit-reload (format "%s historical commits" (if (and stgit-show-committed (> stgit-committed-count 0)) "Showing" "Hiding")))) (provide 'stgit) ;;; stgit.el ends here stgit-0.19/contrib/vim/000077500000000000000000000000001337022307200150275ustar00rootroot00000000000000stgit-0.19/contrib/vim/README000066400000000000000000000005071337022307200157110ustar00rootroot00000000000000To syntax highlight StGit commit messages in vim: * For the current user only: > mkdir -p ~/.vim/ftdetect ~/.vim/syntax > cp syntax/*.vim ~/.vim/syntax/ > cp ftdetect/*.vim ~/.vim/ftdetect/ * For all users: # cp syntax/*.vim /usr/share/vim/site/syntax/ # cp ftdetect/*.vim /usr/share/vim/site/ftdetect/ stgit-0.19/contrib/vim/ftdetect/000077500000000000000000000000001337022307200166315ustar00rootroot00000000000000stgit-0.19/contrib/vim/ftdetect/stg.vim000066400000000000000000000035251337022307200201500ustar00rootroot00000000000000" Vim filetype detection plugin " Language: StGit commit messages " Author: Zane Bitter if has("autocmd") " Detect 'stg new' files autocmd BufNewFile,BufRead .stgit-new.txt setlocal filetype=stgnew autocmd BufNewFile,BufRead .stgitmsg.txt setlocal filetype=stgnew " Ignore the modeline so we get type 'stgnew' instead of 'diff' autocmd BufNewFile,BufRead .stgitmsg.txt setlocal nomodeline " Detect 'stg edit' files autocmd BufNewFile,BufRead .stgit-edit.txt setlocal filetype=stgedit autocmd BufNewFile,BufRead .stgit-edit.patch setlocal filetype=stgedit autocmd BufNewFile,BufRead .stgit-edit.diff setlocal filetype=stgedit autocmd BufNewFile,BufRead .stgit-failed.patch setlocal filetype=stgedit " Detect 'stg squash' files autocmd BufNewFile,BufRead .stgit-squash.txt setlocal filetype=stgsquash " Detect 'stg mail' files autocmd BufNewFile,BufRead .stgitmail.txt setlocal filetype=stgmail " A modeline in a diff belongs to the diffed file, so ignore it autocmd BufNewFile,BufRead .stgit-edit.patch setlocal nomodeline autocmd BufNewFile,BufRead .stgit-edit.diff setlocal nomodeline autocmd BufNewFile,BufRead .stgit-failed.patch setlocal nomodeline autocmd BufNewFile,BufRead .stgitmail.txt setlocal nomodeline " Set parameters on 'stg new' files to be consistent with the modeline autocmd FileType stgnew setlocal textwidth=75 autocmd FileType stgnew setlocal nobackup " For other stg files set textwidth the same as 'stg new' autocmd FileType stgedit setlocal textwidth=75 autocmd FileType stgmail setlocal textwidth=75 autocmd FileType stgsquash setlocal textwidth=75 endif " has("autocmd") stgit-0.19/contrib/vim/syntax/000077500000000000000000000000001337022307200163555ustar00rootroot00000000000000stgit-0.19/contrib/vim/syntax/stgedit.vim000066400000000000000000000023221337022307200205340ustar00rootroot00000000000000" Vim syntax file " Language: StGit 'stg edit' commit message file " Author: Zane Bitter if exists("b:current_syntax") finish endif runtime! syntax/mail.vim unlet b:current_syntax syn include @stgDiff syntax/diff.vim syn case match syn sync minlines=50 if has("spell") syn spell toplevel endif syn match stgeditFrom "\%^From:.*" contains=mailHeader nextgroup=stgeditFirstLine skipempty syn match stgeditFirstLine "^.\+" contained nextgroup=stgeditDiffs,stgeditComment,stgeditBlank skipnl syn match stgeditSummary "^.\{0,50\}" contained containedin=stgeditFirstLine nextgroup=stgeditOverflow contains=@Spell syn match stgeditOverflow ".*" contained contains=@Spell syn match stgeditBlank "^.\+" contained contains=@Spell syn match stgeditComment "^#.*" syn region stgeditDiffs start="^---" end="%$" contains=@stgDiff fold syn region stgeditDiff start="^\%(diff --git \)\@=" end="^\%(diff --git \|$\)\@=" contained containedin=stgeditDiffs contains=@stgDiff fold hi def link stgeditSummary Keyword hi def link stgeditComment Comment hi def link stgeditBlank Error let b:current_syntax = "stgedit" stgit-0.19/contrib/vim/syntax/stgmail.vim000066400000000000000000000012461337022307200205350ustar00rootroot00000000000000" Vim syntax file " Language: StGit 'stg mail' file " Author: Zane Bitter if exists("b:current_syntax") finish endif runtime! syntax/mail.vim unlet b:current_syntax syn include @stgDiff syntax/diff.vim syn case match syn sync minlines=50 if has("spell") syn spell toplevel endif syn match stgmailComment "^#.*" syn region stgmailDiffs start="^---" end="%$" contains=@stgDiff fold syn region stgmailDiff start="^\%(diff --git \)\@=" end="^\%(diff --git \|$\)\@=" contained containedin=stgmailDiffs contains=@stgDiff fold hi def link stgmailComment Comment let b:current_syntax = "stgmail" stgit-0.19/contrib/vim/syntax/stgnew.vim000066400000000000000000000015621337022307200204050ustar00rootroot00000000000000" Vim syntax file " Language: StGit 'stg new' commit message file " Author: Zane Bitter if exists("b:current_syntax") finish endif syn case match syn sync minlines=50 if has("spell") syn spell toplevel endif syn match stgnewFirstLine "\%^.*" nextgroup=stgnewSTG,stgnewComment,stgnewBlank skipnl syn match stgnewSummary "^.\{0,50\}" contained containedin=stgnewFirstLine nextgroup=stgnewOverflow contains=@Spell syn match stgnewOverflow ".*" contained contains=@Spell syn match stgnewBlank "^.\+" contained contains=@Spell syn match stgnewSTG "^STG:.*" syn match stgnewComment "^#.*" hi def link stgnewSummary Keyword hi def link stgnewComment Comment hi def link stgnewSTG Comment hi def link stgnewBlank Error let b:current_syntax = "stgnew" stgit-0.19/contrib/vim/syntax/stgsquash.vim000066400000000000000000000026661337022307200211260ustar00rootroot00000000000000" Vim syntax file " Language: StGit 'stg squash' commit message file " Author: Zane Bitter if exists("b:current_syntax") finish endif syn case match syn sync minlines=50 if has("spell") syn spell toplevel endif syn match stgsqFirstLine "\%^.*" nextgroup=stgsqComment,stgsqContext,stgsqBlank skipnl syn match stgsqSummary "^.\{0,50\}" contained containedin=stgsqFirstLine nextgroup=stgsqOverflow contains=@Spell syn match stgsqOverflow ".*" contained contains=@Spell syn match stgsqBlank "^.\+" contained contains=@Spell syn match stgsqSeparator "-\+$" contained syn region stgsqPatch start="^\(.\{66\}-\{4\}$\)\@=" end="\(^.\{66\}-\{4\}$\)\@=" contained containedin=stgsqContext contains=@Spell fold syn match stgsqNextPatch "^.\{66\}-\{4\}$" contained containedin=stgsqPatch contains=stgsqPatchName syn match stgsqPatchName "^.\{-\}\(-*$\)\@=" contained containedin=stgsqNextPatch nextgroup=stgsqSeparator syn region stgsqContext start="^---" end="%$" contains=@Spell fold syn match stgsqComment "^#.*" hi def link stgsqSummary Keyword hi def link stgsqComment Comment hi def link stgsqBlank Error hi def link stgsqContext Comment hi def link stgsqPatch Constant hi def link stgsqPatchName Identifier hi def link stgsqSeparator Comment let b:current_syntax = "stgsquash" stgit-0.19/debian/000077500000000000000000000000001337022307200140165ustar00rootroot00000000000000stgit-0.19/debian/.gitignore000066400000000000000000000000561337022307200160070ustar00rootroot00000000000000stgit files stgit.substvars stgit.*.debhelper stgit-0.19/debian/changelog000066400000000000000000000035401337022307200156720ustar00rootroot00000000000000stgit (0.19) unstable; urgency=low * New upstream release -- Peter Grayson Mon, 06 Nov 2018 03:40:00 +0000 stgit (0.18) unstable; urgency=low * New upstream release -- Catalin Marinas Mon, 18 Aug 2017 19:53:26 +0100 stgit (0.17.1-0) unstable; urgency=low * New upstream release -- Catalin Marinas Mon, 30 Sep 2013 17:18:35 +0000 stgit (0.17-0) unstable; urgency=low * New upstream release -- PJ Waskiewicz Thu, 27 Jun 2013 15:39:19 -0700 stgit (0.16-0) unstable; urgency=low * New upstream release -- Catalin Marinas Mon, 09 Jan 2012 22:10:19 +0000 stgit (0.15-0) unstable; urgency=low * New upstream release -- Catalin Marinas Sat, 24 Oct 2009 22:45:35 +0100 stgit (0.14.3-0) unstable; urgency=low * New upstream release -- Catalin Marinas Sun, 08 Jun 2008 23:31:51 +0100 stgit (0.14.2-0) unstable; urgency=low * New upstream release -- Catalin Marinas Mon, 24 Mar 2008 19:23:33 +0000 stgit (0.14.1-0) unstable; urgency=low * New upstream release -- Catalin Marinas Tue, 11 Dec 2007 23:51:07 +0000 stgit (0.14-0) unstable; urgency=low * New upstream release -- Catalin Marinas Sun, 09 Dec 2007 23:44:13 +0000 stgit (0.13-0) unstable; urgency=low * New upstream release -- Catalin Marinas Thu, 26 Jul 2007 00:03:03 +0100 stgit (0.12-0) unstable; urgency=low * New upstream release -- Catalin Marinas Tue, 6 Feb 2007 22:47:05 +0000 stgit (0.11-0) unstable; urgency=low * New upstream release -- Catalin Marinas Sat, 21 Oct 2006 09:41:52 +0100 stgit-0.19/debian/compat000066400000000000000000000000021337022307200152140ustar00rootroot000000000000004 stgit-0.19/debian/control000066400000000000000000000013121337022307200154160ustar00rootroot00000000000000Source: stgit Section: devel Priority: optional Maintainer: Catalin Marinas Build-Depends: debhelper (>= 4.0.0), python-dev Standards-Version: 3.6.2 Package: stgit Architecture: all Depends: ${shlibs:Depends}, ${misc:Depends}, ${python:Depends}, git-core Description: provide Quilt functionality on top of GIT StGIT (Stacked GIT) provides similar functionality to Quilt (i.e. pushing/popping patches to/from a stack) on top of GIT. . These operations are performed using GIT commands and the patches are stored as GIT commit objects, allowing easy merging of the StGIT patches into other repositories using standard GIT functionality. . Homepage: http://www.procode.org/stgit/ stgit-0.19/debian/copyright000066400000000000000000000016621337022307200157560ustar00rootroot00000000000000This package was downloaded from http://www.procode.org/stgit/ Copyright Holder: Catalin Marinas and various contributors License: This package is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This package 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 package; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA On Debian systems, the complete text of the GNU General Public License can be found in `/usr/share/common-licenses/GPL'. stgit-0.19/debian/dirs000066400000000000000000000000101337022307200146710ustar00rootroot00000000000000usr/bin stgit-0.19/debian/docs000066400000000000000000000000141337022307200146640ustar00rootroot00000000000000README TODO stgit-0.19/debian/rules000077500000000000000000000035001337022307200150740ustar00rootroot00000000000000#!/usr/bin/make -f # -*- makefile -*- # Sample debian/rules that uses debhelper. # This file was originally written by Joey Hess and Craig Small. # As a special exception, when this file is copied by dh-make into a # dh-make output file, you may use that output file without restriction. # This special exception was added by Craig Small in version 0.37 of dh-make. # Uncomment this to turn on verbose mode. #export DH_VERBOSE=1 CFLAGS = -Wall -g ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS))) CFLAGS += -O0 else CFLAGS += -O2 endif configure: configure-stamp configure-stamp: dh_testdir # Add here commands to configure the package. touch configure-stamp build: build-stamp build-stamp: configure-stamp dh_testdir $(MAKE) all doc touch build-stamp clean: dh_testdir dh_testroot rm -f build-stamp configure-stamp # Add here commands to clean up after the build process. -$(MAKE) clean dh_clean install: build dh_testdir dh_testroot dh_clean -k dh_installdirs # Add here commands to install the package into debian/stgit. $(MAKE) DESTDIR=$(CURDIR)/debian/stgit prefix=/usr install install-doc install-html # Build architecture-independent files here. binary-indep: build install # We have nothing to do by default. # Build architecture-dependent files here. binary-arch: build install dh_testdir dh_testroot dh_installchangelogs dh_installdocs dh_installexamples # dh_install # dh_installmenu # dh_installdebconf # dh_installlogrotate # dh_installemacsen # dh_installpam # dh_installmime # dh_installinit # dh_installcron # dh_installinfo dh_installman dh_link dh_strip dh_compress dh_fixperms # dh_perl dh_python # dh_makeshlibs dh_installdeb dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb binary: binary-indep binary-arch .PHONY: build clean binary-indep binary-arch binary install configure stgit-0.19/examples/000077500000000000000000000000001337022307200144125ustar00rootroot00000000000000stgit-0.19/examples/gitconfig000066400000000000000000000056011337022307200163100ustar00rootroot00000000000000# StGIT configuration file. Copy it to any of ~/.gitconfig or # .git/config and modify as needed. Note that the latter overrides # the former. The "git config" command can be used as well [user] # Default author/committer details (standard GIT variables) name = Your Name email = your.name@yourcompany.com [stgit] # E-mail sender (added to the "From: " header) #sender = Your Name # Automatically Bcc the address below #autobcc = your.name@yourcompany.com # Automatically sign newly created patches #autosign = Signed-off-by # SMTP server for sending patches #smtpserver = /usr/sbin/sendmail -t -i #smtpserver = localhost:25 # Set to 'yes' to use SMTP over TLS #smtptls = no # Username for SMTP authentication, required if TLS is used #smtpuser = username # Password for SMTP. If not provided, it will be asked #smtppassword = password # delay between messages in seconds (defaults to 5) #smtpdelay = 5 # stg will look for this first, then look for the EDITOR environmental # variable, then default to using 'vi' #editor = /usr/bin/vi # this value overrides the default PAGER environment variable #pager = less -FRSX #pager = filterdiff --annotate | colordiff | less -FRSX # GIT pull and fetch commands (should take the same arguments as # git fetch or git pull). By default: #pullcmd = git pull #fetchcmd = git fetch # Rebase command. Note that this command is internally implemented in # a different way. Only define this option if a different rebase # is needed (i.e. 'git svn rebase') #rebasecmd = git reset # "stg pull" policy. This is the repository default, which can be # overriden on a per-branch basis using branch.*.stgit.pull-policy # By default: #pull-policy = pull # To support remote rewinding parent branches: #pull-policy = fetch-rebase # To support local parent branches: #pull-policy = rebase # Automatically invoke the interactive merger (git mergetool) in case # of conflicts #autoimerge = no # Optimize (repack) the object store after every pull #keepoptimized = yes # Extensions for the files involved in a three-way merge (ancestor, # current, patched) #extensions = .ancestor .current .patched # The number of patches to be listed before and after the # current one by the 'series --short' command #shortnr = 5 # The maximum length of an automatically generated patch name #namelength = 30 # Extra options to pass to "git diff" (extend/override with # -O/--diff-opts). For example, -M turns on rename detection. #diff-opts = -M # Behave as if the --keep option is always passed #autokeep = no [stgit "alias"] # Command aliases. #add = git add [mail "alias"] # E-mail aliases used with the 'mail' command git = git@vger.kernel.org [stgit "color"] # Specify output colors for series commands applied = green_foreground current = red_foreground unapplied = white_foreground hidden = cyan_foreground stgit-0.19/examples/patchdescr.tmpl000066400000000000000000000000671337022307200174330ustar00rootroot00000000000000 Signed-off-by: Your Name stgit-0.19/perf/000077500000000000000000000000001337022307200135305ustar00rootroot00000000000000stgit-0.19/perf/.gitignore000066400000000000000000000000211337022307200155110ustar00rootroot00000000000000/*.orig /*.trash stgit-0.19/perf/create_synthetic_repo.py000066400000000000000000000036121337022307200204660ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) next_mark = 1 def get_mark(): global next_mark next_mark += 1 return (next_mark - 1) def write_data(s): print('data %d' % len(s)) print(s) def write_blob(s): print('blob') m = get_mark() print('mark :%d' % m) write_data(s) return m def write_commit(branch, files, msg, parent = None): print('commit %s' % branch) m = get_mark() print('mark :%d' % m) auth = 'X Ample %d +0000' % (1000000000 + m) print('author %s' % auth) print('committer %s' % auth) write_data(msg) if parent is not None: print('from :%d' % parent) for fn, fm in sorted(files.items()): print('M 100644 :%d %s' % (fm, fn)) return m def set_ref(ref, mark): print('reset %s' % ref) print('from :%d' % mark) def stdblob(fn): return ''.join('%d %s\n' % (x, fn) for x in range(10)) def iter_paths(): for i in range(32): for j in range(32): for k in range(32): yield '%02d/%02d/%02d' % (i, j, k) def setup(): def t(name): return 'refs/tags/%s' % name files = dict((fn, write_blob(stdblob(fn))) for fn in iter_paths()) initial = write_commit(t('bomb-base'), files, 'Initial commit') set_ref(t('bomb-top'), initial) for fn in iter_paths(): write_commit(t('bomb-top'), { fn: write_blob(stdblob(fn) + 'Last line\n') }, 'Add last line to %s' % fn) write_commit(t('add-file'), { 'woo-hoo.txt': write_blob('woo-hoo\n') }, 'Add a new file', parent = initial) files = dict((fn, write_blob('First line\n' + stdblob(fn))) for fn in iter_paths()) write_commit(t('modify-all'), files, 'Add first line to all files', parent = initial) setup() stgit-0.19/perf/find_patchbomb.py000066400000000000000000000016221337022307200170420ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Feed this with git rev-list HEAD --parents from __future__ import (absolute_import, division, print_function, unicode_literals) import sys parents = {} for line in sys.stdin.readlines(): commits = line.split() parents[commits[0]] = commits[1:] sequence_num = {} stack = [] for commit in parents: stack.append(commit) while stack: c = stack.pop() if c in sequence_num: continue ps = parents[c] if len(ps) == 1: p = ps[0] if p in sequence_num: sequence_num[c] = 1 + sequence_num[p] else: stack.append(c) stack.append(p) else: sequence_num[c] = 0 (num, commit) = max((num, commit) for (commit, num) in sequence_num.items()) print('%s is a sequence of %d patches' % (commit, num)) stgit-0.19/perf/perftest.py000066400000000000000000000060511337022307200157400ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import datetime import os import subprocess import sys def duration(t1, t2): d = t2 - t1 return 86400*d.days + d.seconds + 1e-6*d.microseconds class Run(object): def __init__(self): self.__cwd = None self.__log = [] def __logfile(self, cmd): fn = os.path.join(os.getcwd(), '%04d.log' % len(self.__log)) f = open(fn, 'w') f.write(' '.join(cmd) + '\n' + '-'*70 + '\n\n') f.close() return fn def __call__(self, *cmd, **args): env = dict(os.environ) env['STGIT_SUBPROCESS_LOG'] = 'profile:' + self.__logfile(cmd) kwargs = { 'cwd': self.__cwd, 'env': env } if args.get('capture_stdout', False): kwargs['stdout'] = subprocess.PIPE start = datetime.datetime.now() p = subprocess.Popen(cmd, **kwargs) (out, err) = p.communicate() stop = datetime.datetime.now() self.__log.append((cmd, duration(start, stop))) return out def cd(self, dir): self.__cwd = dir def summary(self): def pcmd(c): return ' '.join(c) def ptime(t): return '%.3f' % t (cs, times) = zip(*self.__log) ttime = sum(times) cl = max(len(pcmd(c)) for c in cs) tl = max(len(ptime(t)) for t in list(times) + [ttime]) for (c, t) in self.__log: print('%*s %*s' % (tl, ptime(t), -cl, pcmd(c))) print('%*s' % (tl, ptime(ttime))) perftests = {} perftestdesc = {} def perftest(desc, name = None): def decorator(f): def g(): r = Run() f(r) r.summary() perftests[name or f.__name__] = g perftestdesc[name or f.__name__] = desc return g return decorator def copy_testdir(dir): tmp = dir + '.trash' r = Run() r('rsync', '-a', '--delete', dir + '.orig/', tmp) return tmp def new_rebase(r, ref): top = r('stg', 'top', capture_stdout = True) r('stg', 'pop', '-a') r('git', 'reset', '--hard', ref) r('stg', 'goto', top.strip()) def old_rebase(r, ref): r('stg', 'rebase', ref) def def_rebasetest(rebase, dir, tag): @perftest('%s rebase onto %s in %s' % (rebase, tag, dir), 'rebase-%srebase-%s-%s' % (rebase, tag, dir)) def rebasetest(r): r.cd(copy_testdir(dir)) r('stg', 'init') if dir == 'synt': r('stg', 'uncommit', '-n', '500') else: r('stg', 'uncommit', '-x', '-t', 'bomb-base') if rebase == 'new': new_rebase(r, tag) else: old_rebase(r, tag) for rebase in ['old', 'new']: for (dir, tag) in [('synt', 'add-file'), ('synt', 'modify-all'), ('linux', 'add-file')]: def_rebasetest(rebase, dir, tag) args = sys.argv[1:] if len(args) == 0: for (fun, desc) in sorted(perftestdesc.items()): print('%s: %s' % (fun, desc)) else: for test in args: perftests[test]() stgit-0.19/perf/setup.sh000066400000000000000000000021161337022307200152240ustar00rootroot00000000000000krepo='git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git' get_linux() { rm -rf linux.orig git clone "$krepo" linux.orig } mod_linux() { # Tag the top and base of a very long linear sequence of commits. git tag bomb-top 85040bcb4643cba578839e953f25e2d1965d83d0 git tag bomb-base bomb-top~1470 # Add a file at the base of the linear sequence. git checkout bomb-base echo "woo-hoo" > woo-hoo.txt git add woo-hoo.txt git commit -m "Add a file" git tag add-file # Clean up and go to start position. git gc git update-ref refs/heads/master bomb-top git checkout master } setup_linux () { get_linux ( cd linux.orig && mod_linux ) } create_empty () { dir="$1" rm -rf $dir mkdir $dir ( cd $dir && git init ) } fill_synthetic () { python ../create_synthetic_repo.py | git fast-import git gc --aggressive git update-ref refs/heads/master bomb-top git checkout master } setup_synthetic() { create_empty synt.orig ( cd synt.orig && fill_synthetic ) } setup_linux setup_synthetic stgit-0.19/setup.py000077500000000000000000000102041337022307200143060ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from distutils.core import setup from glob import glob import os import sys from stgit import commands, completion, version def __version_to_list(version): """Convert a version string to a list of numbers or strings """ ver_list = [] for p in version.split('.'): try: n = int(p) except ValueError: n = p ver_list.append(n) return ver_list def __check_min_version(min_ver, ver): """Check whether ver is greater or equal to min_ver """ min_ver_list = __version_to_list(min_ver) ver_list = __version_to_list(ver) return min_ver_list <= ver_list def __check_python_version(): """Check the minimum Python version """ pyver = '.'.join(map(str, sys.version_info)) if not __check_min_version(version.python_min_ver, pyver): print('Python version %s or newer required. Found %s' % (version.python_min_ver, pyver), file=sys.stderr) sys.exit(1) def __check_git_version(): """Check the minimum GIT version """ from stgit.run import Run gitver = Run('git', '--version').output_one_line().split()[2] if not __check_min_version(version.git_min_ver, gitver): print('GIT version %s or newer required. Found %s' % (version.git_min_ver, gitver), file=sys.stderr) sys.exit(1) # Check the minimum versions required __check_python_version() __check_git_version() # ensure readable template files old_mask = os.umask(0o022) for get_ver in [ version.git_describe_version, version.git_archival_version, version.get_builtin_version, ]: try: ver = get_ver() except version.VersionUnavailable: continue else: break else: print('StGit version unavailable', file=sys.stderr) sys.exit(1) with open('stgit/builtin_version.py', 'w') as f: print( '# This file is automatically generated. Do not edit.', 'version = {ver!r}'.format(ver=ver), sep='\n', file=f, ) # generate the python command list with open('stgit/commands/cmdlist.py', 'w') as f: commands.py_commands(commands.get_commands(allow_cached=False), f) # generate the bash completion script with open('stgit-completion.bash', 'w') as f: completion.write_completion(f) setup( name='stgit', version=ver, license='GPLv2', author='Catalin Marinas', author_email='catalin.marinas@gmail.com', url='http://www.procode.org/stgit/', download_url='https://repo.or.cz/stgit.git', description='Stacked GIT', long_description='Push/pop utility on top of GIT', scripts=['stg'], packages=list(map(str, ['stgit', 'stgit.commands', 'stgit.lib'])), data_files=[ ('share/stgit/templates', glob('templates/*.tmpl')), ('share/stgit/examples', glob('examples/*.tmpl')), ('share/stgit/examples', ['examples/gitconfig']), ('share/stgit/contrib', ['contrib/stgbashprompt.sh']), ('share/stgit/completion', ['stgit-completion.bash']), ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)' 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Version Control', ], ) # restore the old mask os.umask(old_mask) stgit-0.19/stg000077500000000000000000000032101337022307200133130ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- python-mode -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os import sys __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ if __name__ == '__main__': if os.environ.get('COVERAGE_PROCESS_START'): import coverage coverage.process_startup() # Try to detect where it is run from and set prefix and the search path. # It is assumed that the user installed StGIT using the --prefix= option prefix, bin = os.path.split(sys.path[0]) if bin == 'bin' and prefix != sys.prefix: sys.prefix = prefix sys.exec_prefix = prefix major, minor = sys.version_info[0:2] local_path = [ os.path.join(prefix, 'lib', 'python'), os.path.join(prefix, 'lib', 'python%s.%s' % (major, minor)), os.path.join(prefix, 'lib', 'python%s.%s' % (major, minor), 'site-packages')] sys.path = local_path + sys.path from stgit.main import main main() stgit-0.19/stg-build000077500000000000000000000032301337022307200144120ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- python -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import optparse import sys import stgit.main from stgit import argparse, commands, completion def main(): op = optparse.OptionParser() op.add_option('--asciidoc', metavar = 'CMD', help = 'Print asciidoc documentation for a command') op.add_option('--commands', action = 'store_true', help = 'Print list of all stg subcommands') op.add_option('--cmd-list', action = 'store_true', help = 'Print asciidoc command list') op.add_option('--py-cmd-list', action = 'store_true', help = 'Write Python command list') op.add_option('--bash-completion', action = 'store_true', help = 'Write bash completion code') options, args = op.parse_args() if args: op.error('Wrong number of arguments') if options.asciidoc: argparse.write_asciidoc(stgit.main.commands[options.asciidoc], sys.stdout) elif options.commands: for cmd in sorted(commands.get_commands(allow_cached=False)): print(cmd) elif options.cmd_list: commands.asciidoc_command_list( commands.get_commands(allow_cached = False), sys.stdout) elif options.py_cmd_list: commands.py_commands(commands.get_commands(allow_cached = False), sys.stdout) elif options.bash_completion: completion.write_completion(sys.stdout) else: op.error('No command') if __name__ == '__main__': main() stgit-0.19/stg-dbg000077500000000000000000000031371337022307200140550ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- python-mode -*- """Run stg with the pdb debugger.""" from __future__ import (absolute_import, division, print_function, unicode_literals) import os import pdb import sys __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ if __name__ == '__main__': # Try to detect where it is run from and set prefix and the search path. # It is assumed that the user installed StGIT using the --prefix= option prefix, bin = os.path.split(sys.path[0]) if bin == 'bin' and prefix != sys.prefix: sys.prefix = prefix sys.exec_prefix = prefix major, minor = sys.version_info[0:2] local_path = [ os.path.join(prefix, 'lib', 'python'), os.path.join(prefix, 'lib', 'python%s.%s' % (major, minor)), os.path.join(prefix, 'lib', 'python%s.%s' % (major, minor), 'site-packages')] sys.path = local_path + sys.path from stgit.main import main # noqa pdb.run('main()') stgit-0.19/stg-prof000077500000000000000000000036151337022307200142700ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- python-mode -*- """Run stg with profiling enabled.""" from __future__ import (absolute_import, division, print_function, unicode_literals) import os import profile import pstats import sys import time __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ if __name__ == '__main__': # Try to detect where it is run from and set prefix and the search path. # It is assumed that the user installed StGIT using the --prefix= option prefix, bin = os.path.split(sys.path[0]) if bin == 'bin' and prefix != sys.prefix: sys.prefix = prefix sys.exec_prefix = prefix major, minor = sys.version_info[0:2] local_path = [ os.path.join(prefix, 'lib', 'python'), os.path.join(prefix, 'lib', 'python%s.%s' % (major, minor)), os.path.join(prefix, 'lib', 'python%s.%s' % (major, minor), 'site-packages')] sys.path = local_path + sys.path from stgit.main import main # noqa start_time = time.time() def timer(): return time.time() - start_time prof = profile.Profile(timer) try: prof.run('main()') except SystemExit: pass stats = pstats.Stats(prof) stats.strip_dirs().sort_stats(-1).print_stats().print_callees() stgit-0.19/stgit/000077500000000000000000000000001337022307200137265ustar00rootroot00000000000000stgit-0.19/stgit/.gitignore000066400000000000000000000000311337022307200157100ustar00rootroot00000000000000*.pyc builtin_version.py stgit-0.19/stgit/__init__.py000066400000000000000000000014021337022307200160340ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ stgit-0.19/stgit/argparse.py000066400000000000000000000275621337022307200161200ustar00rootroot00000000000000# -*- coding: utf-8 -*- """This module provides a layer on top of the standard library's C{optparse} module, so that we can easily generate both interactive help and asciidoc documentation (such as man pages).""" from __future__ import (absolute_import, division, print_function, unicode_literals) import io import optparse import sys import textwrap from stgit import utils from stgit.config import config from stgit.lib import git from stgit.out import out def _splitlist(lst, split_on): """Iterate over the sublists of lst that are separated by an element e such that split_on(e) is true.""" current = [] for e in lst: if split_on(e): yield current current = [] else: current.append(e) yield current def _paragraphs(s): """Split a string s into a list of paragraphs, each of which is a list of lines.""" lines = [line.rstrip() for line in textwrap.dedent(s).strip().splitlines()] return [p for p in _splitlist(lines, lambda line: not line.strip()) if p] class opt(object): """Represents a command-line flag.""" def __init__(self, *pargs, **kwargs): self.pargs = pargs self.kwargs = kwargs def get_option(self): kwargs = dict(self.kwargs) kwargs['help'] = kwargs['short'] for k in ['short', 'long', 'args']: kwargs.pop(k, None) return optparse.make_option(*self.pargs, **kwargs) def metavar(self): o = self.get_option() if not o.takes_value(): return None if o.metavar: return o.metavar for flag in self.pargs: if flag.startswith('--'): return utils.strip_prefix('--', flag).upper() raise Exception('Cannot determine metavar') def write_asciidoc(self, f): for flag in self.pargs: f.write(flag) m = self.metavar() if m: f.write(' ' + m) f.write('::\n') paras = _paragraphs(self.kwargs.get('long', self.kwargs['short'] + '.')) for line in paras[0]: f.write(' '*8 + line + '\n') for para in paras[1:]: f.write('+\n') for line in para: f.write(line + '\n') @property def flags(self): return self.pargs @property def args(self): if self.kwargs.get('action', None) in ['store_true', 'store_false']: default = [] else: default = [files] return self.kwargs.get('args', default) def _cmd_name(cmd_mod): return getattr(cmd_mod, 'name', cmd_mod.__name__.split('.')[-1]) def make_option_parser(cmd): pad = ' '*len('Usage: ') return optparse.OptionParser( prog = 'stg %s' % _cmd_name(cmd), usage = (('\n' + pad).join('%%prog %s' % u for u in cmd.usage) + '\n\n' + cmd.help), option_list = [o.get_option() for o in cmd.options]) def _write_underlined(s, u, f): f.write(s + '\n') f.write(u*len(s) + '\n') def write_asciidoc(cmd, f): _write_underlined('stg-%s(1)' % _cmd_name(cmd), '=', f) f.write('\n') _write_underlined('NAME', '-', f) f.write('stg-%s - %s\n\n' % (_cmd_name(cmd), cmd.help)) _write_underlined('SYNOPSIS', '-', f) f.write('[verse]\n') for u in cmd.usage: f.write("'stg' %s %s\n" % (_cmd_name(cmd), u)) f.write('\n') _write_underlined('DESCRIPTION', '-', f) f.write('\n%s\n\n' % cmd.description.strip('\n')) if cmd.options: _write_underlined('OPTIONS', '-', f) for o in cmd.options: o.write_asciidoc(f) f.write('\n') _write_underlined('StGit', '-', f) f.write('Part of the StGit suite - see linkman:stg[1]\n') def sign_options(): def callback(option, opt_str, value, parser, sign_str): if parser.values.sign_str not in [None, sign_str]: raise optparse.OptionValueError( 'Cannot give more than one of --ack, --sign, --review') parser.values.sign_str = sign_str return [ opt('--sign', action = 'callback', dest = 'sign_str', args = [], callback = callback, callback_args = ('Signed-off-by',), short = 'Add "Signed-off-by:" line', long = """ Add a "Signed-off-by:" to the end of the patch."""), opt('--ack', action = 'callback', dest = 'sign_str', args = [], callback = callback, callback_args = ('Acked-by',), short = 'Add "Acked-by:" line', long = """ Add an "Acked-by:" line to the end of the patch."""), opt('--review', action = 'callback', dest = 'sign_str', args = [], callback = callback, callback_args = ('Reviewed-by',), short = 'Add "Reviewed-by:" line', long = """ Add a "Reviewed-by:" line to the end of the patch.""")] def hook_options(): return [ opt('--no-verify', action = 'store_true', dest = 'no_verify', default = False, short = 'Disable commit-msg hook', long = """ This option bypasses the commit-msg hook."""), ] def message_options(save_template): def no_dup(parser): if parser.values.message is not None: raise optparse.OptionValueError( 'Cannot give more than one --message or --file') def no_combine(parser): if (save_template and parser.values.message is not None and parser.values.save_template is not None): raise optparse.OptionValueError( 'Cannot give both --message/--file and --save-template') def msg_callback(option, opt_str, value, parser): no_dup(parser) parser.values.message = value no_combine(parser) def file_callback(option, opt_str, value, parser): no_dup(parser) if value == '-': parser.values.message = sys.stdin.read() else: with open(value) as f: parser.values.message = f.read() no_combine(parser) def templ_callback(option, opt_str, value, parser): if value == '-': def w(s): out.stdout_bytes(s) else: def w(s): with io.open(value, 'wb') as f: f.write(s) parser.values.save_template = w no_combine(parser) opts = [ opt('-m', '--message', action = 'callback', callback = msg_callback, dest = 'message', type = 'string', short = 'Use MESSAGE instead of invoking the editor'), opt('-f', '--file', action = 'callback', callback = file_callback, dest = 'message', type = 'string', args = [files], metavar = 'FILE', short = 'Use FILE instead of invoking the editor', long = """ Use the contents of FILE instead of invoking the editor. (If FILE is "-", write to stdout.)""")] if save_template: opts.append( opt('--save-template', action = 'callback', dest = 'save_template', callback = templ_callback, metavar = 'FILE', type = 'string', short = 'Save the message template to FILE and exit', long = """ Instead of running the command, just write the message template to FILE, and exit. (If FILE is "-", write to stdout.) When driving StGit from another program, it is often useful to first call a command with '--save-template', then let the user edit the message, and then call the same command with '--file'.""")) return opts def diff_opts_option(): def diff_opts_callback(option, opt_str, value, parser): if value: parser.values.diff_flags.extend(value.split()) else: parser.values.diff_flags = [] return [ opt('-O', '--diff-opts', dest = 'diff_flags', default = (config.get('stgit.diff-opts') or '').split(), action = 'callback', callback = diff_opts_callback, type = 'string', metavar = 'OPTIONS', args = [strings('-M', '-C')], short = 'Extra options to pass to "git diff"')] def _person_opts(person, short): """Sets options. to a function that modifies a Person according to the commandline options.""" def short_callback(option, opt_str, value, parser, field): f = getattr(parser.values, person) if field == "date": value = git.Date(value) setattr(parser.values, person, lambda p: getattr(f(p), 'set_' + field)(value)) def full_callback(option, opt_str, value, parser): ne = utils.parse_name_email(value) if not ne: raise optparse.OptionValueError( 'Bad %s specification: %r' % (opt_str, value)) name, email = ne short_callback(option, opt_str, name, parser, 'name') short_callback(option, opt_str, email, parser, 'email') return ( [opt('--%s' % person, metavar = '"NAME "', type = 'string', action = 'callback', callback = full_callback, dest = person, default = lambda p: p, short = 'Set the %s details' % person)] + [opt('--%s%s' % (short, f), metavar = f.upper(), type = 'string', action = 'callback', callback = short_callback, dest = person, callback_args = (f,), short = 'Set the %s %s' % (person, f)) for f in ['name', 'email', 'date']]) def author_options(): return _person_opts('author', 'auth') def keep_option(): return [opt('-k', '--keep', action = 'store_true', short = 'Keep the local changes', default = config.get('stgit.autokeep') == 'yes')] def merged_option(): return [opt('-m', '--merged', action = 'store_true', short = 'Check for patches merged upstream')] class CompgenBase(object): def actions(self, var): return set() def words(self, var): return set() def command(self, var): cmd = ['compgen'] for act in self.actions(var): cmd += ['-A', act] words = self.words(var) if words: cmd += ['-W', '"%s"' % ' '.join(words)] cmd += ['--', '"%s"' % var] return ' '.join(cmd) class CompgenJoin(CompgenBase): def __init__(self, a, b): assert isinstance(a, CompgenBase) assert isinstance(b, CompgenBase) self.__a = a self.__b = b def words(self, var): return self.__a.words(var) | self.__b.words(var) def actions(self, var): return self.__a.actions(var) | self.__b.actions(var) class Compgen(CompgenBase): def __init__(self, words = frozenset(), actions = frozenset()): self.__words = set(words) self.__actions = set(actions) def actions(self, var): return self.__actions def words(self, var): return self.__words def compjoin(compgens): comp = Compgen() for c in compgens: comp = CompgenJoin(comp, c) return comp all_branches = Compgen(['$(_all_branches)']) stg_branches = Compgen(['$(_stg_branches)']) applied_patches = Compgen(['$(_applied_patches)']) other_applied_patches = Compgen(['$(_other_applied_patches)']) unapplied_patches = Compgen(['$(_unapplied_patches)']) hidden_patches = Compgen(['$(_hidden_patches)']) commit = Compgen(['$(_all_branches) $(_tags) $(_remotes)']) conflicting_files = Compgen(['$(_conflicting_files)']) dirty_files = Compgen(['$(_dirty_files)']) unknown_files = Compgen(['$(_unknown_files)']) known_files = Compgen(['$(_known_files)']) repo = Compgen(actions = ['directory']) dir = Compgen(actions = ['directory']) files = Compgen(actions = ['file']) mail_aliases = Compgen(['$(_mail_aliases)']) def strings(*ss): return Compgen(ss) class patch_range(CompgenBase): def __init__(self, *endpoints): self.__endpoints = endpoints def words(self, var): words = set() for e in self.__endpoints: assert not e.actions(var) words |= e.words(var) return set(['$(_patch_range "%s" "%s")' % (' '.join(words), var)]) stgit-0.19/stgit/basedir.py000066400000000000000000000024271337022307200157160ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Access to the GIT base directory.""" from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit.compat import environ_get from stgit.run import Run, RunException __copyright__ = """ Copyright (C) 2006, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ # GIT_DIR value cached __base_dir = None def get(): """Return the .git directory location """ global __base_dir if not __base_dir: __base_dir = environ_get('GIT_DIR') if __base_dir is None: try: __base_dir = Run('git', 'rev-parse', '--git-dir').output_one_line() except RunException: __base_dir = '' return __base_dir stgit-0.19/stgit/commands/000077500000000000000000000000001337022307200155275ustar00rootroot00000000000000stgit-0.19/stgit/commands/.gitignore000066400000000000000000000000141337022307200175120ustar00rootroot00000000000000/cmdlist.py stgit-0.19/stgit/commands/__init__.py000066400000000000000000000067241337022307200176510ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os from stgit.compat import text from stgit.utils import strip_suffix __copyright__ = """ Copyright (C) 2005, Catalin Marinas Copyright (C) 2008, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ def get_command(mod): """Import and return the given command module.""" return __import__(__name__ + '.' + mod, globals(), locals(), ['*']) _kinds = [('repo', 'Repository commands'), ('stack', 'Stack (branch) commands'), ('patch', 'Patch commands'), ('wc', 'Index/worktree commands'), ('alias', 'Alias commands')] _kind_order = [kind for kind, desc in _kinds] _kinds = dict(_kinds) def _find_commands(): for p in __path__: for fn in os.listdir(p): if not fn.endswith('.py'): continue mod = text(strip_suffix('.py', fn)) m = get_command(mod) if not hasattr(m, 'usage'): continue yield mod, m def get_commands(allow_cached = True): """Return a map from command name to a tuple of module name, command type, and one-line command help.""" if allow_cached: try: from stgit.commands.cmdlist import command_list return command_list except ImportError: # cmdlist.py doesn't exist, so do it the expensive way. pass return dict((text(getattr(m, 'name', mod)), (mod, _kinds[m.kind], m.help)) for mod, m in _find_commands()) def py_commands(commands, f): f.write('from __future__ import unicode_literals\n\n') f.write('command_list = {\n') for name, (mod, kind, help) in commands.items(): f.write(' %r: (\n' % name) f.write(' %r,\n' % mod) f.write(' %r,\n' % kind) f.write(' %r,\n' % help) f.write(' ),\n') f.write('}\n') def _command_list(commands): kinds = {} for cmd, (mod, kind, help) in commands.items(): kinds.setdefault(kind, {})[cmd] = help for kind in _kind_order: kind = _kinds[kind] try: yield kind, sorted(kinds[kind].items()) except KeyError: pass def pretty_command_list(commands, f): cmd_len = max(len(cmd) for cmd in commands) sep = '' for kind, cmds in _command_list(commands): f.write(sep) sep = '\n' f.write('%s:\n' % kind) for cmd, help in cmds: f.write(' %*s %s\n' % (-cmd_len, cmd, help)) def _write_underlined(s, u, f): f.write(s + '\n') f.write(u*len(s) + '\n') def asciidoc_command_list(commands, f): for kind, cmds in _command_list(commands): _write_underlined(kind, '~', f) f.write('\n') for cmd, help in cmds: f.write('linkstg:%s[]::\n' % cmd) f.write(' %s\n' % help) f.write('\n') stgit-0.19/stgit/commands/branch.py000066400000000000000000000326771337022307200173550ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import re import time from stgit import argparse, stack, git from stgit.argparse import opt from stgit.commands.common import (CmdException, DirectoryGotoToplevel, check_local_changes, check_conflicts, check_head_top_equal, git_id) from stgit.lib import log from stgit.out import out __copyright__ = """ Copyright (C) 2005, Chuck Lever This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Branch operations: switch, list, create, rename, delete, ...' kind = 'stack' usage = ['', '[--merge] [--] ', '--list', '--create [--] []', '--clone [--] []', '--rename [--] ', '--protect [--] []', '--unprotect [--] []', '--delete [--force] [--] ', '--cleanup [--force] [--] []', '--description= [--] []'] description = """ Create, clone, switch between, rename, or delete development branches within a git repository. 'stg branch':: Display the name of the current branch. 'stg branch' :: Switch to the given branch.""" args = [argparse.all_branches] options = [ opt('-l', '--list', action = 'store_true', short = 'List the branches contained in this repository', long = """ List each branch in the current repository, followed by its branch description (if any). The current branch is prefixed with '>'. Branches that have been initialized for StGit (with linkstg:init[]) are prefixed with 's'. Protected branches are prefixed with 'p'."""), opt('-c', '--create', action = 'store_true', short = 'Create (and switch to) a new branch', long = """ Create (and switch to) a new branch. The new branch is already initialized as an StGit patch stack, so you do not have to run linkstg:init[] manually. If you give a committish argument, the new branch is based there; otherwise, it is based at the current HEAD. StGit will try to detect the branch off of which the new branch is forked, as well as the remote repository from which that parent branch is taken (if any), so that running linkstg:pull[] will automatically pull new commits from the correct branch. It will warn if it cannot guess the parent branch (e.g. if you do not specify a branch name as committish)."""), opt('--clone', action = 'store_true', short = 'Clone the contents of the current branch', long = """ Clone the current branch, under the name if specified, or using the current branch's name plus a timestamp. The description of the new branch is set to tell it is a clone of the current branch. The parent information of the new branch is copied from the current branch."""), opt('-r', '--rename', action = 'store_true', short = 'Rename an existing branch'), opt('-p', '--protect', action = 'store_true', short = 'Prevent StGit from modifying a branch', long = """ Prevent StGit from modifying a branch -- either the current one, or one named on the command line."""), opt('-u', '--unprotect', action = 'store_true', short = 'Allow StGit to modify a branch', long = """ Allow StGit to modify a branch -- either the current one, or one named on the command line. This undoes the effect of an earlier 'stg branch --protect' command."""), opt('--delete', action = 'store_true', short = 'Delete a branch', long = """ Delete the named branch. If there are any patches left in the branch, StGit will refuse to delete it unless you give the '--force' flag. A protected branch cannot be deleted; it must be unprotected first (see '--unprotect' above). If you delete the current branch, you are switched to the "master" branch, if it exists."""), opt('--cleanup', action = 'store_true', short = 'Clean up the StGit metadata for a branch', long = """ Remove the StGit information for the current or given branch. If there are patches left in the branch, StGit refuses the operation unless '--force' is given. A protected branch cannot be cleaned up; it must be unprotected first (see '--unprotect' above). A cleaned up branch can be re-initialised using the 'stg init' command."""), opt('-d', '--description', short = 'Set the branch description'), opt('--merge', action = 'store_true', short = 'Merge work tree changes into the other branch'), opt('--force', action = 'store_true', short = 'Force a delete when the series is not empty')] directory = DirectoryGotoToplevel(log=False) crt_series = None def __is_current_branch(branch_name): return crt_series.get_name() == branch_name def __print_branch(branch_name, length): initialized = ' ' current = ' ' protected = ' ' branch = stack.Series(branch_name) if branch.is_initialised(): initialized = 's' if __is_current_branch(branch_name): current = '>' if branch.get_protected(): protected = 'p' out.stdout(current + ' ' + initialized + protected + '\t' + branch_name.ljust(length) + ' | ' + branch.get_description()) def __delete_branch(doomed_name, force = False): doomed = stack.Series(doomed_name) if __is_current_branch(doomed_name): raise CmdException('Cannot delete the current branch') if doomed.get_protected(): raise CmdException('This branch is protected. Delete is not permitted') out.start('Deleting branch "%s"' % doomed_name) doomed.delete(force) out.done() def __cleanup_branch(name, force = False): branch = stack.Series(name) if branch.get_protected(): raise CmdException('This branch is protected. Clean up is not permitted') out.start('Cleaning up branch "%s"' % name) branch.delete(force = force, cleanup = True) out.done() def func(parser, options, args): if options.create: if len(args) == 0 or len(args) > 2: parser.error('incorrect number of arguments') check_local_changes() check_conflicts() check_head_top_equal(crt_series) tree_id = None if len(args) >= 2: parentbranch = None try: branchpoint = git.rev_parse(args[1]) # parent branch? head_re = re.compile('refs/(heads|remotes)/') ref_re = re.compile(args[1] + '$') for ref in git.all_refs(): if head_re.match(ref) and ref_re.search(ref): # args[1] is a valid ref from the branchpoint # setting above parentbranch = args[1] break except git.GitException: # should use a more specific exception to catch only # non-git refs ? out.info('Don\'t know how to determine parent branch' ' from "%s"' % args[1]) # exception in branch = rev_parse() leaves branchpoint unbound branchpoint = None tree_id = git_id(crt_series, branchpoint or args[1]) if parentbranch: out.info('Recording "%s" as parent branch' % parentbranch) else: out.info('Don\'t know how to determine parent branch' ' from "%s"' % args[1]) else: # branch stack off current branch parentbranch = git.get_head_file() if parentbranch: parentremote = git.identify_remote(parentbranch) if parentremote: out.info('Using remote "%s" to pull parent from' % parentremote) else: out.info('Recording as a local branch') else: # no known parent branch, can't guess the remote parentremote = None stack.Series(args[0]).init(create_at = tree_id, parent_remote = parentremote, parent_branch = parentbranch) out.info('Branch "%s" created' % args[0]) log.compat_log_entry('branch --create') return elif options.clone: if len(args) == 0: clone = crt_series.get_name() + \ time.strftime('-%C%y%m%d-%H%M%S') elif len(args) == 1: clone = args[0] else: parser.error('incorrect number of arguments') check_local_changes() check_conflicts() check_head_top_equal(crt_series) out.start('Cloning current branch to "%s"' % clone) crt_series.clone(clone) out.done() log.copy_log(log.default_repo(), crt_series.get_name(), clone, 'branch --clone') return elif options.delete: if len(args) != 1: parser.error('incorrect number of arguments') __delete_branch(args[0], options.force) log.delete_log(log.default_repo(), args[0]) return elif options.cleanup: if not args: name = crt_series.get_name() elif len(args) == 1: name = args[0] else: parser.error('incorrect number of arguments') __cleanup_branch(name, options.force) log.delete_log(log.default_repo(), name) return elif options.list: if len(args) != 0: parser.error('incorrect number of arguments') branches = set(git.get_heads()) for br in set(branches): m = re.match(r'^(.*)\.stgit$', br) if m and m.group(1) in branches: branches.remove(br) if branches: out.info('Available branches:') max_len = max([len(i) for i in branches]) for i in sorted(branches): __print_branch(i, max_len) else: out.info('No branches') return elif options.protect: if len(args) == 0: branch_name = crt_series.get_name() elif len(args) == 1: branch_name = args[0] else: parser.error('incorrect number of arguments') branch = stack.Series(branch_name) if not branch.is_initialised(): raise CmdException('Branch "%s" is not controlled by StGIT' % branch_name) out.start('Protecting branch "%s"' % branch_name) branch.protect() out.done() return elif options.rename: if len(args) != 2: parser.error('incorrect number of arguments') if __is_current_branch(args[0]): raise CmdException('Renaming the current branch is not supported') stack.Series(args[0]).rename(args[1]) out.info('Renamed branch "%s" to "%s"' % (args[0], args[1])) log.rename_log(log.default_repo(), args[0], args[1], 'branch --rename') return elif options.unprotect: if len(args) == 0: branch_name = crt_series.get_name() elif len(args) == 1: branch_name = args[0] else: parser.error('incorrect number of arguments') branch = stack.Series(branch_name) if not branch.is_initialised(): raise CmdException('Branch "%s" is not controlled by StGIT' % branch_name) out.info('Unprotecting branch "%s"' % branch_name) branch.unprotect() out.done() return elif options.description is not None: if len(args) == 0: branch_name = crt_series.get_name() elif len(args) == 1: branch_name = args[0] else: parser.error('incorrect number of arguments') branch = stack.Series(branch_name) if not branch.is_initialised(): raise CmdException('Branch "%s" is not controlled by StGIT' % branch_name) branch.set_description(options.description) return elif len(args) == 1: if __is_current_branch(args[0]): raise CmdException('Branch "%s" is already the current branch' % args[0]) if not options.merge: check_local_changes() check_conflicts() check_head_top_equal(crt_series) out.start('Switching to branch "%s"' % args[0]) git.switch_branch(args[0]) out.done() return # default action: print the current branch if len(args) != 0: parser.error('incorrect number of arguments') print(crt_series.get_name()) stgit-0.19/stgit/commands/clean.py000066400000000000000000000052351337022307200171700ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Delete the empty patches in the series' kind = 'stack' usage = [''] description = """ Delete the empty patches in the whole series or only those applied or unapplied. A patch is considered empty if the two commit objects representing its boundaries refer to the same tree object.""" args = [] options = [ opt('-a', '--applied', action = 'store_true', short = 'Delete the empty applied patches'), opt('-u', '--unapplied', action = 'store_true', short = 'Delete the empty unapplied patches')] directory = common.DirectoryHasRepositoryLib() def _clean(stack, clean_applied, clean_unapplied): trans = transaction.StackTransaction(stack, 'clean', allow_conflicts = True) def del_patch(pn): if pn in stack.patchorder.applied: if pn == stack.patchorder.applied[-1]: # We're about to clean away the topmost patch. Don't # do that if we have conflicts, since that means the # patch is only empty because the conflicts have made # us dump its contents into the index and worktree. if stack.repository.default_index.conflicts(): return False return clean_applied and trans.patches[pn].data.is_nochange() elif pn in stack.patchorder.unapplied: return clean_unapplied and trans.patches[pn].data.is_nochange() for pn in trans.delete_patches(del_patch): trans.push_patch(pn) trans.run() def func(parser, options, args): """Delete the empty patches in the series """ if len(args) != 0: parser.error('incorrect number of arguments') if not (options.applied or options.unapplied): options.applied = options.unapplied = True _clean(directory.repository.current_stack, options.applied, options.unapplied) stgit-0.19/stgit/commands/clone.py000066400000000000000000000041001337022307200171740ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os from stgit import argparse from stgit.commands import common from stgit.lib import git, stack __copyright__ = """ Copyright (C) 2009, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Make a local clone of a remote repository' kind = 'repo' usage = [' '] description = """ Clone a git repository into the local directory (using linkstg:clone[]) and initialise the local branch "master". This operation is for example suitable to start working using the "tracking branch" workflow (see link:stg[1]). Other means to setup an StGit stack are linkstg:init[] and the '--create' and '--clone' commands of linkstg:branch[]. The target directory will be created by this command, and must not already exist.""" args = [argparse.repo, argparse.dir] options = [] directory = common.DirectoryAnywhere(needs_current_series = False, log = False) def func(parser, options, args): """Clone the into the local and initialises the stack """ if len(args) != 2: parser.error('incorrect number of arguments') repository = args[0] local_dir = args[1] if os.path.exists(local_dir): raise common.CmdException('"%s" exists. Remove it first' % local_dir) git.clone(repository, local_dir) os.chdir(local_dir) directory = common.DirectoryHasRepositoryLib() directory.setup() stack.Stack.initialise(directory.repository) stgit-0.19/stgit/commands/commit.py000066400000000000000000000110251337022307200173700ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Permanently store the applied patches into the stack base' kind = 'stack' usage = ['', '[--] ', '-n NUM', '--all'] description = """ Merge one or more patches into the base of the current stack and remove them from the series while advancing the base. This is the opposite of 'stg uncommit'. Use this command if you no longer want to manage a patch with StGIT. By default, the bottommost patch is committed. If patch names are given, the stack is rearranged so that those patches are at the bottom, and then they are committed. The -n/--number option specifies the number of applied patches to commit (counting from the bottom of the stack). If -a/--all is given, all applied patches are committed.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches)] options = [ opt('-n', '--number', type = 'int', short = 'Commit the specified number of patches'), opt('-a', '--all', action = 'store_true', short = 'Commit all applied patches')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Commit a number of patches.""" stack = directory.repository.current_stack args = common.parse_patches(args, list(stack.patchorder.all_visible)) if len([x for x in [args, options.number is not None, options.all] if x]) > 1: parser.error('too many options') if args: patches = [pn for pn in stack.patchorder.all_visible if pn in args] bad = set(args) - set(patches) if bad: raise common.CmdException('Nonexistent or hidden patch names: %s' % ', '.join(sorted(bad))) elif options.number is not None: if options.number <= len(stack.patchorder.applied): patches = stack.patchorder.applied[:options.number] else: raise common.CmdException('There are not that many applied patches') elif options.all: patches = stack.patchorder.applied else: patches = stack.patchorder.applied[:1] if not patches: raise common.CmdException('No patches to commit') iw = stack.repository.default_iw def allow_conflicts(trans): # As long as the topmost patch stays where it is, it's OK to # run "stg commit" with conflicts in the index. return len(trans.applied) >= 1 trans = transaction.StackTransaction(stack, 'commit', allow_conflicts = allow_conflicts) try: common_prefix = 0 for i in range(min(len(stack.patchorder.applied), len(patches))): if stack.patchorder.applied[i] == patches[i]: common_prefix += 1 else: break if common_prefix < len(patches): to_push = [pn for pn in stack.patchorder.applied[common_prefix:] if pn not in patches[common_prefix:]] # this pops all the applied patches from common_prefix trans.pop_patches(lambda pn: pn in to_push) for pn in patches[common_prefix:]: trans.push_patch(pn, iw) else: to_push = [] new_base = trans.patches[patches[-1]] for pn in patches: trans.patches[pn] = None trans.applied = [pn for pn in trans.applied if pn not in patches] trans.base = new_base out.info('Committed %d patch%s' % (len(patches), ['es', ''][len(patches) == 1])) for pn in to_push: trans.push_patch(pn, iw) except transaction.TransactionHalted: pass return trans.run(iw) stgit-0.19/stgit/commands/common.py000066400000000000000000000505421337022307200173770ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Function/variables common to all the commands""" from __future__ import (absolute_import, division, print_function, unicode_literals) import email.utils import os import re import sys from stgit import stack, git, templates from stgit.compat import text, decode_utf8_with_latin1 from stgit.config import config from stgit.exception import StgException from stgit.lib import git as libgit from stgit.lib import log from stgit.lib import stack as libstack from stgit.out import out from stgit.run import Run, RunException from stgit.utils import (EditorException, add_sign_line, edit_string, get_hook, parse_name_email_date, run_hook_on_string, strip_prefix) __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ # Command exception class class CmdException(StgException): pass # Utility functions def parse_rev(rev): """Parse a revision specification into its branch:patch parts. """ try: branch, patch = rev.split(':', 1) except ValueError: branch = None patch = rev return (branch, patch) def git_id(crt_series, rev): """Return the GIT id """ # TODO: remove this function once all the occurrences were converted # to git_commit() repository = libstack.Repository.default() return git_commit(rev, repository, crt_series.get_name()).sha1 def get_public_ref(branch_name): """Return the public ref of the branch.""" public_ref = config.get('branch.%s.public' % branch_name) if not public_ref: public_ref = 'refs/heads/%s.public' % branch_name return public_ref def git_commit(name, repository, branch_name = None): """Return the a Commit object if 'name' is a patch name or Git commit. The patch names allowed are in the form ':' and can be followed by standard symbols used by git rev-parse. If is '{base}', it represents the bottom of the stack. If is {public}, it represents the public branch corresponding to the stack as described in the 'publish' command. """ # Try a [branch:]patch name first branch, patch = parse_rev(name) if not branch: branch = branch_name or repository.current_branch_name # The stack base if patch.startswith('{base}'): base_id = repository.get_stack(branch).base.sha1 return repository.rev_parse(base_id + strip_prefix('{base}', patch)) elif patch.startswith('{public}'): public_ref = get_public_ref(branch) return repository.rev_parse(public_ref + strip_prefix('{public}', patch), discard_stderr = True) # Other combination of branch and patch try: return repository.rev_parse('patches/%s/%s' % (branch, patch), discard_stderr = True) except libgit.RepositoryException: pass # Try a Git commit try: return repository.rev_parse(name, discard_stderr = True) except libgit.RepositoryException: raise CmdException('%s: Unknown patch or revision name' % name) def color_diff_flags(): """Return the git flags for coloured diff output if the configuration and stdout allows.""" stdout_is_tty = (sys.stdout.isatty() and 'true') or 'false' if config.get_colorbool('color.diff', stdout_is_tty) == 'true': return ['--color'] else: return [] def check_local_changes(): if git.local_changes(): raise CmdException('local changes in the tree. Use "refresh" or' ' "reset --hard"') def check_head_top_equal(crt_series): if not crt_series.head_top_equal(): raise CmdException('HEAD and top are not the same. This can happen' ' if you modify a branch with git. "stg repair' ' --help" explains more about what to do next.') def check_conflicts(): if git.get_conflicts(): raise CmdException('Unsolved conflicts. Please fix the conflicts' ' then use "git add --update " or revert the' ' changes with "reset --hard".') def print_crt_patch(crt_series, branch = None): if not branch: patch = crt_series.get_current() else: patch = stack.Series(branch).get_current() if patch: out.info('Now at patch "%s"' % patch) else: out.info('No patches applied') def push_patches(crt_series, patches, check_merged = False): """Push multiple patches onto the stack. This function is shared between the push and pull commands """ forwarded = crt_series.forward_patches(patches) if forwarded > 1: out.info('Fast-forwarded patches "%s" - "%s"' % (patches[0], patches[forwarded - 1])) elif forwarded == 1: out.info('Fast-forwarded patch "%s"' % patches[0]) names = patches[forwarded:] # check for patches merged upstream if names and check_merged: out.start('Checking for patches merged upstream') merged = crt_series.merged_patches(names) out.done('%d found' % len(merged)) else: merged = [] for p in names: out.start('Pushing patch "%s"' % p) if p in merged: crt_series.push_empty_patch(p) out.done('merged upstream') else: modified = crt_series.push_patch(p) if crt_series.empty_patch(p): out.done('empty patch') elif modified: out.done('modified') else: out.done() def pop_patches(crt_series, patches, keep = False): """Pop the patches in the list from the stack. It is assumed that the patches are listed in the stack reverse order. """ if len(patches) == 0: out.info('Nothing to push/pop') else: p = patches[-1] if len(patches) == 1: out.start('Popping patch "%s"' % p) else: out.start('Popping patches "%s" - "%s"' % (patches[0], p)) crt_series.pop_patch(p, keep) out.done() def get_patch_from_list(part_name, patch_list): candidates = [full for full in patch_list if part_name in full] if len(candidates) >= 2: out.info('Possible patches:\n %s' % '\n '.join(candidates)) raise CmdException('Ambiguous patch name "%s"' % part_name) elif len(candidates) == 1: return candidates[0] else: return None def parse_patches(patch_args, patch_list, boundary = 0, ordered = False): """Parse patch_args list for patch names in patch_list and return a list. The names can be individual patches and/or in the patch1..patch2 format. """ # in case it receives a tuple patch_list = list(patch_list) patches = [] for name in patch_args: pair = name.split('..') for p in pair: if p and p not in patch_list: raise CmdException('Unknown patch name: %s' % p) if len(pair) == 1: # single patch name pl = pair elif len(pair) == 2: # patch range [p1]..[p2] # inclusive boundary if pair[0]: first = patch_list.index(pair[0]) else: first = -1 # exclusive boundary if pair[1]: last = patch_list.index(pair[1]) + 1 else: last = -1 # only cross the boundary if explicitly asked if not boundary: boundary = len(patch_list) if first < 0: if last <= boundary: first = 0 else: first = boundary if last < 0: if first < boundary: last = boundary else: last = len(patch_list) if last > first: pl = patch_list[first:last] else: pl = patch_list[(last - 1):(first + 1)] pl.reverse() else: raise CmdException('Malformed patch name: %s' % name) for p in pl: if p in patches: raise CmdException('Duplicate patch name: %s' % p) patches += pl if ordered: patches = [p for p in patch_list if p in patches] return patches def name_email(address): p = email.utils.parseaddr(address) if p[1]: return p else: raise CmdException('Incorrect "name "/"email (name)" string: %s' % address) def name_email_date(address): p = parse_name_email_date(address) if p: return p else: raise CmdException('Incorrect "name date" string: %s' % address) def address_or_alias(addr_pair): """Return a name-email tuple the e-mail address is valid or look up the aliases in the config files. """ addr = addr_pair[1] if '@' in addr: # it's an e-mail address return addr_pair alias = config.get('mail.alias.' + addr) if alias: # it's an alias return name_email(alias) raise CmdException('unknown e-mail alias: %s' % addr) def prepare_rebase(crt_series): # pop all patches applied = crt_series.get_applied() if len(applied) > 0: out.start('Popping all applied patches') crt_series.pop_patch(applied[0]) out.done() return applied def rebase(crt_series, target): try: tree_id = git_id(crt_series, target) except: # it might be that we use a custom rebase command with its own # target type tree_id = target if target: out.start('Rebasing to "%s"' % target) else: out.start('Rebasing to the default target') git.rebase(tree_id = tree_id) out.done() def post_rebase(crt_series, applied, nopush, merged): # memorize that we rebased to here crt_series._set_field('orig-base', git.get_head()) # push the patches back if not nopush: push_patches(crt_series, applied, merged) # # Patch description/e-mail/diff parsing # def __end_descr(line): return (re.match(br'---\s*$', line) or re.match(b'diff -', line) or re.match(b'Index: ', line) or re.match(br'--- \w', line)) def __split_descr_diff(string): """Return the description and the diff from the given string """ descr = diff = b'' top = True for line in string.split(b'\n'): if top: if not __end_descr(line): descr += line + b'\n' continue else: top = False diff += line + b'\n' return (descr.rstrip(), diff) def __parse_description(descr): """Parse the patch description and return the new description and author information (if any). """ subject = body = '' authname = authemail = authdate = None descr_lines = [line.rstrip() for line in descr.split('\n')] if not descr_lines: raise CmdException("Empty patch description") lasthdr = 0 end = len(descr_lines) descr_strip = 0 # Parse the patch header for pos in range(0, end): if not descr_lines[pos]: continue # check for a "From|Author:" line if re.match(r'\s*(?:from|author):\s+', descr_lines[pos], re.I): auth = re.findall(r'^.*?:\s+(.*)$', descr_lines[pos])[0] authname, authemail = name_email(auth) lasthdr = pos + 1 continue # check for a "Date:" line if re.match(r'\s*date:\s+', descr_lines[pos], re.I): authdate = re.findall(r'^.*?:\s+(.*)$', descr_lines[pos])[0] lasthdr = pos + 1 continue if subject: break # get the subject subject = descr_lines[pos][descr_strip:] if re.match(r'commit [\da-f]{40}$', subject): # 'git show' output, look for the real subject subject = '' descr_strip = 4 lasthdr = pos + 1 # get the body if lasthdr < end: body = '\n' + '\n'.join(l[descr_strip:] for l in descr_lines[lasthdr:]) return (subject + body, authname, authemail, authdate) def parse_mail(msg): """Parse the message object and return (description, authname, authemail, authdate, diff) """ import email.header if sys.version_info[0] <= 2: # Python 2's decode_header() fails to decode encoded words if they are # quoted. This does not match the behavior of Python3 or `git mailinfo`. # For example, Python2 does not handle this header correctly: # # From: "=?UTF-8?q?Christian=20K=C3=B6nig?=" # # By replacing the encoded words regex in the email.header module, we can # bless Python2 with the same behavior as Python3. email.header.ecre = re.compile( (r'=\? (?P[^?]*?)' r' \? (?P[QqBb])' r' \? (?P.*?)' r' \?='), re.VERBOSE | re.MULTILINE) def __decode_header(header): """Decode a qp-encoded e-mail header as per rfc2047""" try: decoded_words = email.header.decode_header(header) return text(email.header.make_header(decoded_words)) except Exception as ex: raise CmdException('header decoding error: %s' % str(ex)) # parse the headers if 'from' in msg: authname, authemail = name_email(__decode_header(msg['from'])) else: authname = authemail = None # '\n\t' can be found on multi-line headers descr = __decode_header(msg['subject']) descr = re.sub('\n[ \t]*', ' ', descr) authdate = msg['date'] # remove the '[*PATCH*]' expression in the subject if descr: descr = re.findall(r'^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$', descr)[0][1] else: raise CmdException('Subject: line not found') # the rest of the message msg_data = b'' for part in msg.walk(): if part.get_content_type() in ['text/plain', 'application/octet-stream']: payload = part.get_payload(decode=True) msg_data += payload rem_descr, diff = __split_descr_diff(msg_data) if rem_descr: descr += '\n\n' + decode_utf8_with_latin1(rem_descr) # parse the description for author information descr, descr_authname, descr_authemail, descr_authdate = \ __parse_description(descr) if descr_authname: authname = descr_authname if descr_authemail: authemail = descr_authemail if descr_authdate: authdate = descr_authdate return (descr, authname, authemail, authdate, diff) def parse_patch(patch_data, contains_diff): """Parse patch data. Returns (description, authname, authemail, authdate, diff) """ assert isinstance(patch_data, bytes) if contains_diff: (descr, diff) = __split_descr_diff(patch_data) else: descr = patch_data diff = None (descr, authname, authemail, authdate) = __parse_description( decode_utf8_with_latin1(descr)) # we don't yet have an agreed place for the creation date. # Just return None return (descr, authname, authemail, authdate, diff) def readonly_constant_property(f): """Decorator that converts a function that computes a value to an attribute that returns the value. The value is computed only once, the first time it is accessed.""" def new_f(self): n = '__' + f.__name__ if not hasattr(self, n): setattr(self, n, f(self)) return getattr(self, n) return property(new_f) def run_commit_msg_hook(repo, cd, editor_is_used=True): """Run the commit-msg hook (if any) on a commit. @param cd: The L{CommitData} to run the hook on. Return the new L{CommitData}.""" env = dict(cd.env) if not editor_is_used: env['GIT_EDITOR'] = ':' commit_msg_hook = get_hook(repo, 'commit-msg', env) try: new_msg = run_hook_on_string(commit_msg_hook, cd.message) except RunException as exc: raise EditorException(str(exc)) return cd.set_message(new_msg) def update_commit_data(cd, options): """Return a new CommitData object updated according to the command line options.""" # Set the commit message from commandline. if options.message is not None: cd = cd.set_message(options.message) # Modify author data. cd = cd.set_author(options.author(cd.author)) # Add Signed-off-by: or similar. if options.sign_str is not None: sign_str = options.sign_str else: sign_str = config.get("stgit.autosign") if sign_str is not None: cd = cd.set_message( add_sign_line(cd.message, sign_str, cd.committer.name, cd.committer.email)) # Let user edit the commit message manually, unless # --save-template or --message was specified. if not getattr(options, 'save_template', None) and options.message is None: tmpl = templates.get_template('patchdescr.tmpl') if tmpl: cd = cd.set_message(cd.message + tmpl) cd = cd.set_message(edit_string(cd.message, '.stgit-new.txt')) return cd class DirectoryException(StgException): pass class _Directory(object): def __init__(self, needs_current_series = True, log = True): self.needs_current_series = needs_current_series self.log = log @readonly_constant_property def git_dir(self): try: return Run('git', 'rev-parse', '--git-dir' ).discard_stderr().output_one_line() except RunException: raise DirectoryException('No git repository found') @readonly_constant_property def __topdir_path(self): try: lines = Run('git', 'rev-parse', '--show-cdup' ).discard_stderr().output_lines() if len(lines) == 0: return '.' elif len(lines) == 1: return lines[0] else: raise RunException('Too much output') except RunException: raise DirectoryException('No git repository found') @readonly_constant_property def is_inside_git_dir(self): return { 'true': True, 'false': False }[Run('git', 'rev-parse', '--is-inside-git-dir' ).output_one_line()] @readonly_constant_property def is_inside_worktree(self): return { 'true': True, 'false': False }[Run('git', 'rev-parse', '--is-inside-work-tree' ).output_one_line()] def cd_to_topdir(self): os.chdir(self.__topdir_path) def write_log(self, msg): if self.log: log.compat_log_entry(msg) class DirectoryAnywhere(_Directory): def setup(self): pass class DirectoryHasRepository(_Directory): def setup(self): self.git_dir # might throw an exception log.compat_log_external_mods() class DirectoryInWorktree(DirectoryHasRepository): def setup(self): DirectoryHasRepository.setup(self) if not self.is_inside_worktree: raise DirectoryException('Not inside a git worktree') class DirectoryGotoToplevel(DirectoryInWorktree): def setup(self): DirectoryInWorktree.setup(self) self.cd_to_topdir() class DirectoryHasRepositoryLib(_Directory): """For commands that use the new infrastructure in stgit.lib.*.""" def __init__(self): self.needs_current_series = False self.log = False # stgit.lib.transaction handles logging def setup(self): # This will throw an exception if we don't have a repository. self.repository = libstack.Repository.default() stgit-0.19/stgit/commands/delete.py000066400000000000000000000067071337022307200173550ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Delete patches' kind = 'patch' usage = ['[options] [--] [] [..]'] description = """ Delete the patches passed as arguments.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches)] options = [ opt('--spill', action = 'store_true', short = 'Spill patch contents to worktree and index', long = """ Delete the patches, but do not touch the index and worktree. This only works with applied patches at the top of the stack. The effect is to "spill" the patch contents into the index and worktree. This can be useful e.g. if you want to split a patch into several smaller pieces."""), opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch'), opt('-t', '--top', action = 'store_true', short = 'Delete top patch'),] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Delete one or more patches.""" stack = directory.repository.get_stack(options.branch) if options.branch: iw = None # can't use index/workdir to manipulate another branch else: iw = stack.repository.default_iw if args and options.top: parser.error('Either --top or patches must be specified') elif args: patches = set(common.parse_patches(args, list(stack.patchorder.all), len(stack.patchorder.applied))) elif options.top: applied = stack.patchorder.applied if applied: patches = set([applied[-1]]) else: raise common.CmdException('No patches applied') else: parser.error('No patches specified') if options.spill: if set(stack.patchorder.applied[-len(patches):]) != patches: parser.error('Can only spill topmost applied patches') iw = None # don't touch index+worktree def allow_conflicts(trans): # Allow conflicts if the topmost patch stays the same. if stack.patchorder.applied: return (trans.applied and trans.applied[-1] == stack.patchorder.applied[-1]) else: return not trans.applied trans = transaction.StackTransaction(stack, 'delete', allow_conflicts = allow_conflicts) try: to_push = trans.delete_patches(lambda pn: pn in patches) for pn in to_push: trans.push_patch(pn, iw) except transaction.TransactionHalted: pass return trans.run(iw) stgit-0.19/stgit/commands/diff.py000066400000000000000000000055571337022307200170250ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, git from stgit.argparse import opt from stgit.commands.common import (DirectoryHasRepository, color_diff_flags, git_id) from stgit.lib import git as gitlib from stgit.out import out from stgit.pager import pager __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Show the tree diff' kind = 'wc' usage = ['[options] [--] []'] description = """ Show the diff (default) or diffstat between the current working copy or a tree-ish object and another tree-ish object (defaulting to HEAD). File names can also be given to restrict the diff output. The tree-ish object has the format accepted by the linkstg:id[] command.""" args = [argparse.known_files, argparse.dirty_files] options = [ opt('-r', '--range', metavar = 'rev1[..[rev2]]', dest = 'revs', args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches)], short = 'Show the diff between revisions'), opt('-s', '--stat', action = 'store_true', short = 'Show the stat instead of the diff'), ] + argparse.diff_opts_option() directory = DirectoryHasRepository(log=False) crt_series = None def func(parser, options, args): """Show the tree diff """ args = git.ls_files(args) directory.cd_to_topdir() if options.revs: rev_list = options.revs.split('..') rev_list_len = len(rev_list) if rev_list_len == 1: rev1 = rev_list[0] rev2 = None elif rev_list_len == 2: rev1 = rev_list[0] rev2 = rev_list[1] else: parser.error('incorrect parameters to -r') else: rev1 = 'HEAD' rev2 = None if not options.stat: options.diff_flags.extend(color_diff_flags()) diff = git.diff(args, rev1 and git_id(crt_series, rev1), rev2 and git_id(crt_series, rev2), diff_flags = options.diff_flags) if options.stat: out.stdout_raw(gitlib.diffstat(diff) + '\n') elif diff: pager(diff) stgit-0.19/stgit/commands/edit.py000066400000000000000000000144411337022307200170320ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Patch editing command""" from __future__ import (absolute_import, division, print_function, unicode_literals) import io from stgit import argparse, utils from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction, edit from stgit.out import out __copyright__ = """ Copyright (C) 2007, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Edit a patch description or diff' kind = 'patch' usage = ['[options] [--] []'] description = """ Edit the description and author information of the given patch (or the current patch if no patch name was given). With --diff, also edit the diff. The editor is invoked with the following contents: From: A U Thor Date: creation date Patch description If --diff was specified, the diff appears at the bottom, after a separator: --- Diff text Command-line options can be used to modify specific information without invoking the editor. (With the --edit option, the editor is invoked even if such command-line options are given.) If the patch diff is edited but does not apply, no changes are made to the patch at all. The edited patch is saved to a file which you can feed to "stg edit --file", once you have made sure it does apply. With --set-tree you set the git tree of the patch to the specified TREE-ISH without changing the tree of any other patches. When used on the top patch, the index and work tree will be updated to match the tree. This low-level option is primarily meant to be used by tools built on top of StGit, such as the Emacs mode. See also the --set-tree flag of stg push.""" args = [argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches] options = ( [ opt('-d', '--diff', action = 'store_true', short = 'Edit the patch diff'), opt('-e', '--edit', action = 'store_true', short = 'Invoke interactive editor') ] + argparse.sign_options() + argparse.message_options(save_template = True) + argparse.hook_options() + argparse.author_options() + argparse.diff_opts_option() + [ opt('-t', '--set-tree', action = 'store', metavar = 'TREE-ISH', short = 'Set the git tree of the patch to TREE-ISH') ]) directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Edit the given patch or the current one. """ stack = directory.repository.current_stack if len(args) == 0: if not stack.patchorder.applied: raise common.CmdException( 'Cannot edit top patch, because no patches are applied') patchname = stack.patchorder.applied[-1] elif len(args) == 1: [patchname] = args if not stack.patches.exists(patchname): raise common.CmdException('%s: no such patch' % patchname) else: parser.error('Cannot edit more than one patch') cd = orig_cd = stack.patches.get(patchname).commit.data if options.set_tree: cd = cd.set_tree(stack.repository.rev_parse( options.set_tree, discard_stderr = True, object_type = 'tree')) cd, failed_diff = edit.auto_edit_patch( stack.repository, cd, msg=(None if options.message is None else options.message.encode('utf-8')), contains_diff=True, author=options.author, committer=lambda p: p, sign_str=options.sign_str) if options.save_template: options.save_template( edit.patch_desc(stack.repository, cd, options.diff, options.diff_flags, failed_diff)) return utils.STGIT_SUCCESS use_editor = cd == orig_cd or options.edit if use_editor: cd, failed_diff = edit.interactive_edit_patch( stack.repository, cd, options.diff, options.diff_flags, failed_diff) def failed(reason='Edited patch did not apply.'): fn = '.stgit-failed.patch' with io.open(fn, 'wb') as f: f.write(edit.patch_desc(stack.repository, cd, options.diff, options.diff_flags, failed_diff)) out.error(reason, 'The patch has been saved to "%s".' % fn) return utils.STGIT_COMMAND_ERROR # If we couldn't apply the patch, fail without even trying to # effect any of the changes. if failed_diff: return failed() if not options.no_verify and (use_editor or cd.message != orig_cd.message): try: cd = common.run_commit_msg_hook(stack.repository, cd, use_editor) except Exception: if options.diff: failed('The commit-msg hook failed.') raise # The patch applied, so now we have to rewrite the StGit patch # (and any patches on top of it). iw = stack.repository.default_iw trans = transaction.StackTransaction(stack, 'edit', allow_conflicts = True) if patchname in trans.applied: popped = trans.applied[trans.applied.index(patchname)+1:] assert not trans.pop_patches(lambda pn: pn in popped) else: popped = [] trans.patches[patchname] = stack.repository.commit(cd) try: for pn in popped: if options.set_tree: trans.push_tree(pn) else: trans.push_patch(pn, iw, allow_interactive = True) except transaction.TransactionHalted: pass try: # Either a complete success, or a conflict during push. But in # either case, we've successfully effected the edits the user # asked us for. return trans.run(iw) except transaction.TransactionException: # Transaction aborted -- we couldn't check out files due to # dirty index/worktree. The edits were not carried out. return failed() stgit-0.19/stgit/commands/export.py000066400000000000000000000146571337022307200174370ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Export command""" from __future__ import (absolute_import, division, print_function, unicode_literals) import io import os import sys from stgit import argparse, git, templates from stgit.argparse import opt from stgit.commands import common from stgit.lib import git as gitlib from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Export patches to a directory' kind = 'patch' usage = ['[options] [--] [] [] [..]'] description = """ Export a range of applied patches to a given directory (defaults to 'patches-') in a standard unified GNU diff format. A template file (defaulting to '.git/patchexport.tmpl' or '~/.stgit/templates/patchexport.tmpl' or '/usr/share/stgit/templates/patchexport.tmpl') can be used for the patch format. The following variables are supported in the template file: %(description)s - patch description %(shortdescr)s - the first line of the patch description %(longdescr)s - the rest of the patch description, after the first line %(diffstat)s - the diff statistics %(authname)s - author's name %(authemail)s - author's e-mail %(authdate)s - patch creation date %(commname)s - committer's name %(commemail)s - committer's e-mail""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches)] options = [ opt('-d', '--dir', args = [argparse.dir], short = 'Export patches to DIR instead of the default'), opt('-p', '--patch', action = 'store_true', short = 'Append .patch to the patch names'), opt('-e', '--extension', short = 'Append .EXTENSION to the patch names'), opt('-n', '--numbered', action = 'store_true', short = 'Prefix the patch names with order numbers'), opt('-t', '--template', metavar = 'FILE', args = [argparse.files], short = 'Use FILE as a template'), opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch'), opt('-s', '--stdout', action = 'store_true', short = 'Dump the patches to the standard output'), ] + argparse.diff_opts_option() directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Export a range of patches. """ stack = directory.repository.get_stack(options.branch) if options.dir: dirname = options.dir else: dirname = 'patches-%s' % stack.name directory.cd_to_topdir() if not options.branch and git.local_changes(): out.warn('Local changes in the tree;' ' you might want to commit them first') applied = stack.patchorder.applied unapplied = stack.patchorder.unapplied if len(args) != 0: patches = common.parse_patches(args, applied + unapplied, len(applied)) else: patches = applied num = len(patches) if num == 0: raise common.CmdException('No patches applied') zpadding = len(str(num)) if zpadding < 2: zpadding = 2 # get the template if options.template: with io.open(options.template, 'r') as f: tmpl = f.read() else: tmpl = templates.get_template('patchexport.tmpl') if not tmpl: tmpl = '' if not options.stdout: if not os.path.isdir(dirname): os.makedirs(dirname) series = io.open(os.path.join(dirname, 'series'), 'w') # note the base commit for this series base_commit = stack.base.sha1 print('# This series applies on GIT commit %s' % base_commit, file=series) for patch_no, p in enumerate(patches, 1): pname = p if options.patch: pname = '%s.patch' % pname elif options.extension: pname = '%s.%s' % (pname, options.extension) if options.numbered: pname = '%s-%s' % (str(patch_no).zfill(zpadding), pname) pfile = os.path.join(dirname, pname) if not options.stdout: print(pname, file=series) # get the patch description patch = stack.patches.get(p) cd = patch.commit.data descr = cd.message.strip() descr_lines = descr.split('\n') short_descr = descr_lines[0].rstrip() long_descr = '\n'.join(descr_lines[1:]).strip() diff = stack.repository.diff_tree(cd.parent.data.tree, cd.tree, options.diff_flags) tmpl_dict = {'description': descr, 'shortdescr': short_descr, 'longdescr': long_descr, 'diffstat': gitlib.diffstat(diff).rstrip(), 'authname': cd.author.name, 'authemail': cd.author.email, 'authdate': cd.author.date.isoformat(), 'commname': cd.committer.name, 'commemail': cd.committer.email} try: descr = templates.specialize_template(tmpl, tmpl_dict) except KeyError as err: raise common.CmdException('Unknown patch template variable: %s' % err) except TypeError: raise common.CmdException('Only "%(name)s" variables are ' 'supported in the patch template') if options.stdout: if hasattr(sys.stdout, 'buffer'): f = sys.stdout.buffer else: f = sys.stdout else: f = io.open(pfile, 'wb') if options.stdout and num > 1: f.write('\n'.join(['-' * 79, patch.name, '-' * 79, '']).encode('utf-8')) f.write(descr) f.write(diff) if not options.stdout: f.close() if not options.stdout: series.close() stgit-0.19/stgit/commands/files.py000066400000000000000000000051021337022307200172010ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, git from stgit.argparse import opt from stgit.commands.common import DirectoryHasRepository, git_id from stgit.lib import git as gitlib from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Show the files modified by a patch (or the current patch)' kind = 'patch' usage = ['[options] [--] [[:]]'] description = """ List the files modified by the given patch (defaulting to the current one). Passing the '--stat' option shows the diff statistics for the given patch. Note that this command doesn't show the files modified in the working tree and not yet included in the patch by a 'refresh' command. Use the 'diff' or 'status' commands for these files.""" args = [argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches] options = [ opt('-s', '--stat', action = 'store_true', short = 'Show the diffstat'), opt('--bare', action = 'store_true', short = 'Bare file names (useful for scripting)'), ] + argparse.diff_opts_option() directory = DirectoryHasRepository(log=False) crt_series = None def func(parser, options, args): """Show the files modified by a patch (or the current patch) """ if len(args) == 0: patch = 'HEAD' elif len(args) == 1: patch = args[0] else: parser.error('incorrect number of arguments') rev1 = git_id(crt_series, '%s^' % patch) rev2 = git_id(crt_series, '%s' % patch) if options.stat: output = gitlib.diffstat(git.diff(rev1 = rev1, rev2 = rev2, diff_flags = options.diff_flags)) elif options.bare: output = git.barefiles(rev1, rev2) else: output = git.files(rev1, rev2, diff_flags = options.diff_flags) if output: if not output.endswith('\n'): output += '\n' out.stdout_raw(output) stgit-0.19/stgit/commands/float.py000066400000000000000000000057111337022307200172120ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import io import re import sys from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction __copyright__ = """ Copyright (C) 2006, Robin Rosenberg Modified by Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Push patches to the top, even if applied' kind = 'stack' usage = ['[--] ', '-s '] description = """ Push a patch or a range of patches to the top even if applied. The necessary pop and push operations will be performed to accomplish this. The '--series' option can be used to rearrange the (top) patches as specified by the given series file (or the standard input).""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches)] options = [ opt('-s', '--series', metavar = 'FILE', short = 'Rearrange according to the series FILE') ] + argparse.keep_option() directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Reorder patches to make the named patch the topmost one. """ if options.series and args: parser.error(' cannot be used with --series') elif not options.series and not args: parser.error('incorrect number of arguments') stack = directory.repository.current_stack if options.series: if options.series == '-': f = io.open(sys.stdin.fileno()) else: f = io.open(options.series) patches = [] for line in f: patch = re.sub('#.*$', '', line).strip() if patch: patches.append(patch) else: patches = common.parse_patches(args, stack.patchorder.all) if not patches: raise common.CmdException('No patches to float') applied = [p for p in stack.patchorder.applied if p not in patches] + \ patches unapplied = [p for p in stack.patchorder.unapplied if p not in patches] iw = stack.repository.default_iw clean_iw = (not options.keep and iw) or None trans = transaction.StackTransaction(stack, 'float', check_clean_iw = clean_iw) try: trans.reorder_patches(applied, unapplied, iw = iw) except transaction.TransactionHalted: pass return trans.run(iw) stgit-0.19/stgit/commands/fold.py000066400000000000000000000067451337022307200170410ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os from stgit import argparse, git from stgit.argparse import opt from stgit.commands.common import (CmdException, DirectoryHasRepository, check_local_changes, check_conflicts, check_head_top_equal, git_id) from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Integrate a GNU diff patch into the current patch' kind = 'patch' usage = ['[options] [--] []'] description = """ Apply the given GNU diff file (or the standard input) onto the top of the current patch. With the '--threeway' option, the patch is applied onto the bottom of the current patch and a three-way merge is performed with the current top. With the --base option, the patch is applied onto the specified base and a three-way merged is performed with the current top.""" args = [argparse.files] options = [ opt('-t', '--threeway', action = 'store_true', short = 'Perform a three-way merge with the current patch'), opt('-b', '--base', args = [argparse.commit], short = 'Use BASE instead of HEAD when applying the patch'), opt('-p', '--strip', type = 'int', metavar = 'N', short = 'Remove N leading slashes from diff paths (default 1)'), opt('--reject', action = 'store_true', short = 'Leave the rejected hunks in corresponding *.rej files')] directory = DirectoryHasRepository(log=True) crt_series = None def func(parser, options, args): """Integrate a GNU diff patch into the current patch """ if len(args) > 1: parser.error('incorrect number of arguments') check_local_changes() check_conflicts() check_head_top_equal(crt_series) if len(args) == 1: filename = args[0] else: filename = None current = crt_series.get_current() if not current: raise CmdException('No patches applied') if filename: if os.path.exists(filename): out.start('Folding patch "%s"' % filename) else: raise CmdException('No such file: %s' % filename) else: out.start('Folding patch from stdin') if options.threeway: crt_patch = crt_series.get_patch(current) bottom = crt_patch.get_bottom() git.apply_patch(filename = filename, base = bottom, strip = options.strip, reject = options.reject) elif options.base: git.apply_patch(filename = filename, reject = options.reject, strip = options.strip, base = git_id(crt_series, options.base)) else: git.apply_patch(filename = filename, strip = options.strip, reject = options.reject) out.done() stgit-0.19/stgit/commands/goto.py000066400000000000000000000051111337022307200170470ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.commands import common from stgit.lib import transaction __copyright__ = """ Copyright (C) 2006, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Push or pop patches to the given one' kind = 'stack' usage = ['[options] [--] '] description = """ Push/pop patches to/from the stack until the one given on the command line becomes current.""" args = [argparse.other_applied_patches, argparse.unapplied_patches] options = argparse.keep_option() + argparse.merged_option() directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): if len(args) != 1: parser.error('incorrect number of arguments') patch = args[0] stack = directory.repository.current_stack iw = stack.repository.default_iw clean_iw = (not options.keep and iw) or None trans = transaction.StackTransaction(stack, 'goto', check_clean_iw = clean_iw) if patch not in trans.all_patches: candidate = common.get_patch_from_list(patch, trans.all_patches) if candidate is None: raise common.CmdException('Patch "%s" does not exist' % patch) patch = candidate if patch in trans.applied: to_pop = set(trans.applied[trans.applied.index(patch)+1:]) assert not trans.pop_patches(lambda pn: pn in to_pop) elif patch in trans.unapplied: try: to_push = trans.unapplied[:trans.unapplied.index(patch)+1] if options.merged: merged = set(trans.check_merged(to_push)) else: merged = set() for pn in to_push: trans.push_patch(pn, iw, allow_interactive = True, already_merged = pn in merged) except transaction.TransactionHalted: pass else: raise common.CmdException('Cannot goto a hidden patch') return trans.run(iw) stgit-0.19/stgit/commands/hide.py000066400000000000000000000041441337022307200170150ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.commands import common from stgit.lib import transaction from stgit.out import out __copyright__ = """ Copyright (C) 2009, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Hide a patch in the series' kind = 'stack' usage = ['[options] [--] '] description = """ Hide a range of unapplied patches so that they are no longer shown in the plain 'series' command output.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches)] options = [ argparse.opt('-b', '--branch', args=[argparse.stg_branches], short='Use BRANCH instead of the default branch')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Hide a range of patch in the series.""" stack = directory.repository.current_stack trans = transaction.StackTransaction(stack, 'hide') if not args: parser.error('No patches specified') patches = common.parse_patches(args, trans.all_patches) for p in patches: if p in trans.hidden: out.warn('Patch "%s" already hidden' % p) patches = [p for p in patches if p not in set(trans.hidden)] applied = [p for p in trans.applied if p not in set(patches)] unapplied = [p for p in trans.unapplied if p not in set(patches)] hidden = patches + trans.hidden trans.reorder_patches(applied, unapplied, hidden) return trans.run() stgit-0.19/stgit/commands/id.py000066400000000000000000000036111337022307200164760ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.commands import common from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Print the git hash value of a StGit reference' kind = 'repo' usage = ['[options] [--] []'] description = r""" Print the SHA1 value of a Git id (defaulting to HEAD). In addition to the standard Git id's like heads and tags, this command also accepts '[:]' for the id of a patch, '[:]\{base\}' for the base of the stack and '[:]\{public\}' for the public branch corresponding to the stack (see the 'publish' command for details). If no branch is specified, it defaults to the current one. The bottom of a patch is accessible with the '[:]^' format.""" args = [argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches] options = [] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Show the applied patches """ if len(args) == 0: id_str = 'HEAD' elif len(args) == 1: id_str = args[0] else: parser.error('incorrect number of arguments') out.stdout(common.git_commit(id_str, directory.repository).sha1) stgit-0.19/stgit/commands/imprt.py000066400000000000000000000312001337022307200172300ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from contextlib import closing import bz2 import gzip import mailbox import os import re import sys import tarfile from stgit import argparse, git from stgit.argparse import opt from stgit.compat import message_from_binary_file, text from stgit.config import config from stgit.lib import git as gitlib from stgit.out import out from stgit.commands.common import (CmdException, DirectoryHasRepository, check_conflicts, check_head_top_equal, check_local_changes, git_id, parse_mail, parse_patch, print_crt_patch) from stgit.utils import make_patch_name __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ name = 'import' help = 'Import a GNU diff file as a new patch' kind = 'patch' usage = ['[options] [--] [|]'] description = """ Create a new patch and apply the given GNU diff file (or the standard input). By default, the file name is used as the patch name but this can be overridden with the '--name' option. The patch can either be a normal file with the description at the top or it can have standard mail format, the Subject, From and Date headers being used for generating the patch information. The command can also read series and mbox files. If a patch does not apply cleanly, the failed diff is written to the .stgit-failed.patch file and an empty StGIT patch is added to the stack. The patch description has to be separated from the data with a '---' line.""" args = [argparse.files] options = [ opt('-m', '--mail', action = 'store_true', short = 'Import the patch from a standard e-mail file'), opt('-M', '--mbox', action = 'store_true', short = 'Import a series of patches from an mbox file'), opt('-s', '--series', action = 'store_true', short = 'Import a series of patches', long = """ Import a series of patches from a series file or a tar archive."""), opt('-u', '--url', action = 'store_true', short = 'Import a patch from a URL'), opt('-n', '--name', short = 'Use NAME as the patch name'), opt('-p', '--strip', type = 'int', metavar = 'N', short = 'Remove N leading slashes from diff paths (default 1)'), opt('-t', '--stripname', action = 'store_true', short = 'Strip numbering and extension from patch name'), opt('-i', '--ignore', action = 'store_true', short = 'Ignore the applied patches in the series'), opt('--replace', action = 'store_true', short = 'Replace the unapplied patches in the series'), opt('-b', '--base', args = [argparse.commit], short = 'Use BASE instead of HEAD for file importing'), opt('--reject', action = 'store_true', short = 'Leave the rejected hunks in corresponding *.rej files'), opt('-e', '--edit', action = 'store_true', short = 'Invoke an editor for the patch description'), opt('-d', '--showdiff', action = 'store_true', short = 'Show the patch content in the editor buffer'), ] + argparse.author_options() + argparse.sign_options() directory = DirectoryHasRepository(log=True) crt_series = None def __strip_patch_name(name): stripped = re.sub('^[0-9]+-(.*)$', r'\g<1>', name) stripped = re.sub(r'^(.*)\.(diff|patch)$', r'\g<1>', stripped) return stripped def __replace_slashes_with_dashes(name): stripped = name.replace('/', '-') return stripped def __create_patch(filename, message, author_name, author_email, author_date, diff, options): """Create a new patch on the stack """ if options.name: patch = options.name elif filename: patch = os.path.basename(filename) else: patch = '' if options.stripname: patch = __strip_patch_name(patch) if not patch: if options.ignore or options.replace: unacceptable_name = lambda name: False else: unacceptable_name = crt_series.patch_exists patch = make_patch_name(message, unacceptable_name) else: # fix possible invalid characters in the patch name patch = re.sub(r'[^\w.]+', '-', patch).strip('-') if options.ignore and patch in crt_series.get_applied(): out.info('Ignoring already applied patch "%s"' % patch) return if options.replace and patch in crt_series.get_unapplied(): crt_series.delete_patch(patch, keep_log = True) # override the automatically parsed settings author = options.author(gitlib.Person()) if author.name: author_name = author.name if author.email: author_email = author.email if author.date: author_date = text(author.date) sign_str = options.sign_str if not options.sign_str: sign_str = config.get('stgit.autosign') crt_series.new_patch(patch, message = message, can_edit = False, author_name = author_name, author_email = author_email, author_date = author_date, sign_str = sign_str) if not diff: out.warn('No diff found, creating empty patch') else: out.start('Importing patch "%s"' % patch) if options.base: base = git_id(crt_series, options.base) else: base = None try: git.apply_patch(diff = diff, base = base, reject = options.reject, strip = options.strip) except git.GitException: if not options.reject: crt_series.delete_patch(patch) raise crt_series.refresh_patch(edit = options.edit, show_patch = options.showdiff, author_date = author_date, backup = False) out.done() def __mkpatchname(name, suffix): if name.lower().endswith(suffix.lower()): return name[:-len(suffix)] return name def __get_handle_and_name(filename): """Return a file object and a patch name derived from filename """ # see if it's a gzip'ed or bzip2'ed patch for copen, ext in [(gzip.open, '.gz'), (bz2.BZ2File, '.bz2')]: try: f = copen(filename) f.read(1) f.seek(0) return (f, __mkpatchname(filename, ext)) except IOError: pass # plain old file... return (open(filename, 'rb'), filename) def __import_file(filename, options, patch = None): """Import a patch from a file or standard input """ pname = None if filename: (f, pname) = __get_handle_and_name(filename) else: f = os.fdopen(sys.__stdin__.fileno(), 'rb') if patch: pname = patch elif not pname: pname = filename if options.mail: try: msg = message_from_binary_file(f) except Exception as ex: raise CmdException('error parsing the e-mail file: %s' % str(ex)) message, author_name, author_email, author_date, diff = \ parse_mail(msg) else: patch_str = f.read() message, author_name, author_email, author_date, diff = \ parse_patch(patch_str, contains_diff=True) if filename: f.close() __create_patch(pname, message, author_name, author_email, author_date, diff, options) def __import_series(filename, options): """Import a series of patches """ if filename: if tarfile.is_tarfile(filename): __import_tarfile(filename, options) return f = open(filename) patchdir = os.path.dirname(filename) else: f = sys.stdin patchdir = '' for line in f: patch = re.sub('#.*$', '', line).strip() if not patch: continue # Quilt can have "-p0", "-p1" or "-pab" patches stacked in the # series but as strip level default to 1, only "-p0" can actually # be found in the series file, the other ones are implicit m = re.match(r'(?P.*)\s+-p\s*(?P(\d+|ab)?)\s*$', patch) options.strip = 1 if m: patch = m.group('patchfilename') if m.group('striplevel') != '0': raise CmdException("error importing quilt series, patch '%s'" " has unsupported strip level: '-p%s'" % (patch, m.group('striplevel'))) options.strip = 0 patchfile = os.path.join(patchdir, patch) patch = __replace_slashes_with_dashes(patch) __import_file(patchfile, options, patch) if filename: f.close() def __import_mbox(filename, options): """Import a series from an mbox file """ if filename: namedtemp = None else: from tempfile import NamedTemporaryFile stdin = os.fdopen(sys.__stdin__.fileno(), 'rb') namedtemp = NamedTemporaryFile('wb', suffix='.mbox', delete=False) namedtemp.write(stdin.read()) namedtemp.close() filename = namedtemp.name try: try: mbox = mailbox.mbox(filename, message_from_binary_file, create=False) except Exception as ex: raise CmdException('error parsing the mbox file: %s' % str(ex)) with closing(mbox): for msg in mbox: (message, author_name, author_email, author_date, diff) = parse_mail(msg) __create_patch(None, message, author_name, author_email, author_date, diff, options) finally: if namedtemp is not None: os.unlink(namedtemp.name) def __import_url(url, options): """Import a patch from a URL """ try: from urllib.request import urlretrieve from urllib.parse import unquote except ImportError: from urllib import urlretrieve, unquote import tempfile if not url: raise CmdException('URL argument required') patch = os.path.basename(unquote(url)) filename = os.path.join(tempfile.gettempdir(), patch) urlretrieve(url, filename) __import_file(filename, options) def __import_tarfile(tar, options): """Import patch series from a tar archive """ import tempfile import shutil if not tarfile.is_tarfile(tar): raise CmdException("%s is not a tarfile!" % tar) t = tarfile.open(tar, 'r') names = t.getnames() # verify paths in the tarfile are safe for n in names: if n.startswith('/'): raise CmdException("Absolute path found in %s" % tar) if n.find("..") > -1: raise CmdException("Relative path found in %s" % tar) # find the series file seriesfile = '' for m in names: if m.endswith('/series') or m == 'series': seriesfile = m break if seriesfile == '': raise CmdException("no 'series' file found in %s" % tar) # unpack into a tmp dir tmpdir = tempfile.mkdtemp('.stg') t.extractall(tmpdir) # apply the series __import_series(os.path.join(tmpdir, seriesfile), options) # cleanup the tmpdir shutil.rmtree(tmpdir) def func(parser, options, args): """Import a GNU diff file as a new patch """ if len(args) > 1: parser.error('incorrect number of arguments') check_local_changes() check_conflicts() check_head_top_equal(crt_series) if len(args) == 1: filename = args[0] else: filename = None if not options.url and filename: filename = os.path.abspath(filename) directory.cd_to_topdir() if options.series: __import_series(filename, options) elif options.mbox: __import_mbox(filename, options) elif options.url: __import_url(filename, options) else: __import_file(filename, options) print_crt_patch(crt_series) stgit-0.19/stgit/commands/init.py000066400000000000000000000025551337022307200170530ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit.commands import common from stgit.lib import stack __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Initialise the current branch for use with StGIT' kind = 'stack' usage = [''] description = """ Initialise the current git branch to be used as an StGIT stack. The branch (and the git repository it is in) must already exist and contain at least one commit.""" args = [] options = [] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Performs the repository initialisation """ if len(args) != 0: parser.error('incorrect number of arguments') stack.Stack.initialise(directory.repository) stgit-0.19/stgit/commands/log.py000066400000000000000000000071371337022307200166720ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.lib import log from stgit.out import out from stgit.run import Run __copyright__ = """ Copyright (C) 2006, Catalin Marinas Copyright (C) 2008, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Display the patch changelog' kind = 'stack' usage = ['[options] [--] []'] description = """ List the history of the patch stack: the stack log. If one or more patch names are given, limit the list to the log entries that touch the named patches. "stg undo" and "stg redo" let you step back and forth in the patch stack. "stg reset" lets you go directly to any state.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches)] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default one'), opt('-d', '--diff', action = 'store_true', short = 'Show the refresh diffs'), opt('-n', '--number', type = 'int', short = 'Limit the output to NUMBER commits'), opt('-f', '--full', action = 'store_true', short = 'Show the full commit ids'), opt('-g', '--graphical', action = 'store_true', short = 'Run gitk instead of printing'), opt('--clear', action = 'store_true', short = 'Clear the log history')] directory = common.DirectoryHasRepositoryLib() def show_log(stacklog, pathlim, num, full, show_diff): cmd = ['git', 'log'] if num is not None and num > 0: cmd.append('-%d' % num) if show_diff: cmd.append('-p') elif not full: cmd.append('--pretty=format:%h %aD %s') cmd.extend([stacklog.sha1, '--']) cmd.extend(pathlim) Run(*cmd).run() def func(parser, options, args): if options.branch: stack = directory.repository.get_stack(options.branch) else: stack = directory.repository.current_stack patches = common.parse_patches(args, list(stack.patchorder.all)) logref = log.log_ref(stack.name) try: logcommit = stack.repository.refs.get(logref) except KeyError: out.info('Log is empty') return if options.clear: log.delete_log(stack.repository, stack.name) return stacklog = log.get_log_entry(stack.repository, logref, logcommit) pathlim = [os.path.join('patches', pn) for pn in patches] if options.graphical: for o in ['diff', 'number', 'full']: if getattr(options, o): parser.error('cannot combine --graphical and --%s' % o) cmd = ['gitk', stacklog.simplified.sha1, '--'] + pathlim # Discard the exit codes generated by SIGINT, SIGKILL, and SIGTERM. Run(*cmd).returns([0, -2, -9, -15]).run() else: show_log(stacklog.simplified, pathlim, options.number, options.full, options.diff) stgit-0.19/stgit/commands/mail.py000066400000000000000000000647371337022307200170440ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import email import email.charset import email.header import email.utils import getpass import io import os import re import smtplib import socket import time from stgit import argparse, stack, git, version, templates from stgit.argparse import opt from stgit.commands.common import (CmdException, DirectoryHasRepository, address_or_alias, git_id, parse_patches) from stgit.compat import text, message_from_bytes from stgit.config import config from stgit.lib import git as gitlib from stgit.out import out from stgit.run import Run from stgit.utils import edit_bytes __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Send a patch or series of patches by e-mail' kind = 'patch' usage = [' [options] [--] [] [] [..]'] description = r""" Send a patch or a range of patches by e-mail using the SMTP server specified by the 'stgit.smtpserver' configuration option, or the '--smtp-server' command line option. This option can also be an absolute path to 'sendmail' followed by command line arguments. The From address and the e-mail format are generated from the template file passed as argument to '--template' (defaulting to '.git/patchmail.tmpl' or '~/.stgit/templates/patchmail.tmpl' or '/usr/share/stgit/templates/patchmail.tmpl'). A patch can be sent as attachment using the --attach option in which case the 'mailattch.tmpl' template will be used instead of 'patchmail.tmpl'. The To/Cc/Bcc addresses can either be added to the template file or passed via the corresponding command line options. They can be e-mail addresses or aliases which are automatically expanded to the values stored in the [mail "alias"] section of GIT configuration files. A preamble e-mail can be sent using the '--cover' and/or '--edit-cover' options. The first allows the user to specify a file to be used as a template. The latter option will invoke the editor on the specified file (defaulting to '.git/covermail.tmpl' or '~/.stgit/templates/covermail.tmpl' or '/usr/share/stgit/templates/covermail.tmpl'). All the subsequent e-mails appear as replies to the first e-mail sent (either the preamble or the first patch). E-mails can be seen as replies to a different e-mail by using the '--in-reply-to' option. SMTP authentication is also possible with '--smtp-user' and '--smtp-password' options, also available as configuration settings: 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by '--smtp-tls' option and 'smtptls' setting. The following variables are accepted by both the preamble and the patch e-mail templates: %(diffstat)s - diff statistics %(number)s - empty if only one patch is sent or 'patchnr/totalnr' %(snumber)s - stripped version of '%(number)s' %(nspace)s - ' ' if %(number)s is non-empty, otherwise empty string %(patchnr)s - patch number %(sender)s - 'sender' or 'authname ' as per the config file %(totalnr)s - total number of patches to be sent %(version)s - 'version' string passed on the command line (or empty) %(vspace)s - ' ' if %(version)s is non-empty, otherwise empty string In addition to the common variables, the preamble e-mail template accepts the following: %(shortlog)s - first line of each patch description, listed by author In addition to the common variables, the patch e-mail template accepts the following: %(authdate)s - patch creation date %(authemail)s - author's email %(authname)s - author's name %(commemail)s - committer's e-mail %(commname)s - committer's name %(diff)s - unified diff of the patch %(fromauth)s - 'From: author\n\n' if different from sender %(longdescr)s - the rest of the patch description, after the first line %(patch)s - patch name %(prefix)s - 'prefix' string passed on the command line %(pspace)s - ' ' if %(prefix)s is non-empty, otherwise empty string %(shortdescr)s - the first line of the patch description""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches)] options = [ opt('-a', '--all', action = 'store_true', short = 'E-mail all the applied patches'), opt('--to', action = 'append', args = [argparse.mail_aliases], short = 'Add TO to the To: list'), opt('--cc', action = 'append', args = [argparse.mail_aliases], short = 'Add CC to the Cc: list'), opt('--bcc', action = 'append', args = [argparse.mail_aliases], short = 'Add BCC to the Bcc: list'), opt('--auto', action = 'store_true', short = 'Automatically cc the patch signers'), opt('--no-thread', action = 'store_true', short = 'Do not send subsequent messages as replies'), opt('--unrelated', action = 'store_true', short = 'Send patches without sequence numbering'), opt('--attach', action = 'store_true', short = 'Send a patch as attachment'), opt('--attach-inline', action = 'store_true', short = 'Send a patch inline and as an attachment'), opt('-v', '--version', metavar = 'VERSION', short = 'Add VERSION to the [PATCH ...] prefix'), opt('--prefix', metavar = 'PREFIX', short = 'Add PREFIX to the [... PATCH ...] prefix'), opt('-t', '--template', metavar = 'FILE', short = 'Use FILE as the message template'), opt('-c', '--cover', metavar = 'FILE', short = 'Send FILE as the cover message'), opt('-e', '--edit-cover', action = 'store_true', short = 'Edit the cover message before sending'), opt('-E', '--edit-patches', action = 'store_true', short = 'Edit each patch before sending'), opt('-s', '--sleep', type = 'int', metavar = 'SECONDS', short = 'Sleep for SECONDS between e-mails sending'), opt('--in-reply-to', metavar = 'REFID', short = 'Use REFID as the reference id'), opt('--smtp-server', metavar = 'HOST[:PORT] or "/path/to/sendmail -t -i"', short = 'SMTP server or command to use for sending mail'), opt('-u', '--smtp-user', metavar = 'USER', short = 'Username for SMTP authentication'), opt('-p', '--smtp-password', metavar = 'PASSWORD', short = 'Password for SMTP authentication'), opt('-T', '--smtp-tls', action = 'store_true', short = 'Use SMTP with TLS encryption'), opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch'), opt('-m', '--mbox', action = 'store_true', short = 'Generate an mbox file instead of sending'), opt('--git', action = 'store_true', short = 'Use git send-email (EXPERIMENTAL)') ] + argparse.diff_opts_option() directory = DirectoryHasRepository(log=False) crt_series = None def __get_sender(): """Return the 'authname ' string as read from the configuration file """ sender = config.get('stgit.sender') if not sender: try: sender = text(git.user()) except git.GitException: try: sender = text(git.author()) except git.GitException: pass if not sender: raise CmdException('Unknown sender name and e-mail; you should for ' 'example set git config user.name and user.email') sender = email.utils.parseaddr(sender) return email.utils.formataddr(address_or_alias(sender)) def __addr_list(msg, header): return [addr for name, addr in email.utils.getaddresses(msg.get_all(header, []))] def __parse_addresses(msg): """Return a two elements tuple: (from, [to]) """ from_addr_list = __addr_list(msg, 'From') if len(from_addr_list) == 0: raise CmdException('No "From" address') to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \ + __addr_list(msg, 'Bcc') if len(to_addr_list) == 0: raise CmdException('No "To/Cc/Bcc" addresses') return (from_addr_list[0], set(to_addr_list)) def __send_message_sendmail(sendmail, msg_bytes): """Send the message using the sendmail command. """ cmd = sendmail.split() Run(*cmd).encoding(None).raw_input(msg_bytes).discard_output() __smtp_credentials = None def __set_smtp_credentials(options): """Set the (smtpuser, smtppassword, smtpusetls) credentials if the method of sending is SMTP. """ global __smtp_credentials smtpserver = options.smtp_server or config.get('stgit.smtpserver') if options.mbox or options.git or smtpserver.startswith('/'): return smtppassword = options.smtp_password or config.get('stgit.smtppassword') smtpuser = options.smtp_user or config.get('stgit.smtpuser') smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes' if (smtppassword and not smtpuser): raise CmdException('SMTP password supplied, username needed') if (smtpusetls and not smtpuser): raise CmdException('SMTP over TLS requested, username needed') if (smtpuser and not smtppassword): smtppassword = getpass.getpass("Please enter SMTP password: ") __smtp_credentials = (smtpuser, smtppassword, smtpusetls) def __send_message_smtp(smtpserver, from_addr, to_addr_list, msg, options): """Send the message using the given SMTP server """ smtpuser, smtppassword, smtpusetls = __smtp_credentials try: s = smtplib.SMTP(smtpserver) except Exception as err: raise CmdException(str(err)) s.set_debuglevel(0) try: if smtpuser and smtppassword: s.ehlo() if smtpusetls: if not hasattr(socket, 'ssl'): raise CmdException( "cannot use TLS - no SSL support in Python") s.starttls() s.ehlo() s.login(smtpuser, smtppassword) result = s.sendmail(from_addr, to_addr_list, msg) if len(result): print("mail server refused delivery for the following recipients: %s" % result) except Exception as err: raise CmdException(str(err)) s.quit() def __send_message_git(msg_bytes, from_, options): """Send the message using git send-email """ from subprocess import call from tempfile import mkstemp cmd = ["git", "send-email", "--from=%s" % from_] cmd.append("--quiet") cmd.append("--suppress-cc=self") if not options.auto: cmd.append("--suppress-cc=body") if options.in_reply_to: cmd.extend(["--in-reply-to", options.in_reply_to]) if options.no_thread: cmd.append("--no-thread") # We only support To/Cc/Bcc in git send-email for now. for x in ['to', 'cc', 'bcc']: if getattr(options, x): cmd.extend('--%s=%s' % (x, a) for a in getattr(options, x)) (fd, path) = mkstemp() try: os.write(fd, msg_bytes) os.close(fd) try: cmd.append(path) call(cmd) except Exception as err: raise CmdException(str(err)) finally: os.unlink(path) def __send_message(type, tmpl, options, *args): """Message sending dispatcher. """ (build, outstr) = {'cover': (__build_cover, 'the cover message'), 'patch': (__build_message, 'patch "%s"' % args[0])}[type] if type == 'patch': (patch_nr, total_nr) = (args[1], args[2]) msg_id = email.utils.make_msgid('stgit') msg = build(tmpl, msg_id, options, *args) if hasattr(msg, 'as_bytes'): msg_bytes = msg.as_bytes(options.mbox) else: msg_bytes = msg.as_string(options.mbox) # Python 3.3 only has Message.as_string(). We encode it back to bytes # and hope for the best. if isinstance(msg_bytes, text): msg_bytes = msg_bytes.encode('utf-8') if options.mbox: out.stdout_bytes(msg_bytes + b'\n') return msg_id if not options.git: from_addr, to_addrs = __parse_addresses(msg) out.start('Sending ' + outstr) smtpserver = options.smtp_server or config.get('stgit.smtpserver') if options.git: __send_message_git(msg_bytes, msg['From'], options) elif smtpserver.startswith('/'): # Use the sendmail tool __send_message_sendmail(smtpserver, msg_bytes) else: # Use the SMTP server (we have host and port information) __send_message_smtp(smtpserver, from_addr, to_addrs, msg_bytes, options) # give recipients a chance of receiving related patches in correct order if type == 'cover' or (type == 'patch' and patch_nr < total_nr): sleep = options.sleep or config.getint('stgit.smtpdelay') time.sleep(sleep) if not options.git: out.done() return msg_id def __update_header(msg, header, addr = '', ignore = ()): addr_pairs = email.utils.getaddresses(msg.get_all(header, []) + [addr]) del msg[header] # remove pairs without an address and resolve the aliases addr_pairs = [address_or_alias(name_addr) for name_addr in addr_pairs if name_addr[1]] # remove the duplicates and filter the addresses addr_pairs = [name_addr for name_addr in addr_pairs if name_addr[1] not in ignore] if addr_pairs: msg[header] = ', '.join(map(email.utils.formataddr, addr_pairs)) return set(addr for _, addr in addr_pairs) def __build_address_headers(msg, options, extra_cc = []): """Build the address headers and check existing headers in the template. """ to_addr = '' cc_addr = '' extra_cc_addr = '' bcc_addr = '' autobcc = config.get('stgit.autobcc') or '' if options.to: to_addr = ', '.join(options.to) if options.cc: cc_addr = ', '.join(options.cc) if extra_cc: extra_cc_addr = ', '.join(extra_cc) if options.bcc: bcc_addr = ', '.join(options.bcc + [autobcc]) elif autobcc: bcc_addr = autobcc # if an address is on a header, ignore it from the rest from_set = __update_header(msg, 'From') to_set = __update_header(msg, 'To', to_addr) # --auto generated addresses, don't include the sender __update_header(msg, 'Cc', extra_cc_addr, from_set) cc_set = __update_header(msg, 'Cc', cc_addr, to_set) __update_header(msg, 'Bcc', bcc_addr, to_set.union(cc_set)) def __get_signers_list(msg): """Return the address list generated from signed-off-by and acked-by lines in the message. """ addr_list = [] tags = '%s|%s|%s|%s|%s|%s|%s|%s' % ( 'signed-off-by', 'acked-by', 'cc', 'reviewed-by', 'reported-by', 'tested-by', 'suggested-by', 'reported-and-tested-by') regex = r'^(%s):\s+(.+)$' % tags r = re.compile(regex, re.I) for line in msg.split('\n'): m = r.match(line) if m: addr_list.append(m.expand(r'\g<2>')) return addr_list def __build_extra_headers(msg, msg_id, ref_id = None): """Build extra email headers and encoding """ del msg['Date'] msg['Date'] = email.utils.formatdate(localtime = True) msg['Message-ID'] = msg_id if ref_id: # make sure the ref id has the angle brackets ref_id = '<%s>' % ref_id.strip(' \t\n<>') msg['In-Reply-To'] = ref_id msg['References'] = ref_id msg['User-Agent'] = 'StGit/%s' % version.get_version() # update other address headers __update_header(msg, 'Reply-To') __update_header(msg, 'Mail-Reply-To') __update_header(msg, 'Mail-Followup-To') def __encode_message(msg): # 7 or 8 bit encoding charset = email.charset.Charset('utf-8') charset.body_encoding = None # encode headers for header, value in msg.items(): words = [] for word in value.split(' '): words.append(email.header.Header(word).encode()) new_val = ' '.join(words) msg.replace_header(header, new_val) # replace the Subject string with a Header() object otherwise the long # line folding is done using "\n\t" rather than "\n ", causing issues with # some e-mail clients subject = msg.get('subject', '') msg.replace_header('subject', email.header.Header(subject, header_name = 'subject')) # encode the body and set the MIME and encoding headers if msg.is_multipart(): for p in msg.get_payload(): # TODO test if payload can be encoded with charset. Perhaps # iterate email.charset.CHARSETS to find an encodable one? p.set_charset(charset) else: msg.set_charset(charset) def __build_cover(tmpl, msg_id, options, patches): """Build the cover message (series description) to be sent via SMTP """ sender = __get_sender() if options.version: version_str = '%s' % options.version version_space = ' ' else: version_str = '' version_space = '' if options.prefix: prefix_str = options.prefix else: prefix_str = config.get('stgit.mail.prefix') if prefix_str: prefix_space = ' ' else: prefix_str = '' prefix_space = '' total_nr_str = text(len(patches)) patch_nr_str = '0'.zfill(len(total_nr_str)) if len(patches) > 1: number_str = '%s/%s' % (patch_nr_str, total_nr_str) number_space = ' ' else: number_str = '' number_space = '' tmpl_dict = {'sender': sender, # for backward template compatibility 'maintainer': sender, # for backward template compatibility 'endofheaders': '', # for backward template compatibility 'date': '', 'version': version_str, 'vspace': version_space, 'prefix': prefix_str, 'pspace': prefix_space, 'patchnr': patch_nr_str, 'totalnr': total_nr_str, 'number': number_str, 'nspace': number_space, 'snumber': number_str.strip(), 'shortlog': stack.shortlog(crt_series.get_patch(p) for p in reversed(patches)), 'diffstat': gitlib.diffstat(git.diff( rev1 = git_id(crt_series, '%s^' % patches[0]), rev2 = git_id(crt_series, '%s' % patches[-1]), diff_flags = options.diff_flags))} try: msg_bytes = templates.specialize_template(tmpl, tmpl_dict) except KeyError as err: raise CmdException('Unknown patch template variable: %s' % err) except TypeError: raise CmdException('Only "%(name)s" variables are ' 'supported in the patch template') if options.edit_cover: msg_bytes = edit_bytes(msg_bytes, '.stgitmail.txt') # The Python email message try: msg = message_from_bytes(msg_bytes) except Exception as ex: raise CmdException('template parsing error: %s' % str(ex)) extra_cc = [] if options.auto: for patch in patches: p = crt_series.get_patch(patch) if p.get_description(): descr = p.get_description().strip() extra_cc.extend(__get_signers_list(descr)) extra_cc = list(set(extra_cc)) if not options.git: __build_address_headers(msg, options, extra_cc) __build_extra_headers(msg, msg_id, options.in_reply_to) __encode_message(msg) return msg def __build_message(tmpl, msg_id, options, patch, patch_nr, total_nr, ref_id): """Build the message to be sent via SMTP """ p = crt_series.get_patch(patch) if p.get_description(): descr = p.get_description().strip() else: # provide a place holder and force the edit message option on descr = '' options.edit_patches = True descr_lines = descr.split('\n') short_descr = descr_lines[0].strip() long_descr = '\n'.join(l.rstrip() for l in descr_lines[1:]).lstrip('\n') authname = p.get_authname() authemail = p.get_authemail() commname = p.get_commname() commemail = p.get_commemail() sender = __get_sender() fromauth = '%s <%s>' % (authname, authemail) if fromauth != sender: fromauth = 'From: %s\n\n' % fromauth else: fromauth = '' if options.version: version_str = '%s' % options.version version_space = ' ' else: version_str = '' version_space = '' if options.prefix: prefix_str = options.prefix else: prefix_str = config.get('stgit.mail.prefix') if prefix_str: prefix_space = ' ' else: prefix_str = '' prefix_space = '' total_nr_str = text(total_nr) patch_nr_str = text(patch_nr).zfill(len(total_nr_str)) if not options.unrelated and total_nr > 1: number_str = '%s/%s' % (patch_nr_str, total_nr_str) number_space = ' ' else: number_str = '' number_space = '' diff = git.diff(rev1 = git_id(crt_series, '%s^' % patch), rev2 = git_id(crt_series, '%s' % patch), diff_flags = options.diff_flags) tmpl_dict = {'patch': patch, 'sender': sender, # for backward template compatibility 'maintainer': sender, 'shortdescr': short_descr, 'longdescr': long_descr, # for backward template compatibility 'endofheaders': '', 'diff': diff, 'diffstat': gitlib.diffstat(diff), # for backward template compatibility 'date': '', 'version': version_str, 'vspace': version_space, 'prefix': prefix_str, 'pspace': prefix_space, 'patchnr': patch_nr_str, 'totalnr': total_nr_str, 'number': number_str, 'nspace': number_space, 'snumber': number_str.strip(), 'fromauth': fromauth, 'authname': authname, 'authemail': authemail, 'authdate': p.get_authdate(), 'commname': commname, 'commemail': commemail} try: msg_bytes = templates.specialize_template(tmpl, tmpl_dict) except KeyError as err: raise CmdException('Unknown patch template variable: %s' % err) except TypeError: raise CmdException('Only "%(name)s" variables are ' 'supported in the patch template') if options.edit_patches: msg_bytes = edit_bytes(msg_bytes, '.stgitmail.txt') # The Python email message try: msg = message_from_bytes(msg_bytes) except Exception as ex: raise CmdException('template parsing error: %s' % str(ex)) if options.auto: extra_cc = __get_signers_list(descr) else: extra_cc = [] if not options.git: __build_address_headers(msg, options, extra_cc) __build_extra_headers(msg, msg_id, ref_id) __encode_message(msg) return msg def func(parser, options, args): """Send the patches by e-mail using the patchmail.tmpl file as a template """ applied = crt_series.get_applied() if options.all: patches = applied elif len(args) >= 1: unapplied = crt_series.get_unapplied() patches = parse_patches(args, applied + unapplied, len(applied)) else: raise CmdException('Incorrect options. Unknown patches to send') # early test for sender identity __get_sender() out.start('Checking the validity of the patches') for p in patches: if crt_series.empty_patch(p): raise CmdException('Cannot send empty patch "%s"' % p) out.done() total_nr = len(patches) if total_nr == 0: raise CmdException('No patches to send') if options.in_reply_to: if options.no_thread or options.unrelated: raise CmdException('--in-reply-to option not allowed with ' '--no-thread or --unrelated') ref_id = options.in_reply_to else: ref_id = None # get username/password if sending by SMTP __set_smtp_credentials(options) # send the cover message (if any) if options.cover or options.edit_cover: if options.unrelated: raise CmdException('cover sending not allowed with --unrelated') # find the template file if options.cover: with io.open(options.cover, 'r') as f: tmpl = f.read() else: tmpl = templates.get_template('covermail.tmpl') if not tmpl: raise CmdException('No cover message template file found') msg_id = __send_message('cover', tmpl, options, patches) # subsequent e-mails are seen as replies to the first one if not options.no_thread: ref_id = msg_id # send the patches if options.template: with io.open(options.template, 'r') as f: tmpl = f.read() else: if options.attach: tmpl = templates.get_template('mailattch.tmpl') elif options.attach_inline: tmpl = templates.get_template('patchandattch.tmpl') else: tmpl = templates.get_template('patchmail.tmpl') if not tmpl: raise CmdException('No e-mail template file found') for (p, n) in zip(patches, range(1, total_nr + 1)): msg_id = __send_message('patch', tmpl, options, p, n, total_nr, ref_id) # subsequent e-mails are seen as replies to the first one if not options.no_thread and not options.unrelated and not ref_id: ref_id = msg_id stgit-0.19/stgit/commands/new.py000066400000000000000000000065001337022307200166730ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, utils from stgit.commands import common from stgit.lib import git as gitlib, transaction __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Create a new, empty patch' kind = 'patch' usage = ['[options] [--] []'] description = """ Create a new, empty patch on the current stack. The new patch is created on top of the currently applied patches, and is made the new top of the stack. Uncommitted changes in the work tree are not included in the patch -- that is handled by linkstg:refresh[]. The given name must be unique in the stack, and may only contain alphanumeric characters, dashes and underscores. If no name is given, one is generated from the first line of the patch's commit message. An editor will be launched to edit the commit message to be used for the patch, unless the '--message' flag already specified one. The 'patchdescr.tmpl' template file (if available) is used to pre-fill the editor.""" args = [] options = (argparse.author_options() + argparse.message_options(save_template = True) + argparse.sign_options() + argparse.hook_options()) directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Create a new patch.""" stack = directory.repository.current_stack if stack.repository.default_index.conflicts(): raise common.CmdException( 'Cannot create a new patch -- resolve conflicts first') # Choose a name for the new patch -- or None, which means make one # up later when we've gotten hold of the commit message. if len(args) == 0: name = None elif len(args) == 1: name = args[0] if stack.patches.exists(name): raise common.CmdException('%s: patch already exists' % name) else: parser.error('incorrect number of arguments') cd = gitlib.CommitData( tree = stack.head.data.tree, parents = [stack.head], message = '', author = gitlib.Person.author(), committer = gitlib.Person.committer()) cd = common.update_commit_data(cd, options) if options.save_template: options.save_template(cd.message.encode('utf-8')) return utils.STGIT_SUCCESS if not options.no_verify: cd = common.run_commit_msg_hook(stack.repository, cd) if name is None: name = utils.make_patch_name(cd.message, lambda name: stack.patches.exists(name)) # Write the new patch. stack.repository.default_iw trans = transaction.StackTransaction(stack, 'new') trans.patches[name] = stack.repository.commit(cd) trans.applied.append(name) return trans.run() stgit-0.19/stgit/commands/next.py000066400000000000000000000030621337022307200170600ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Print the name of the next patch' kind = 'stack' usage = [''] description = """ Print the name of the next patch.""" args = [] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Show the name of the next patch """ if len(args) != 0: parser.error('incorrect number of arguments') stack = directory.repository.get_stack(options.branch) unapplied = stack.patchorder.unapplied if unapplied: out.stdout(unapplied[0]) else: raise common.CmdException('No unapplied patches') stgit-0.19/stgit/commands/patches.py000066400000000000000000000062731337022307200175400ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, git from stgit.argparse import opt from stgit.commands.common import CmdException, DirectoryHasRepository from stgit.out import out from stgit.pager import pager __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Show the applied patches modifying a file' kind = 'stack' usage = ['[options] [--] []'] description = """ Show the applied patches modifying the given files. Without arguments, it shows the patches affected by the local tree modifications. The '--diff' option also lists the patch log and the diff for the given files.""" args = [argparse.known_files] options = [ opt('-d', '--diff', action = 'store_true', short = 'Show the diff for the given files'), opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch')] directory = DirectoryHasRepository(log=False) crt_series = None diff_tmpl = \ '-------------------------------------------------------------------------------\n' \ '%s\n' \ '-------------------------------------------------------------------------------\n' \ '%s' \ '---\n\n' \ '%s' def func(parser, options, args): """Show the patches modifying a file """ if not args: files = [path for (stat,path) in git.tree_status(verbose = True)] # git.tree_status returns absolute paths else: files = git.ls_files(args) directory.cd_to_topdir() if not files: raise CmdException('No files specified or no local changes') applied = crt_series.get_applied() if not applied: raise CmdException('No patches applied') revs = git.modifying_revs(files, crt_series.get_base(), crt_series.get_head()) revs.reverse() # build the patch/revision mapping rev_patch = dict() for name in applied: patch = crt_series.get_patch(name) rev_patch[patch.get_top()] = patch # print the patch names diff_output = '' for rev in revs: if rev in rev_patch: patch = rev_patch[rev] if options.diff: diff_output += diff_tmpl \ % (patch.get_name(), patch.get_description(), git.diff(files, patch.get_bottom(), patch.get_top())) else: out.stdout(patch.get_name()) if options.diff: pager(diff_output.encode('utf-8')) stgit-0.19/stgit/commands/pick.py000066400000000000000000000206551337022307200170370ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, git from stgit.argparse import opt from stgit.commands.common import (CmdException, DirectoryGotoToplevel, check_head_top_equal, check_local_changes, check_conflicts, git_id, name_email_date, parse_patches, parse_rev, print_crt_patch) from stgit.out import out from stgit.stack import Series from stgit.utils import find_patch_name __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Import a patch from a different branch or a commit object' kind = 'patch' usage = ['[options] [--] ([] [] [..])|'] description = """ Import one or more patches from a different branch or a commit object into the current series. By default, the name of the imported patch is used as the name of the current patch. It can be overridden with the '--name' option. A commit object can be reverted with the '--revert' option. The log and author information are those of the commit object.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches)] options = [ opt('-n', '--name', short = 'Use NAME as the patch name'), opt('-B', '--ref-branch', args = [argparse.stg_branches], short = 'Pick patches from BRANCH'), opt('-r', '--revert', action = 'store_true', short = 'Revert the given commit object'), opt('-p', '--parent', metavar = 'COMMITID', args = [argparse.commit], short = 'Use COMMITID as parent'), opt('-x', '--expose', action = 'store_true', short = 'Append the imported commit id to the patch log'), opt('--fold', action = 'store_true', short = 'Fold the commit object into the current patch'), opt('--update', action = 'store_true', short = 'Like fold but only update the current patch files'), opt('-f', '--file', action = 'append', short = 'Only fold the given file (can be used multiple times)'), opt('--unapplied', action = 'store_true', short = 'Keep the patch unapplied')] directory = DirectoryGotoToplevel(log=True) crt_series = None def __pick_commit(commit_id, patchname, options): """Pick a commit id. """ commit = git.Commit(commit_id) if options.name: patchname = options.name elif patchname and options.revert: patchname = 'revert-' + patchname if patchname: patchname = find_patch_name(patchname, crt_series.patch_exists) if options.parent: parent = git_id(crt_series, options.parent) else: parent = commit.get_parent() if not options.revert: bottom = parent top = commit_id else: bottom = commit_id top = parent if options.fold: out.start('Folding commit %s' % commit_id) # try a direct git apply first if not git.apply_diff(bottom, top, files = options.file): if options.file: raise CmdException('Patch folding failed') else: git.merge_recursive(bottom, git.get_head(), top) out.done() elif options.update: rev1 = git_id(crt_series, 'HEAD^') rev2 = git_id(crt_series, 'HEAD') files = git.barefiles(rev1, rev2).split('\n') out.start('Updating with commit %s' % commit_id) if not git.apply_diff(bottom, top, files = files): raise CmdException('Patch updating failed') out.done() else: message = commit.get_log() if options.revert: if message: lines = message.splitlines() subject = lines[0] body = '\n'.join(lines[2:]) else: subject = commit.get_id_hash() body = '' message = 'Revert "%s"\n\nThis reverts commit %s.\n\n%s\n' \ % (subject, commit.get_id_hash(), body) elif options.expose: if not message.endswith('\n'): message += '\n' message += '(imported from commit %s)\n' % commit.get_id_hash() author_name, author_email, author_date = \ name_email_date(commit.get_author()) if options.revert: author_name = author_email = None out.start('Importing commit %s' % commit_id) newpatch = crt_series.new_patch(patchname, message = message, can_edit = False, unapplied = True, bottom = bottom, top = top, author_name = author_name, author_email = author_email, author_date = author_date) # in case the patch name was automatically generated patchname = newpatch.get_name() # find a patchlog to fork from refbranchname, refpatchname = parse_rev(patchname) if refpatchname: if refbranchname: # assume the refseries is OK, since we already resolved # commit_str to a git_id refseries = Series(refbranchname) else: refseries = crt_series patch = refseries.get_patch(refpatchname) if patch.get_log(): out.info("Log was %s" % newpatch.get_log()) out.info("Setting log to %s\n" % patch.get_log()) newpatch.set_log(patch.get_log()) out.info("Log is now %s" % newpatch.get_log()) else: out.info("No log for %s\n" % patchname) if not options.unapplied: modified = crt_series.push_patch(patchname) else: modified = False if crt_series.empty_patch(patchname): out.done('empty patch') elif modified: out.done('modified') else: out.done() def func(parser, options, args): """Import a commit object as a new patch """ if not args: parser.error('incorrect number of arguments') if options.file and not options.fold: parser.error('--file can only be specified with --fold') if not options.unapplied: check_local_changes() check_conflicts() check_head_top_equal(crt_series) if options.ref_branch: remote_series = Series(options.ref_branch) else: remote_series = crt_series applied = remote_series.get_applied() unapplied = remote_series.get_unapplied() try: patches = parse_patches(args, applied + unapplied, len(applied)) commit_id = None except CmdException: if len(args) > 1: raise # no patches found, try a commit id commit_id = git_id(remote_series, args[0]) if not commit_id and len(patches) > 1: if options.name: raise CmdException('--name can only be specified with one patch') if options.parent: raise CmdException('--parent can only be specified with one patch') if options.update and not crt_series.get_current(): raise CmdException('No patches applied') if commit_id: # Try to guess a patch name if the argument was : try: patchname = args[0].split(':')[1] except IndexError: patchname = None __pick_commit(commit_id, patchname, options) else: if options.unapplied: patches.reverse() for patch in patches: __pick_commit(git_id(remote_series, patch), patch, options) print_crt_patch(crt_series) stgit-0.19/stgit/commands/pop.py000066400000000000000000000070731337022307200167060ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Pop one or more patches from the stack' kind = 'stack' usage = ['[options] [--] [] [] [..]'] description = """ Pop the topmost patch or a range of patches from the stack. The command fails if there are conflicts or local changes (and --keep was not specified). A series of pop and push operations are performed so that only the patches passed on the command line are popped from the stack. Some of the push operations may fail because of conflicts ("stg undo" would revert the last push operation).""" args = [argparse.patch_range(argparse.applied_patches)] options = [ opt('-a', '--all', action = 'store_true', short = 'Pop all the applied patches'), opt('-s', '--spill', action = 'store_true', short = 'Pop a patch, keeping its modifications in the tree'), opt('-n', '--number', type = 'int', short = 'Pop the specified number of patches', long = ''' Pop the specified number of patches. With a negative number, pop all but that many patches.'''), ] + argparse.keep_option() directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Pop the given patches or the topmost one from the stack.""" stack = directory.repository.current_stack iw = stack.repository.default_iw clean_iw = (not options.keep and not options.spill and iw) or None trans = transaction.StackTransaction(stack, 'pop', check_clean_iw = clean_iw) if options.number == 0: # explicitly allow this without any warning/error message return if not trans.applied: raise common.CmdException('No patches applied') if options.all: patches = trans.applied elif options.number is not None: # reverse it twice to also work with negative or bigger than # the length numbers patches = trans.applied[::-1][:options.number][::-1] elif not args: patches = [trans.applied[-1]] else: patches = common.parse_patches(args, trans.applied, ordered = True) if not patches: #FIXME: Why is this an error, and not just a noop ? raise common.CmdException('No patches to pop') if options.spill: if set(stack.patchorder.applied[-len(patches):]) != set(patches): parser.error('Can only spill topmost applied patches') iw = None # don't touch index+worktree applied = [p for p in trans.applied if p not in set(patches)] unapplied = patches + trans.unapplied try: trans.reorder_patches(applied, unapplied, iw = iw, allow_interactive = True) except transaction.TransactionException: pass return trans.run(iw) stgit-0.19/stgit/commands/prev.py000066400000000000000000000031231337022307200170540ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Print the name of the previous patch' kind = 'stack' usage = [''] description = """ Print the name of the previous patch.""" args = [] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Show the name of the previous patch """ if len(args) != 0: parser.error('incorrect number of arguments') stack = directory.repository.get_stack(options.branch) applied = stack.patchorder.applied if applied and len(applied) >= 2: out.stdout(applied[-2]) else: raise common.CmdException('Not enough applied patches') stgit-0.19/stgit/commands/publish.py000066400000000000000000000201701337022307200175470ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, utils from stgit.argparse import opt from stgit.commands import common from stgit.lib import git, transaction from stgit.out import out __copyright__ = """ Copyright (C) 2009, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Push the stack changes to a merge-friendly branch' kind = 'stack' usage = ['[options] [--] [branch]'] description = """ This command commits a set of changes on a separate (called public) branch based on the modifications of the given or current stack. The history of the public branch is not re-written, making it merge-friendly and feasible for publishing. The heads of the stack and public branch may be different but the corresponding tree objects are always the same. If the trees of the stack and public branch are different (otherwise the command has no effect), StGit first checks for a rebase of the stack since the last publishing. If a rebase is detected, StGit creates a commit on the public branch corresponding to a merge between the new stack base and the latest public head. If no rebasing was detected, StGit checks for new patches that may have been created on top of the stack since the last publishing. If new patches are found and are not empty, they are checked into the public branch keeping the same commit information (e.g. log message, author, committer, date). If the above tests fail (e.g. patches modified or removed), StGit creates a new commit on the public branch having the same tree as the stack but the public head as its parent. The editor will be invoked if no "--message" option is given. It is recommended that stack modifications falling in different categories as described above are separated by a publish command in order to keep the public branch history cleaner (otherwise StGit would generate a big commit including several stack modifications). The '--unpublished' option can be used to check if there are applied patches that have not been published to the public branch. This is done by trying to revert the patches in the public tree (similar to the 'push --merged' detection). The '--last' option tries to find the last published patch by checking the SHA1 of the patch tree agains the public tree. This may fail if the stack was rebased since the last publish command. The public branch name can be set via the branch..public configuration variable (defaulting to ".public"). """ args = [argparse.all_branches] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch'), opt('-l', '--last', action = 'store_true', short = 'Show the last published patch'), opt('-u', '--unpublished', action = 'store_true', short = 'Show applied patches that have not been published') ] + (argparse.author_options() + argparse.message_options(save_template = False) + argparse.sign_options()) directory = common.DirectoryHasRepositoryLib() def __create_commit(repository, tree, parents, options, message = ''): """Return a new Commit object.""" cd = git.CommitData( tree = tree, parents = parents, message = message, author = git.Person.author(), committer = git.Person.committer()) cd = common.update_commit_data(cd, options) return repository.commit(cd) def __get_published(stack, tree): """Check the patches that were already published.""" trans = transaction.StackTransaction(stack, 'publish') published = trans.check_merged(trans.applied, tree = tree, quiet = True) trans.abort() return published def __get_last(stack, tree): """Return the name of the last published patch.""" for p in reversed(stack.patchorder.applied): pc = stack.patches.get(p).commit if tree.sha1 == pc.data.tree.sha1: return p return None def func(parser, options, args): """Publish the stack changes.""" repository = directory.repository stack = repository.get_stack(options.branch) if not args: public_ref = common.get_public_ref(stack.name) elif len(args) == 1: public_ref = args[0] else: parser.error('incorrect number of arguments') if not public_ref.startswith('refs/heads/'): public_ref = 'refs/heads/' + public_ref # just clone the stack if the public ref does not exist if not repository.refs.exists(public_ref): if options.unpublished or options.last: raise common.CmdException('"%s" does not exist' % public_ref) repository.refs.set(public_ref, stack.head, 'publish') out.info('Created "%s"' % public_ref) return public_head = repository.refs.get(public_ref) public_tree = public_head.data.tree # find the last published patch if options.last: last = __get_last(stack, public_tree) if not last: raise common.CmdException('Unable to find the last published patch ' '(possibly rebased stack)') out.info('%s' % last) return # check for same tree (already up to date) if public_tree.sha1 == stack.head.data.tree.sha1: out.info('"%s" already up to date' % public_ref) return # check for unpublished patches if options.unpublished: published = set(__get_published(stack, public_tree)) for p in stack.patchorder.applied: if p not in published: print(p) return # check for rebased stack. In this case we emulate a merge with the stack # base by setting two parents. merge_bases = set(repository.get_merge_bases(public_head, stack.base)) if public_head in merge_bases: # fast-forward the public ref repository.refs.set(public_ref, stack.head, 'publish') out.info('Fast-forwarded "%s"' % public_ref) return if stack.base not in merge_bases: message = 'Merge %s into %s' % (repository.describe(stack.base).strip(), utils.strip_prefix('refs/heads/', public_ref)) public_head = __create_commit(repository, stack.head.data.tree, [public_head, stack.base], options, message) repository.refs.set(public_ref, public_head, 'publish') out.info('Merged the stack base into "%s"' % public_ref) return # check for new patches from the last publishing. This is done by checking # whether the public tree is the same as the bottom of the checked patch. # If older patches were modified, new patches cannot be detected. The new # patches and their metadata are pushed directly to the published head. for p in stack.patchorder.applied: pc = stack.patches.get(p).commit if public_tree.sha1 == pc.data.parent.data.tree.sha1: if pc.data.is_nochange(): out.info('Ignored new empty patch "%s"' % p) continue cd = pc.data.set_parent(public_head) public_head = repository.commit(cd) public_tree = public_head.data.tree out.info('Published new patch "%s"' % p) # create a new commit (only happens if no new patches are detected) if public_tree.sha1 != stack.head.data.tree.sha1: public_head = __create_commit(repository, stack.head.data.tree, [public_head], options) # update the public head repository.refs.set(public_ref, public_head, 'publish') out.info('Updated "%s"' % public_ref) stgit-0.19/stgit/commands/pull.py000066400000000000000000000104061337022307200170560ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, git from stgit.argparse import opt from stgit.commands.common import (CmdException, DirectoryGotoToplevel, check_conflicts, check_head_top_equal, check_local_changes, post_rebase, prepare_rebase, print_crt_patch, rebase) from stgit.config import config, GitConfigException from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Pull changes from a remote repository' kind = 'stack' usage = ['[options] [--] []'] description = """ Pull the latest changes from the given remote repository (defaulting to branch..remote, or 'origin' if not set). This command works by popping all the patches from the stack, pulling the changes in the parent repository, setting the base of the stack to the latest parent HEAD and pushing the patches back (unless '--nopush' is specified). The 'push' operation can fail if there are conflicts. They need to be resolved and the patch pushed again. Check the 'git fetch' documentation for the format.""" args = [argparse.repo] options = [ opt('-n', '--nopush', action = 'store_true', short = 'Do not push the patches back after pulling'), opt('-m', '--merged', action = 'store_true', short = 'Check for patches merged upstream')] directory = DirectoryGotoToplevel(log=True) crt_series = None def func(parser, options, args): """Pull the changes from a remote repository """ policy = config.get('branch.%s.stgit.pull-policy' % crt_series.get_name()) or \ config.get('stgit.pull-policy') if policy == 'rebase': # parent is local if len(args) == 1: parser.error('specifying a repository is meaningless for policy="%s"' % policy) if len(args) > 0: parser.error('incorrect number of arguments') else: # parent is remote if len(args) > 1: parser.error('incorrect number of arguments') if len(args) >= 1: repository = args[0] else: repository = crt_series.get_parent_remote() if crt_series.get_protected(): raise CmdException('This branch is protected. Pulls are not permitted') check_local_changes() check_conflicts() check_head_top_equal(crt_series) if policy not in ['pull', 'fetch-rebase', 'rebase']: raise GitConfigException('Unsupported pull-policy "%s"' % policy) applied = prepare_rebase(crt_series) # pull the remote changes if policy == 'pull': out.info('Pulling from "%s"' % repository) git.pull(repository) elif policy == 'fetch-rebase': out.info('Fetching from "%s"' % repository) git.fetch(repository) try: target = git.fetch_head() except git.GitException: out.error('Could not find the remote head to rebase onto - fix branch.%s.merge in .git/config' % crt_series.get_name()) out.error('Pushing any patches back...') post_rebase(crt_series, applied, False, False) raise rebase(crt_series, target) elif policy == 'rebase': rebase(crt_series, crt_series.get_parent_branch()) post_rebase(crt_series, applied, options.nopush, options.merged) # maybe tidy up if config.getbool('stgit.keepoptimized'): git.repack() print_crt_patch(crt_series) stgit-0.19/stgit/commands/push.py000066400000000000000000000110021337022307200170520ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Push one or more patches onto the stack' kind = 'stack' usage = ['[options] [--] [] [] [..]'] description = """ Push one or more patches (defaulting to the first unapplied one) onto the stack. The 'push' operation allows patch reordering by commuting them with the three-way merge algorithm. If there are conflicts while pushing a patch, those conflicts are written to the work tree, and the command halts. Conflicts raised during the push operation have to be fixed and the 'git add --update' command run (alternatively, you may undo the conflicting push with 'stg undo'). The command also notifies when the patch becomes empty (fully merged upstream) or is modified (three-way merged) by the 'push' operation.""" args = [argparse.patch_range(argparse.unapplied_patches)] options = [ opt('-a', '--all', action = 'store_true', short = 'Push all the unapplied patches'), opt('-n', '--number', type = 'int', short = 'Push the specified number of patches', long = ''' Push the specified number of patches. With a negative number, push all but that many patches.'''), opt('--reverse', action = 'store_true', short = 'Push the patches in reverse order'), opt('--set-tree', action = 'store_true', short = 'Push the patch with the original tree', long = """ Push the patches, but don't perform a merge. Instead, the resulting tree will be identical to the tree that the patch previously created. This can be useful when splitting a patch by first popping the patch and creating a new patch with some of the changes. Pushing the original patch with '--set-tree' will avoid conflicts and only the remaining changes will be in the patch.""") ] + argparse.keep_option() + argparse.merged_option() directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Pushes the given patches or the first unapplied onto the stack.""" stack = directory.repository.current_stack iw = stack.repository.default_iw clean_iw = (not options.keep and iw) or None trans = transaction.StackTransaction(stack, 'push', check_clean_iw = clean_iw) if options.number == 0: # explicitly allow this without any warning/error message return if not trans.unapplied: raise common.CmdException('No patches to push') if options.all: patches = list(trans.unapplied) elif options.number is not None: patches = trans.unapplied[:options.number] elif not args: patches = [trans.unapplied[0]] else: try: patches = common.parse_patches(args, trans.unapplied) except common.CmdException as e: try: patches = common.parse_patches(args, trans.applied) except common.CmdException: raise e else: raise common.CmdException('Patch%s already applied: %s' % ( 'es' if len(patches) > 1 else '', ', '.join(patches))) assert patches if options.reverse: patches.reverse() if options.set_tree: for pn in patches: trans.push_tree(pn) else: try: if options.merged: merged = set(trans.check_merged(patches)) else: merged = set() for pn in patches: trans.push_patch(pn, iw, allow_interactive = True, already_merged = pn in merged) except transaction.TransactionHalted: pass return trans.run(iw) stgit-0.19/stgit/commands/rebase.py000066400000000000000000000056111337022307200173450ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands.common import (CmdException, DirectoryGotoToplevel, check_conflicts, check_head_top_equal, check_local_changes, git_id, post_rebase, prepare_rebase, print_crt_patch, rebase) from stgit.git import GitException __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Move the stack base to another point in history' kind = 'stack' usage = ['[options] [--] '] description = """ Pop all patches from current stack, move the stack base to the given and push the patches back. If you experience merge conflicts, resolve the problem and continue the rebase by executing the following sequence: $ git add --update $ stg refresh $ stg goto top-patch Or if you want to skip that patch: $ stg undo --hard $ stg push next-patch..top-patch""" args = [argparse.commit] options = [ opt('-n', '--nopush', action = 'store_true', short = 'Do not push the patches back after rebasing'), opt('-m', '--merged', action = 'store_true', short = 'Check for patches merged upstream')] directory = DirectoryGotoToplevel(log=True) crt_series = None def func(parser, options, args): """Rebase the current stack """ if len(args) != 1: parser.error('incorrect number of arguments') if crt_series.get_protected(): raise CmdException('This branch is protected. Rebase is not permitted') check_local_changes() check_conflicts() check_head_top_equal(crt_series) # ensure an exception is raised before popping on non-existent target if git_id(crt_series, args[0]) is None: raise GitException('Unknown revision: %s' % args[0]) applied = prepare_rebase(crt_series) rebase(crt_series, args[0]) post_rebase(crt_series, applied, options.nopush, options.merged) print_crt_patch(crt_series) stgit-0.19/stgit/commands/redo.py000066400000000000000000000041361337022307200170360ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit.argparse import opt from stgit.commands import common from stgit.lib import log, transaction __copyright__ = """ Copyright (C) 2008, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Undo the last undo operation' kind = 'stack' usage = [''] description = """ If the last command was an undo, reset the patch stack to the state it had before the undo. Consecutive invocations of "stg redo" will undo the effects of consecutive invocations of "stg undo". It is an error to run "stg redo" if the last command was not an undo.""" args = [] options = [ opt('-n', '--number', type = 'int', metavar = 'N', default = 1, short = 'Undo the last N undos'), opt('--hard', action = 'store_true', short = 'Discard changes in your index/worktree')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): stack = directory.repository.current_stack if options.number < 1: raise common.CmdException('Bad number of undos to redo') state = log.undo_state(stack, -options.number) trans = transaction.StackTransaction(stack, 'redo %d' % options.number, discard_changes = options.hard, allow_bad_head = True) try: log.reset_stack(trans, stack.repository.default_iw, state) except transaction.TransactionHalted: pass return trans.run(stack.repository.default_iw, allow_bad_head = True) stgit-0.19/stgit/commands/refresh.py000066400000000000000000000326601337022307200175460ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, utils from stgit.argparse import opt from stgit.commands import common from stgit.lib import git, transaction, edit from stgit.config import config from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas Copyright (C) 2008, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Generate a new commit for the current patch' kind = 'patch' usage = ['[options] [--] []'] description = """ Include the latest work tree and index changes in the current patch. This command generates a new git commit object for the patch; the old commit is no longer visible. Refresh will warn if the index is dirty, and require use of either the '--index' or '--force' options to override this check. This is to prevent accidental full refresh when only some changes were staged using git add interative mode. You may optionally list one or more files or directories relative to the current working directory; if you do, only matching files will be updated. Behind the scenes, stg refresh first creates a new temporary patch with your updates, and then merges that patch into the patch you asked to have refreshed. If you asked to refresh a patch other than the topmost patch, there can be conflicts; in that case, the temporary patch will be left for you to take care of, for example with stg squash. The creation of the temporary patch is recorded in a separate entry in the patch stack log; this means that one undo step will undo the merge between the other patch and the temp patch, and two undo steps will additionally get rid of the temp patch.""" args = [argparse.dirty_files] options = [ opt('-u', '--update', action = 'store_true', short = 'Only update the current patch files'), opt('-i', '--index', action = 'store_true', short = 'Refresh from index instead of worktree', long = """ Instead of setting the patch top to the current contents of the worktree, set it to the current contents of the index."""), opt('-F', '--force', action = 'store_true', short = 'Force refresh even if index is dirty', long = """ Instead of warning the user when some work has already been staged (such as with git add interactive mode) force a full refresh."""), opt('-p', '--patch', args = [argparse.other_applied_patches, argparse.unapplied_patches], short = 'Refresh (applied) PATCH instead of the top patch'), opt('-e', '--edit', action = 'store_true', short = 'Invoke an editor for the patch description'), opt('-a', '--annotate', metavar = 'NOTE', short = 'Annotate the patch log entry'), opt('-s', '--submodules', action = 'store_true', short = 'Include submodules when refreshing patch contents'), opt('', '--no-submodules', action = 'store_false', dest = 'submodules', short = 'Exclude submodules when refreshing patch contents') ] + (argparse.message_options(save_template = False) + argparse.hook_options() + argparse.sign_options() + argparse.author_options()) directory = common.DirectoryHasRepositoryLib() def get_patch(stack, given_patch): """Get the name of the patch we are to refresh.""" if given_patch: patch_name = given_patch if not stack.patches.exists(patch_name): raise common.CmdException('%s: no such patch' % patch_name) return patch_name else: if not stack.patchorder.applied: raise common.CmdException( 'Cannot refresh top patch because no patches are applied') return stack.patchorder.applied[-1] def list_files(stack, patch_name, args, index, update, submodules): """Figure out which files to update.""" if index: # --index: Don't update the index. return set() paths = stack.repository.default_iw.changed_files( stack.head.data.tree, args or []) if update: # --update: Restrict update to the paths that were already # part of the patch. paths &= stack.patches.get(patch_name).files() else: # Avoid including submodule files by default. This is to ensure that # users in repositories with submodueles do not accidentally include # submodule changes to patches just because they happen to have not # run "git submodule update" prior to running stg refresh. We won't # exclude them if we're explicitly told to include them, or if we're # given explicit paths. if not args and not submodules: paths -= stack.repository.submodules(stack.head.data.tree) return paths def write_tree(stack, paths, temp_index): """Possibly update the index, and then write its tree. @return: The written tree. @rtype: L{Tree}""" def go(index): if paths: iw = git.IndexAndWorktree(index, stack.repository.default_worktree) iw.update_index(paths) return index.write_tree() if temp_index: index = stack.repository.temp_index() try: index.read_tree(stack.head) return go(index) finally: index.delete() stack.repository.default_iw.update_index(paths) else: return go(stack.repository.default_index) def make_temp_patch(stack, patch_name, paths, temp_index): """Commit index to temp patch, in a complete transaction. If any path limiting is in effect, use a temp index.""" tree = write_tree(stack, paths, temp_index) commit = stack.repository.commit(git.CommitData( tree = tree, parents = [stack.head], message = 'Refresh of %s' % patch_name)) temp_name = utils.make_patch_name('refresh-temp', stack.patches.exists) trans = transaction.StackTransaction(stack, 'refresh (create temporary patch)') trans.patches[temp_name] = commit trans.applied.append(temp_name) return trans.run(stack.repository.default_iw, print_current_patch = False), temp_name def absorb_applied(trans, iw, patch_name, temp_name, edit_fun): """Absorb the temp patch (C{temp_name}) into the given patch (C{patch_name}), which must be applied. If the absorption succeeds, call C{edit_fun} on the resulting L{CommitData} before committing it and commit the return value. @return: C{True} if we managed to absorb the temp patch, C{False} if we had to leave it for the user to deal with.""" temp_absorbed = False try: # Pop any patch on top of the patch we're refreshing. to_pop = trans.applied[trans.applied.index(patch_name)+1:] if len(to_pop) > 1: popped = trans.pop_patches(lambda pn: pn in to_pop) assert not popped # no other patches were popped trans.push_patch(temp_name, iw) assert to_pop.pop() == temp_name # Absorb the temp patch. temp_cd = trans.patches[temp_name].data assert trans.patches[patch_name] == temp_cd.parent trans.patches[patch_name] = trans.stack.repository.commit( edit_fun(trans.patches[patch_name].data.set_tree(temp_cd.tree))) popped = trans.delete_patches(lambda pn: pn == temp_name, quiet = True) assert not popped # the temp patch was topmost temp_absorbed = True # Push back any patch we were forced to pop earlier. for pn in to_pop: trans.push_patch(pn, iw) except transaction.TransactionHalted: pass return temp_absorbed def absorb_unapplied(trans, iw, patch_name, temp_name, edit_fun): """Absorb the temp patch (C{temp_name}) into the given patch (C{patch_name}), which must be unapplied. If the absorption succeeds, call C{edit_fun} on the resulting L{CommitData} before committing it and commit the return value. @param iw: Not used. @return: C{True} if we managed to absorb the temp patch, C{False} if we had to leave it for the user to deal with.""" # Pop the temp patch. popped = trans.pop_patches(lambda pn: pn == temp_name) assert not popped # the temp patch was topmost # Try to create the new tree of the refreshed patch. (This is the # same operation as pushing the temp patch onto the patch we're # trying to refresh -- but we don't have a worktree to spill # conflicts to, so if the simple merge doesn't succeed, we have to # give up.) patch_cd = trans.patches[patch_name].data temp_cd = trans.patches[temp_name].data new_tree = trans.stack.repository.simple_merge( base = temp_cd.parent.data.tree, ours = patch_cd.tree, theirs = temp_cd.tree) if new_tree: # It worked. Refresh the patch with the new tree, and delete # the temp patch. trans.patches[patch_name] = trans.stack.repository.commit( edit_fun(patch_cd.set_tree(new_tree))) popped = trans.delete_patches(lambda pn: pn == temp_name, quiet = True) assert not popped # the temp patch was not applied return True else: # Nope, we couldn't create the new tree, so we'll just have to # leave the temp patch for the user. return False def absorb(stack, patch_name, temp_name, edit_fun, annotate = None): """Absorb the temp patch into the target patch.""" if annotate: log_msg = 'refresh\n\n' + annotate else: log_msg = 'refresh' trans = transaction.StackTransaction(stack, log_msg) iw = stack.repository.default_iw f = { True: absorb_applied, False: absorb_unapplied }[patch_name in trans.applied] if f(trans, iw, patch_name, temp_name, edit_fun): def info_msg(): pass else: def info_msg(): out.warn('The new changes did not apply cleanly to %s.' % patch_name, 'They were saved in %s.' % temp_name) r = trans.run(iw) info_msg() return r def func(parser, options, args): """Generate a new commit for the current or given patch.""" # Catch illegal argument combinations. path_limiting = bool(args or options.update) if options.index and path_limiting: raise common.CmdException( 'Only full refresh is available with the --index option') if options.index and options.force: raise common.CmdException( 'You cannot --force a full refresh when using --index mode') if options.update and options.submodules: raise common.CmdException( '--submodules is meaningless when only updating modified files') if options.index and options.submodules: raise common.CmdException( '--submodules is meaningless when keeping the current index') # If submodules was not specified on the command line, infer a default # from configuration. if options.submodules is None: options.submodules = (config.getbool('stgit.refreshsubmodules')) stack = directory.repository.current_stack patch_name = get_patch(stack, options.patch) paths = list_files(stack, patch_name, args, options.index, options.update, options.submodules) # Make sure there are no conflicts in the files we want to # refresh. if stack.repository.default_index.conflicts() & paths: raise common.CmdException( 'Cannot refresh -- resolve conflicts first') # Make sure the index is clean before performing a full refresh if not options.index and not options.force: if not (stack.repository.default_index.is_clean(stack.head) or stack.repository.default_iw.worktree_clean()): raise common.CmdException( 'The index is dirty. Did you mean --index? To force a full refresh use --force.') # Commit index to temp patch, and absorb it into the target patch. retval, temp_name = make_temp_patch( stack, patch_name, paths, temp_index = path_limiting) if retval != utils.STGIT_SUCCESS: return retval def edit_fun(cd): orig_msg = cd.message cd, failed_diff = edit.auto_edit_patch( stack.repository, cd, msg=(None if options.message is None else options.message.encode('utf-8')), contains_diff=False, author=options.author, committer=lambda p: p, sign_str=options.sign_str) assert not failed_diff if options.edit: cd, failed_diff = edit.interactive_edit_patch( stack.repository, cd, edit_diff = False, diff_flags = [], replacement_diff = None) assert not failed_diff if not options.no_verify and (options.edit or cd.message != orig_msg): cd = common.run_commit_msg_hook(stack.repository, cd, options.edit) return cd return absorb(stack, patch_name, temp_name, edit_fun, annotate = options.annotate) stgit-0.19/stgit/commands/rename.py000066400000000000000000000036031337022307200173520ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands.common import CmdException, DirectoryHasRepository from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Rename a patch' kind = 'patch' usage = ['[options] [--] [oldpatch] '] description = """ Rename into in a series. If is not given, the top-most patch will be renamed.""" args = [argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'use BRANCH instead of the default one')] directory = DirectoryHasRepository(log=True) crt_series = None def func(parser, options, args): """Rename a patch in the series """ crt = crt_series.get_current() if len(args) == 2: old, new = args elif len(args) == 1: if not crt: raise CmdException("No applied top patch to rename exists.") old, [new] = crt, args else: parser.error('incorrect number of arguments') out.start('Renaming patch "%s" to "%s"' % (old, new)) crt_series.rename_patch(old, new) out.done() stgit-0.19/stgit/commands/repair.py000066400000000000000000000204771337022307200173750ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import re from stgit import git from stgit.commands.common import (CmdException, DirectoryGotoToplevel, name_email_date) from stgit.out import out from stgit.run import Run from stgit.utils import make_patch_name __copyright__ = """ Copyright (C) 2006, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Fix StGit metadata if branch was modified with git commands' kind = 'stack' usage = [''] description = """ If you modify an StGit stack (branch) with some git commands -- such as commit, pull, merge, and rebase -- you will leave the StGit metadata in an inconsistent state. In that situation, you have two options: 1. Use "stg undo" to undo the effect of the git commands. (If you know what you are doing and want more control, "git reset" or similar will work too.) 2. Use "stg repair". This will fix up the StGit metadata to accommodate the modifications to the branch. Specifically, it will do the following: * If you have made regular git commits on top of your stack of StGit patches, "stg repair" makes new StGit patches out of them, preserving their contents. * However, merge commits cannot become patches; if you have committed a merge on top of your stack, "repair" will simply mark all patches below the merge unapplied, since they are no longer reachable. If this is not what you want, use "stg undo" to get rid of the merge and run "stg repair" again. * The applied patches are supposed to be precisely those that are reachable from the branch head. If you have used e.g. "git reset" to move the head, some applied patches may no longer be reachable, and some unapplied patches may have become reachable. "stg repair" will correct the appliedness of such patches. "stg repair" will fix these inconsistencies reliably, so as long as you like what it does, you have no reason to avoid causing them in the first place. For example, you might find it convenient to make commits with a graphical tool and then have "stg repair" make proper patches of the commits. NOTE: If using git commands on the stack was a mistake, running "stg repair" is _not_ what you want. In that case, what you want is option (1) above.""" args = [] options = [] directory = DirectoryGotoToplevel(log=True) crt_series = None class Commit(object): def __init__(self, id): self.id = id self.parents = set() self.children = set() self.patch = None self.__commit = None def __get_commit(self): if not self.__commit: self.__commit = git.get_commit(self.id) return self.__commit commit = property(__get_commit) def __str__(self): if self.patch: return '%s (%s)' % (self.id, self.patch) else: return self.id def __repr__(self): return '<%s>' % str(self) def read_commit_dag(branch): out.start('Reading commit DAG') commits = {} patches = set() for line in Run('git', 'rev-list', '--parents', '--all').output_lines(): cs = line.split() for id in cs: if id not in commits: commits[id] = Commit(id) for id in cs[1:]: commits[cs[0]].parents.add(commits[id]) commits[id].children.add(commits[cs[0]]) for line in Run('git', 'show-ref').output_lines(): id, ref = line.split() m = re.match(r'^refs/patches/%s/(.+)$' % re.escape(branch), ref) if m and not m.group(1).endswith('.log'): c = commits[id] c.patch = m.group(1) patches.add(c) out.done() return commits, patches def func(parser, options, args): """Repair inconsistencies in StGit metadata.""" orig_applied = crt_series.get_applied() orig_unapplied = crt_series.get_unapplied() orig_hidden = crt_series.get_hidden() if crt_series.get_protected(): raise CmdException( 'This branch is protected. Modification is not permitted.') # Find commits that aren't patches, and applied patches. head = git.get_commit(git.get_head()).get_id_hash() commits, patches = read_commit_dag(crt_series.get_name()) c = commits[head] patchify = [] # commits to definitely patchify maybe_patchify = [] # commits to patchify if we find a patch below them applied = [] while len(c.parents) == 1: parent, = c.parents if c.patch: applied.append(c) patchify.extend(maybe_patchify) maybe_patchify = [] else: maybe_patchify.append(c) c = parent applied.reverse() patchify.reverse() # Find patches hidden behind a merge. merge = c todo = set([c]) seen = set() hidden = set() while todo: c = todo.pop() seen.add(c) todo |= c.parents - seen if c.patch: hidden.add(c) if hidden: out.warn(('%d patch%s are hidden below the merge commit' % (len(hidden), ['es', ''][len(hidden) == 1])), '%s,' % merge.id, 'and will be considered unapplied.') # Make patches of any linear sequence of commits on top of a patch. names = set(p.patch for p in patches) def name_taken(name): return name in names if applied and patchify: out.start('Creating %d new patch%s' % (len(patchify), ['es', ''][len(patchify) == 1])) for p in patchify: name = make_patch_name(p.commit.get_log(), name_taken) out.info('Creating patch %s from commit %s' % (name, p.id)) aname, amail, adate = name_email_date(p.commit.get_author()) cname, cmail, cdate = name_email_date(p.commit.get_committer()) parent, = p.parents crt_series.new_patch( name, can_edit = False, commit = False, top = p.id, bottom = parent.id, message = p.commit.get_log(), author_name = aname, author_email = amail, author_date = adate, committer_name = cname, committer_email = cmail) p.patch = name applied.append(p) names.add(name) out.done() # Figure out hidden orig_patches = orig_applied + orig_unapplied + orig_hidden orig_applied_name_set = set(orig_applied) orig_unapplied_name_set = set(orig_unapplied) orig_hidden_name_set = set(orig_hidden) orig_patches_name_set = set(orig_patches) hidden = [p for p in patches if p.patch in orig_hidden_name_set] # Write the applied/unapplied files. out.start('Checking patch appliedness') unapplied = patches - set(applied) - set(hidden) applied_name_set = set(p.patch for p in applied) unapplied_name_set = set(p.patch for p in unapplied) hidden_name_set = set(p.patch for p in hidden) patches_name_set = set(p.patch for p in patches) for name in orig_patches_name_set - patches_name_set: out.info('%s is gone' % name) for name in applied_name_set - orig_applied_name_set: out.info('%s is now applied' % name) for name in unapplied_name_set - orig_unapplied_name_set: out.info('%s is now unapplied' % name) for name in hidden_name_set - orig_hidden_name_set: out.info('%s is now hidden' % name) orig_order = dict(zip(orig_patches, range(len(orig_patches)))) def patchname_key(p): i = orig_order.get(p, len(orig_order)) return i, p crt_series.set_applied(p.patch for p in applied) crt_series.set_unapplied(sorted(unapplied_name_set, key=patchname_key)) crt_series.set_hidden(sorted(hidden_name_set, key=patchname_key)) out.done() stgit-0.19/stgit/commands/reset.py000066400000000000000000000051671337022307200172340ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, utils from stgit.argparse import opt from stgit.commands import common from stgit.lib import log, transaction __copyright__ = """ Copyright (C) 2008, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Reset the patch stack to an earlier state' kind = 'stack' usage = ['[options] [--] [ []]'] description = """ Reset the patch stack to an earlier state. If no state is specified, reset only the changes in the worktree. The state is specified with a commit id from a stack log; "stg log" lets you view this log, and "stg reset" lets you reset to any state you see in the log. If one or more patch names are given, reset only those patches, and leave the rest alone.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches)] options = [ opt('--hard', action = 'store_true', short = 'Discard changes in your index/worktree')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): stack = directory.repository.current_stack iw = stack.repository.default_iw if len(args) >= 1: ref, patches = args[0], args[1:] state = log.get_log_entry(stack.repository, ref, stack.repository.rev_parse(ref)) elif options.hard: iw.checkout_hard(stack.head.data.tree) return utils.STGIT_SUCCESS else: raise common.CmdException('Wrong options or number of arguments') trans = transaction.StackTransaction(stack, 'reset', discard_changes = options.hard, allow_bad_head = True) try: if patches: log.reset_stack_partially(trans, iw, state, patches) else: log.reset_stack(trans, iw, state) except transaction.TransactionHalted: pass return trans.run(iw, allow_bad_head = not patches) stgit-0.19/stgit/commands/series.py000066400000000000000000000204431337022307200173760ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.commands.common import parse_patches from stgit.config import config from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Print the patch series' kind = 'stack' usage = ['[options] [--] []'] description = """ Show all the patches in the series, or just those in the given range, ordered from top to bottom. The applied patches are prefixed with a +++ (except the current patch, which is prefixed with a +>+), the unapplied patches with a +-+, and the hidden patches with a +!+. Empty patches are prefixed with a '0'.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches)] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch'), opt('-a', '--all', action = 'store_true', short = 'Show all patches, including the hidden ones'), opt('-A', '--applied', action = 'store_true', short = 'Show the applied patches only'), opt('-U', '--unapplied', action = 'store_true', short = 'Show the unapplied patches only'), opt('-H', '--hidden', action = 'store_true', short = 'Show the hidden patches only'), opt('-m', '--missing', metavar = 'BRANCH', args = [argparse.stg_branches], short = 'Show patches in BRANCH missing in current'), opt('-c', '--count', action = 'store_true', short = 'Print the number of patches in the series'), opt('-d', '--description', action = 'store_true', short = 'Show a short description for each patch'), opt('--author', action = 'store_true', short = 'Show the author name for each patch'), opt('-e', '--empty', action = 'store_true', short = 'Check whether patches are empty', long = """ Before the +++, +>+, +-+, and +!+ prefixes, print a column that contains either +0+ (for empty patches) or a space (for non-empty patches)."""), opt('--showbranch', action = 'store_true', short = 'Append the branch name to the listed patches'), opt('--noprefix', action = 'store_true', short = 'Do not show the patch status prefix'), opt('-s', '--short', action = 'store_true', short = 'List just the patches around the topmost patch')] directory = common.DirectoryHasRepositoryLib() def __get_description(stack, patch): """Extract and return a patch's short description """ cd = stack.patches.get(patch).commit.data descr = cd.message.strip() descr_lines = descr.split('\n') return descr_lines[0].rstrip() def __get_author(stack, patch): """Extract and return a patch's short description """ cd = stack.patches.get(patch).commit.data return cd.author.name def __render_text(text, effects): _effects = { 'none' : 0, 'bright' : 1, 'dim' : 2, 'black_foreground' : 30, 'red_foreground' : 31, 'green_foreground' : 32, 'yellow_foreground' : 33, 'blue_foreground' : 34, 'magenta_foreground' : 35, 'cyan_foreground' : 36, 'white_foreground' : 37, 'black_background' : 40, 'red_background' : 41, 'green_background' : 42, 'yellow_background' : 44, 'blue_background' : 44, 'magenta_background' : 45, 'cyan_background' : 46, 'white_background' : 47 } start = [str(_effects[e]) for e in effects.split() if e in _effects] start = '\033[' + ';'.join(start) + 'm' stop = '\033[' + str(_effects['none']) + 'm' return ''.join([start, text, stop]) def __print_patch(stack, patch, branch_str, prefix, length, options, effects): """Print a patch name, description and various markers. """ if options.noprefix: prefix = '' elif options.empty: if stack.patches.get(patch).is_empty(): prefix = '0' + prefix else: prefix = ' ' + prefix patch_str = branch_str + patch if options.description or options.author: patch_str = patch_str.ljust(length) if options.description: output = prefix + patch_str + ' # ' + __get_description(stack, patch) elif options.author: output = prefix + patch_str + ' # ' + __get_author(stack, patch) else: output = prefix + patch_str if not effects: out.stdout(output) else: out.stdout(__render_text(output, effects)) def func(parser, options, args): """Show the patch series """ if options.all and options.short: raise common.CmdException('combining --all and --short is meaningless') stack = directory.repository.get_stack(options.branch) if options.missing: cmp_stack = stack stack = directory.repository.get_stack(options.missing) # current series patches applied = unapplied = hidden = () if options.applied or options.unapplied or options.hidden: if options.all: raise common.CmdException('--all cannot be used with' ' --applied/unapplied/hidden') if options.applied: applied = stack.patchorder.applied if options.unapplied: unapplied = stack.patchorder.unapplied if options.hidden: hidden = stack.patchorder.hidden elif options.all: applied = stack.patchorder.applied unapplied = stack.patchorder.unapplied hidden = stack.patchorder.hidden else: applied = stack.patchorder.applied unapplied = stack.patchorder.unapplied if options.missing: cmp_patches = cmp_stack.patchorder.all else: cmp_patches = () # the filtering range covers the whole series if args: show_patches = parse_patches(args, applied + unapplied + hidden, len(applied)) else: show_patches = applied + unapplied + hidden # missing filtering show_patches = [p for p in show_patches if p not in cmp_patches] # filter the patches applied = [p for p in applied if p in show_patches] unapplied = [p for p in unapplied if p in show_patches] hidden = [p for p in hidden if p in show_patches] if options.short: nr = int(config.get('stgit.shortnr')) if len(applied) > nr: applied = applied[-(nr+1):] n = len(unapplied) if n > nr: unapplied = unapplied[:nr] elif n < nr: hidden = hidden[:nr-n] patches = applied + unapplied + hidden if options.count: out.stdout(len(patches)) return if not patches: return if options.showbranch: branch_str = stack.name + ':' else: branch_str = '' max_len = 0 if len(patches) > 0: max_len = max([len(i + branch_str) for i in patches]) if applied: for p in applied[:-1]: __print_patch(stack, p, branch_str, '+ ', max_len, options, config.get("stgit.color.applied")) __print_patch(stack, applied[-1], branch_str, '> ', max_len, options, config.get("stgit.color.current")) for p in unapplied: __print_patch(stack, p, branch_str, '- ', max_len, options, config.get("stgit.color.unapplied")) for p in hidden: __print_patch(stack, p, branch_str, '! ', max_len, options, config.get("stgit.color.hidden")) stgit-0.19/stgit/commands/show.py000066400000000000000000000061561337022307200170710ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands.common import (DirectoryHasRepository, color_diff_flags, git_id, parse_patches) from stgit.lib import git from stgit.pager import pager from stgit.run import Run __copyright__ = """ Copyright (C) 2006, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Show the commit corresponding to a patch' kind = 'patch' usage = ['[options] [--] [] [] [..]'] description = """ Show the commit log and the diff corresponding to the given patches. The output is similar to that generated by 'git show'.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches, argparse.hidden_patches)] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch'), opt('-a', '--applied', action = 'store_true', short = 'Show the applied patches'), opt('-u', '--unapplied', action = 'store_true', short = 'Show the unapplied patches'), opt('-s', '--stat', action = 'store_true', short = 'Show a diffstat summary of the specified patches'), ] + argparse.diff_opts_option() directory = DirectoryHasRepository(log=False) crt_series = None def func(parser, options, args): """Show commit log and diff """ if options.applied: patches = crt_series.get_applied() elif options.unapplied: patches = crt_series.get_unapplied() elif len(args) == 0: patches = ['HEAD'] elif '..' in ' '.join(args): # patch ranges applied = crt_series.get_applied() unapplied = crt_series.get_unapplied() patches = parse_patches(args, applied + unapplied + \ crt_series.get_hidden(), len(applied)) else: # individual patches or commit ids patches = args if not options.stat: options.diff_flags.extend(color_diff_flags()) commit_ids = [git_id(crt_series, patch) for patch in patches] commit_bytes = b'\n'.join( (Run('git', 'show', *(options.diff_flags + [commit_id])) .decoding(None).raw_output()) for commit_id in commit_ids) if options.stat: commit_bytes = git.diffstat(commit_bytes).encode('utf-8') if commit_bytes: pager(commit_bytes) stgit-0.19/stgit/commands/sink.py000066400000000000000000000074601337022307200170540ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction __copyright__ = """ Copyright (C) 2007, Yann Dirson This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Send patches deeper down the stack' kind = 'stack' usage = ['[-t ] [-n] [--] []'] description = """ This is the opposite operation of linkstg:float[]: move the specified patches down the stack. It is for example useful to group stable patches near the bottom of the stack, where they are less likely to be impacted by the push of another patch, and from where they can be more easily committed or pushed. If no patch is specified on command-line, the current patch gets sunk. By default patches are sunk to the bottom of the stack, but the '--to' option allows one to place them under any applied patch. Sinking internally involves popping all patches (or all patches including ), then pushing the patches to sink, and then (unless '--nopush' is also given) pushing back into place the formerly-applied patches.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches)] options = [ opt('-n', '--nopush', action = 'store_true', short = 'Do not push the patches back after sinking', long = """ Do not push back on the stack the formerly-applied patches. Only the patches to sink are pushed."""), opt('-t', '--to', metavar = 'TARGET', args = [argparse.applied_patches], short = 'Sink patches below the TARGET patch', long = """ Specify a target patch to place the patches below, instead of sinking them to the bottom of the stack.""") ] + argparse.keep_option() directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Sink patches down the stack. """ stack = directory.repository.current_stack if options.to and options.to not in stack.patchorder.applied: raise common.CmdException('Cannot sink below %s since it is not applied' % options.to) if len(args) > 0: patches = common.parse_patches(args, stack.patchorder.all) else: # current patch patches = list(stack.patchorder.applied[-1:]) if not patches: raise common.CmdException('No patches to sink') if options.to and options.to in patches: raise common.CmdException('Cannot have a sinked patch as target') applied = [p for p in stack.patchorder.applied if p not in patches] if options.to: insert_idx = applied.index(options.to) else: insert_idx = 0 applied = applied[:insert_idx] + patches + applied[insert_idx:] unapplied = [p for p in stack.patchorder.unapplied if p not in patches] iw = stack.repository.default_iw clean_iw = (not options.keep and iw) or None trans = transaction.StackTransaction(stack, 'sink', check_clean_iw = clean_iw) try: trans.reorder_patches(applied, unapplied, iw = iw, allow_interactive = True) except transaction.TransactionHalted: pass return trans.run(iw) stgit-0.19/stgit/commands/squash.py000066400000000000000000000130731337022307200174110ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, utils from stgit.argparse import opt from stgit.commands import common from stgit.lib import git, transaction __copyright__ = """ Copyright (C) 2007, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Squash two or more patches into one' kind = 'stack' usage = ['[options] [--] '] description = """ Squash two or more patches, creating one big patch that contains all their changes. In more detail: 1. Pop all the given patches, plus any other patches on top of them. 2. Push the given patches in the order they were given on the command line. 3. Squash the given patches into one big patch. 4. Allow the user to edit the commit message of the new patch interactively. 5. Push the other patches that were popped in step (1). Conflicts can occur whenever we push a patch; that is, in step (2) and (5). If there are conflicts, the command will stop so that you can resolve them.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches)] options = ([opt('-n', '--name', short = 'Name of squashed patch')] + argparse.message_options(save_template = True) + argparse.hook_options()) directory = common.DirectoryHasRepositoryLib() class SaveTemplateDone(Exception): pass def _squash_patches(trans, patches, msg, save_template, no_verify=False): cd = trans.patches[patches[0]].data cd = git.CommitData(tree = cd.tree, parents = cd.parents) for pn in patches[1:]: c = trans.patches[pn] tree = trans.stack.repository.simple_merge( base = c.data.parent.data.tree, ours = cd.tree, theirs = c.data.tree) if not tree: return None cd = cd.set_tree(tree) if msg is None: msg = utils.append_comment( trans.patches[patches[0]].data.message, '\n\n'.join('%s\n\n%s' % (pn.ljust(70, '-'), trans.patches[pn].data.message) for pn in patches[1:])) if save_template: save_template(msg.encode('utf-8')) raise SaveTemplateDone() else: msg = utils.edit_string(msg, '.stgit-squash.txt') msg = utils.strip_comment(msg).strip() cd = cd.set_message(msg) if not no_verify: cd = common.run_commit_msg_hook(trans.stack.repository, cd) return cd def _squash(stack, iw, name, msg, save_template, patches, no_verify=False): # If a name was supplied on the command line, make sure it's OK. def bad_name(pn): return pn not in patches and stack.patches.exists(pn) def get_name(cd): return name or utils.make_patch_name(cd.message, bad_name) if name and bad_name(name): raise common.CmdException('Patch name "%s" already taken' % name) def make_squashed_patch(trans, new_commit_data): name = get_name(new_commit_data) trans.patches[name] = stack.repository.commit(new_commit_data) trans.unapplied.insert(0, name) trans = transaction.StackTransaction(stack, 'squash', allow_conflicts = True) push_new_patch = bool(set(patches) & set(trans.applied)) try: new_commit_data = _squash_patches(trans, patches, msg, save_template, no_verify) if new_commit_data: # We were able to construct the squashed commit # automatically. So just delete its constituent patches. to_push = trans.delete_patches(lambda pn: pn in patches) else: # Automatic construction failed. So push the patches # consecutively, so that a second construction attempt is # guaranteed to work. to_push = trans.pop_patches(lambda pn: pn in patches) for pn in patches: trans.push_patch(pn, iw) new_commit_data = _squash_patches(trans, patches, msg, save_template, no_verify) assert not trans.delete_patches(lambda pn: pn in patches) make_squashed_patch(trans, new_commit_data) # Push the new patch if necessary, and any unrelated patches we've # had to pop out of the way. if push_new_patch: trans.push_patch(get_name(new_commit_data), iw) for pn in to_push: trans.push_patch(pn, iw) except SaveTemplateDone: trans.abort(iw) return except transaction.TransactionHalted: pass return trans.run(iw) def func(parser, options, args): stack = directory.repository.current_stack patches = common.parse_patches(args, list(stack.patchorder.all)) if len(patches) < 2: raise common.CmdException('Need at least two patches') return _squash(stack, stack.repository.default_iw, options.name, options.message, options.save_template, patches, options.no_verify) stgit-0.19/stgit/commands/sync.py000066400000000000000000000134741337022307200170660ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os import re from stgit import argparse, stack, git from stgit.argparse import opt from stgit.commands.common import (CmdException, DirectoryGotoToplevel, check_local_changes, check_conflicts, check_head_top_equal, parse_patches, pop_patches, push_patches) from stgit.out import out __copyright__ = """ Copyright (C) 2006, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Synchronise patches with a branch or a series' kind = 'patch' usage = ['[options] [--] [] [] [..]'] description = """ For each of the specified patches perform a three-way merge with the same patch in the specified branch or series. The command can be used for keeping patches on several branches in sync. Note that the operation may fail for some patches because of conflicts. The patches in the series must apply cleanly.""" args = [argparse.patch_range(argparse.applied_patches, argparse.unapplied_patches)] options = [ opt('-a', '--all', action = 'store_true', short = 'Synchronise all the applied patches'), opt('-B', '--ref-branch', args = [argparse.stg_branches], short = 'Syncronise patches with BRANCH'), opt('-s', '--series', args = [argparse.files], short = 'Syncronise patches with SERIES')] directory = DirectoryGotoToplevel(log=True) crt_series = None def __check_all(): check_local_changes() check_conflicts() check_head_top_equal(crt_series) def __branch_merge_patch(remote_series, pname): """Merge a patch from a remote branch into the current tree. """ patch = remote_series.get_patch(pname) git.merge_recursive(patch.get_bottom(), git.get_head(), patch.get_top()) def __series_merge_patch(base, patchdir, pname): """Merge a patch file with the given StGIT patch. """ patchfile = os.path.join(patchdir, pname) git.apply_patch(filename = patchfile, base = base) def func(parser, options, args): """Synchronise a range of patches """ if options.ref_branch: remote_series = stack.Series(options.ref_branch) if options.ref_branch == crt_series.get_name(): raise CmdException('Cannot synchronise with the current branch') remote_patches = remote_series.get_applied() # the merge function merge_patch(patch, pname) merge_patch = lambda patch, pname: \ __branch_merge_patch(remote_series, pname) elif options.series: patchdir = os.path.dirname(options.series) remote_patches = [] with open(options.series) as f: for line in f: p = re.sub('#.*$', '', line).strip() if not p: continue remote_patches.append(p) # the merge function merge_patch(patch, pname) merge_patch = lambda patch, pname: \ __series_merge_patch(patch.get_bottom(), patchdir, pname) else: raise CmdException('No remote branch or series specified') applied = crt_series.get_applied() unapplied = crt_series.get_unapplied() if options.all: patches = applied elif len(args) != 0: patches = parse_patches(args, applied + unapplied, len(applied), ordered = True) elif applied: patches = [crt_series.get_current()] else: parser.error('no patches applied') if not patches: raise CmdException('No patches to synchronise') __check_all() # only keep the patches to be synchronised sync_patches = [p for p in patches if p in remote_patches] if not sync_patches: raise CmdException('No common patches to be synchronised') # pop to the one before the first patch to be synchronised first_patch = sync_patches[0] if first_patch in applied: to_pop = applied[applied.index(first_patch) + 1:] if to_pop: pop_patches(crt_series, to_pop[::-1]) pushed = [first_patch] else: to_pop = [] pushed = [] popped = to_pop + [p for p in patches if p in unapplied] for p in pushed + popped: if p in popped: # push this patch push_patches(crt_series, [p]) if p not in sync_patches: # nothing to synchronise continue # the actual sync out.start('Synchronising "%s"' % p) patch = crt_series.get_patch(p) top = patch.get_top() # reset the patch backup information. patch.set_top(top, backup = True) # the actual merging (either from a branch or an external file) merge_patch(patch, p) if git.local_changes(verbose = False): # index (cache) already updated by the git merge. The # backup information was already reset above crt_series.refresh_patch(cache_update = False, backup = False, log = 'sync') out.done('updated') else: out.done() stgit-0.19/stgit/commands/top.py000066400000000000000000000030701337022307200167030ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit.argparse import opt from stgit.commands import common from stgit.out import out from stgit import argparse __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Print the name of the top patch' kind = 'stack' usage = [''] description = """ Print the name of the current (topmost) patch.""" args = [] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Show the name of the topmost patch """ if len(args) != 0: parser.error('incorrect number of arguments') stack = directory.repository.get_stack(options.branch) applied = stack.patchorder.applied if applied: out.stdout(applied[-1]) else: raise common.CmdException('No patches applied') stgit-0.19/stgit/commands/uncommit.py000066400000000000000000000131771337022307200177450ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse, utils from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction from stgit.out import out __copyright__ = """ Copyright (C) 2006, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Turn regular git commits into StGit patches' kind = 'stack' usage = ['[--] [ ...]', '-n NUM [--] []', '-t [-x]'] description = """ Take one or more git commits at the base of the current stack and turn them into StGIT patches. The new patches are created as applied patches at the bottom of the stack. This is the opposite of 'stg commit'. By default, the number of patches to uncommit is determined by the number of patch names provided on the command line. First name is used for the first patch to uncommit, i.e. for the newest patch. The -n/--number option specifies the number of patches to uncommit. In this case, at most one patch name may be specified. It is used as prefix to which the patch number is appended. If no patch names are provided on the command line, StGIT automatically generates them based on the first line of the patch description. The -t/--to option specifies that all commits up to and including the given commit should be uncommitted. Only commits with exactly one parent can be uncommitted; in other words, you can't uncommit a merge.""" args = [] options = [ opt('-n', '--number', type = 'int', short = 'Uncommit the specified number of commits'), opt('-t', '--to', args = [argparse.commit], short = 'Uncommit to the specified commit'), opt('-x', '--exclusive', action = 'store_true', short = 'Exclude the commit specified by the --to option')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Uncommit a number of patches. """ stack = directory.repository.current_stack if options.to: if options.number: parser.error('cannot give both --to and --number') if len(args) != 0: parser.error('cannot specify patch name with --to') patch_nr = patchnames = None to_commit = stack.repository.rev_parse(options.to) # check whether the --to commit is on a different branch merge_bases = directory.repository.get_merge_bases(to_commit, stack.base) if to_commit not in merge_bases: to_commit = merge_bases[0] options.exclusive = True elif options.number: if options.number <= 0: parser.error('invalid value passed to --number') patch_nr = options.number if len(args) == 0: patchnames = None elif len(args) == 1: # prefix specified patchnames = ['%s%d' % (args[0], i) for i in range(patch_nr, 0, -1)] else: parser.error('when using --number, specify at most one patch name') elif len(args) == 0: patchnames = None patch_nr = 1 else: patchnames = args patch_nr = len(patchnames) def check_and_append(c, n): next = n.data.parents try: [next] = next except ValueError: out.done() raise common.CmdException( 'Trying to uncommit %s, which does not have exactly one parent' % n.sha1) return c.append(n) commits = [] next_commit = stack.base if patch_nr: out.start('Uncommitting %d patches' % patch_nr) for i in range(patch_nr): check_and_append(commits, next_commit) next_commit = next_commit.data.parent else: if options.exclusive: out.start('Uncommitting to %s (exclusive)' % to_commit.sha1) else: out.start('Uncommitting to %s' % to_commit.sha1) while True: if next_commit == to_commit: if not options.exclusive: check_and_append(commits, next_commit) break check_and_append(commits, next_commit) next_commit = next_commit.data.parent patch_nr = len(commits) taken_names = set(stack.patchorder.all) if patchnames: for pn in patchnames: if pn in taken_names: raise common.CmdException('Patch name "%s" already taken' % pn) taken_names.add(pn) else: patchnames = [] for c in reversed(commits): pn = utils.make_patch_name(c.data.message, lambda pn: pn in taken_names) patchnames.append(pn) taken_names.add(pn) patchnames.reverse() trans = transaction.StackTransaction(stack, 'uncommit', allow_conflicts = True, allow_bad_head = True) for commit, pn in zip(commits, patchnames): trans.patches[pn] = commit trans.applied = list(reversed(patchnames)) + trans.applied trans.run(set_head = False) out.done() stgit-0.19/stgit/commands/undo.py000066400000000000000000000037221337022307200170520ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit.argparse import opt from stgit.commands import common from stgit.lib import log, transaction __copyright__ = """ Copyright (C) 2008, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Undo the last operation' kind = 'stack' usage = [''] description = """ Reset the patch stack to the previous state. Consecutive invocations of "stg undo" will take you ever further into the past.""" args = [] options = [ opt('-n', '--number', type = 'int', metavar = 'N', default = 1, short = 'Undo the last N commands'), opt('--hard', action = 'store_true', short = 'Discard changes in your index/worktree')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): stack = directory.repository.current_stack if options.number < 1: raise common.CmdException('Bad number of commands to undo') state = log.undo_state(stack, options.number) trans = transaction.StackTransaction(stack, 'undo %d' % options.number, discard_changes = options.hard, allow_bad_head = True) try: log.reset_stack(trans, stack.repository.default_iw, state) except transaction.TransactionHalted: pass return trans.run(stack.repository.default_iw, allow_bad_head = True) stgit-0.19/stgit/commands/unhide.py000066400000000000000000000037111337022307200173570ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import argparse from stgit.argparse import opt from stgit.commands import common from stgit.lib import transaction __copyright__ = """ Copyright (C) 2009, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ help = 'Unhide a hidden patch' kind = 'stack' usage = ['[options] [--] '] description = """ Unhide a hidden range of patches so that they are shown in the plain 'stg series' command output.""" args = [argparse.patch_range(argparse.hidden_patches)] options = [ opt('-b', '--branch', args = [argparse.stg_branches], short = 'Use BRANCH instead of the default branch')] directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Unhide a range of patch in the series.""" stack = directory.repository.current_stack trans = transaction.StackTransaction(stack, 'unhide') if not args: parser.error('No patches specified') patches = common.parse_patches(args, trans.all_patches) for p in patches: if p not in trans.hidden: raise common.CmdException('Patch "%s" not hidden' % p) applied = list(trans.applied) unapplied = trans.unapplied + patches hidden = [p for p in trans.hidden if p not in set(patches)] trans.reorder_patches(applied, unapplied, hidden) return trans.run() stgit-0.19/stgit/compat.py000066400000000000000000000101501337022307200155600ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import email import os import sys # With unicode_literals enabled, the type of a string literal will be `unicode` # for Python 2 and `str` for Python 3. text = type('') # PEP-540 (Add a new UTF-8 mode) makes a compelling argument for Python # programs making special effort to work around misconfigured locale # settings. This largely boils down to treating incoming byte sequences, # i.e. command line arguments and environment variables, as UTF-8. # # This is specifically relevant when the POSIX (aka C) locale is in effect. # # https://www.python.org/dev/peps/pep-0540/ # # The following functions help achieve this goal by using UTF-8 as a fallback # encoding when the nominal encoding (sys.getfilesystemencoding()) fails. if sys.version_info[0] <= 2: _fs_enc = sys.getfilesystemencoding() def fsdecode_utf8(b): """Decode to filesystem encoding, with UTF-8 fallback.""" if isinstance(b, bytes): try: return b.decode(_fs_enc) except UnicodeDecodeError: return b.decode('utf-8') else: return fsdecode_utf8(fsencode_utf8(b)) def fsencode_utf8(s): """Encode to filesystem encoding, with UTF-8 fallback.""" try: return s.encode(_fs_enc) except UnicodeEncodeError: return s.encode('utf-8') def environ_get(key, default=None): b = os.environ.get(key, default) if b is default: return default else: return fsdecode_utf8(b) def environ_copy(): return dict((fsdecode_utf8(k), fsdecode_utf8(v)) for k, v in os.environ.iteritems()) else: # Python 3 def fsdecode_utf8(b): if isinstance(b, bytes): try: return os.fsdecode(b) except UnicodeDecodeError: return b.decode('utf-8') else: return os.fsencode(b).decode('utf-8') def fsencode_utf8(s): try: return os.fsencode(s) except UnicodeEncodeError: return s.encode('utf-8') def environ_get(key, default=None): s = os.environ.get(key, default) if s is default: return default else: return s.encode('utf-8', 'surrogateescape').decode('utf-8') def environ_copy(): return os.environ.copy() class file_wrapper(object): """Wrap file object with missing methods needed by TextIOWrapper.""" def __init__(self, f, readable=False, writable=False, seekable=False): self.__f = f self.__readable = readable self.__writable = writable self.__seekable = seekable def __getattr__(self, name): return getattr(self.__f, name) def readable(self): return self.__readable def writable(self): return self.__writable def seekable(self): return self.__seekable # Python 2 only has email.message_from_file(), but it behaves like Python 3's # email.message_from_binary_file(). message_from_binary_file = getattr(email, 'message_from_binary_file', email.message_from_file) message_from_bytes = getattr(email, 'message_from_bytes', email.message_from_string) def decode_utf8_with_latin1(input, errors='strict'): """Decode utf-8 bytes with possible latin-1 encoded bytes. There are cases where encoded byte streams may nominally be utf-8 encoded, but contain stray latin-1 (iso8859-1) characters. The input bytes are decoded as utf-8, but with any non-utf-8 byte sequences decoded as latin-1. This is the decode strategy employed by git when decoding utf-8 email bodies. """ s = '' while True: try: s += input.decode('utf-8', 'strict') except UnicodeDecodeError as e: _, _, start, end, _ = e.args s += input[:start].decode('utf-8') s += input[start:end].decode('latin1') input = input[end:] else: break return s stgit-0.19/stgit/completion.py000066400000000000000000000135571337022307200164640ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import itertools from stgit import argparse from stgit.compat import text import stgit.commands def fun(name, *body): return ['%s ()' % name, '{', list(body), '}'] def fun_desc(name, desc, *body): return ['# %s' % desc] + fun(name, *body) def flatten(stuff, sep): r = stuff[0] for s in stuff[1:]: r.append(sep) r.extend(s) return r def write(f, stuff, indent = 0): for s in stuff: if isinstance(s, text): f.write((' '*4*indent + s).rstrip() + '\n') else: write(f, s, indent + 1) def patch_list_fun(type): return fun('_%s_patches' % type, 'local g=$(_gitdir)', 'test "$g" && cat "$g/patches/$(_current_branch)/%s"' % type) def file_list_fun(name, cmd): return fun('_%s_files' % name, 'local g=$(_gitdir)', 'test "$g" && %s' % cmd) def ref_list_fun(name, prefix): return fun(name, 'local g=$(_gitdir)', ("test \"$g\" && git show-ref | grep ' %s/' | sed 's,.* %s/,,'" % (prefix, prefix))) def util(): r = [fun_desc('_gitdir', "The path to .git, or empty if we're not in a repository.", 'echo "$(git rev-parse --git-dir 2>/dev/null)"'), fun_desc('_current_branch', "Name of the current branch, or empty if there isn't one.", 'local b=$(git symbolic-ref HEAD 2>/dev/null)', 'echo ${b#refs/heads/}'), fun_desc('_other_applied_patches', 'List of all applied patches except the current patch.', 'local b=$(_current_branch)', 'local g=$(_gitdir)', ('test "$g" && cat "$g/patches/$b/applied" | grep -v' ' "^$(tail -n 1 $g/patches/$b/applied 2> /dev/null)$"')), fun('_patch_range', 'local patches="$1"', 'local cur="$2"', 'case "$cur" in', [ '*..*)', ['local pfx="${cur%..*}.."', 'cur="${cur#*..}"', 'compgen -P "$pfx" -W "$patches" -- "$cur"', ';;'], '*)', ['compgen -W "$patches" -- "$cur"', ';;']], 'esac'), fun('_stg_branches', 'local g=$(_gitdir)', 'test "$g" && (cd $g/patches/ && echo *)'), fun('_mail_aliases', 'git config --name-only --get-regexp "^mail\\.alias\\." | cut -d. -f 3'), ref_list_fun('_all_branches', 'refs/heads'), ref_list_fun('_tags', 'refs/tags'), ref_list_fun('_remotes', 'refs/remotes')] for type in ['applied', 'unapplied', 'hidden']: r.append(patch_list_fun(type)) for name, cmd in [('conflicting', r"git ls-files --unmerged | sed 's/.*\t//g' | sort -u"), ('dirty', 'git diff-index --name-only HEAD'), ('unknown', 'git ls-files --others --exclude-standard'), ('known', 'git ls-files')]: r.append(file_list_fun(name, cmd)) return flatten(r, '') def command_list(commands): return ['_stg_commands="%s"\n' % ' '.join(sorted(commands))] def command_fun(cmd, modname): mod = stgit.commands.get_command(modname) def cg(args, flags): return argparse.compjoin(list(args) + [argparse.strings(*flags)] ).command('$cur') return fun( '_stg_%s' % cmd, 'local flags="%s"' % ' '.join(sorted( itertools.chain( ('--help',), (flag for opt in mod.options for flag in opt.flags if flag.startswith('--'))))), 'local prev="${COMP_WORDS[COMP_CWORD-1]}"', 'local cur="${COMP_WORDS[COMP_CWORD]}"', 'case "$prev" in', [ '%s) COMPREPLY=($(%s)) ;;' % ('|'.join(opt.flags), cg(opt.args, [])) for opt in mod.options if opt.args] + [ '*) COMPREPLY=($(%s)) ;;' % cg(mod.args, ['$flags'])], 'esac') def main_switch(commands): return fun( '_stg', 'local i', 'local c=1', 'local command', '', 'while test $c -lt $COMP_CWORD; do', [ 'if test $c == 1; then', [ 'command="${COMP_WORDS[c]}"'], 'fi', 'c=$((++c))'], 'done', '', ('# Complete name of subcommand if the user has not finished' ' typing it yet.'), 'if test $c -eq $COMP_CWORD -a -z "$command"; then', [ ('COMPREPLY=($(compgen -W "help version copyright $_stg_commands" --' ' "${COMP_WORDS[COMP_CWORD]}"))'), 'return'], 'fi', '', '# Complete arguments to subcommands.', 'case "$command" in', [ 'help) ', [ ('COMPREPLY=($(compgen -W "$_stg_commands" --' ' "${COMP_WORDS[COMP_CWORD]}"))'), 'return ;;'], 'version) return ;;', 'copyright) return ;;'], [ '%s) _stg_%s ;;' % (cmd, cmd) for cmd in sorted(commands)], 'esac') def install(): return ['complete -o bashdefault -o default -F _stg stg 2>/dev/null \\', [ '|| complete -o default -F _stg stg' ] ] def write_completion(f): commands = stgit.commands.get_commands(allow_cached = False) r = [["""# -*- shell-script -*- # bash completion script for StGit (automatically generated) # # To use these routines: # # 1. Copy this file to somewhere (e.g. ~/.stgit-completion.bash). # # 2. Add the following line to your .bashrc: # . ~/.stgit-completion.bash"""]] r += [util(), command_list(commands)] for cmd, (modname, _, _) in sorted(commands.items()): r.append(command_fun(cmd, modname)) r += [main_switch(commands), install()] write(f, flatten(r, '')) if __name__ == '__main__': import sys write_completion(sys.stdout) stgit-0.19/stgit/config.py000066400000000000000000000133311337022307200155460ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Handles the Stacked GIT configuration files""" from __future__ import (absolute_import, division, print_function, unicode_literals) import os import re from stgit.exception import StgException from stgit.run import Run __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ class GitConfigException(StgException): pass class GitConfig(object): __defaults = { 'stgit.smtpserver': ['localhost:25'], 'stgit.smtpdelay': ['5'], 'stgit.pullcmd': ['git pull'], 'stgit.fetchcmd': ['git fetch'], 'stgit.pull-policy': ['pull'], 'stgit.autoimerge': ['no'], 'stgit.keepoptimized': ['no'], 'stgit.refreshsubmodules': ['no'], 'stgit.shortnr': ['5'], 'stgit.pager': ['less'], 'stgit.alias.add': ['git add'], 'stgit.alias.rm': ['git rm'], 'stgit.alias.mv': ['git mv'], 'stgit.alias.resolved': ['git add'], 'stgit.alias.status': ['git status -s'] } __cache = None def load(self): """Load the whole configuration in __cache unless it has been done already.""" if self.__cache is not None: return self.__cache = self.__defaults lines = Run('git', 'config', '--null', '--list' ).discard_exitcode().output_lines('\0') for line in lines: try: key, value = line.split('\n', 1) except ValueError: key = line value = None self.__cache.setdefault(key, []).append(value) def get(self, name): self.load() try: return self.__cache[name][-1] except KeyError: return None def getall(self, name): self.load() try: return self.__cache[name] except KeyError: return [] def getint(self, name): value = self.get(name) if value is None: return None elif value.isdigit(): return int(value) else: raise GitConfigException('Value for "%s" is not an integer: "%s"' % (name, value)) def getbool(self, name): """Report the canonicalized boolean value for a given key.""" # We cannot directly call get() because we need to use the KeyError in # order to distinguish between the case of a key with an undefined # value, and a completely undefined key. Git expects the former to be # reported as "true". self.load() try: value = self.__cache[name][-1] except KeyError: return None if value is None: # The key is defined, but the value is not, so treat it as true. return True elif value in ['yes', 'on', 'true']: return True elif value in ['no', 'off', 'false', '']: return False elif value.isdigit(): return bool(value) else: raise GitConfigException('Value for "%s" is not a booleain: "%s"' % (name, value)) def getstartswith(self, name): self.load() return ((n, v[-1]) for (n, v) in self.__cache.items() if n.startswith(name)) def rename_section(self, from_name, to_name): """Rename a section in the config file. Silently do nothing if the section doesn't exist.""" Run('git', 'config', '--rename-section', from_name, to_name ).returns([0, 1, 128]).run() self.__cache.clear() def remove_section(self, name): """Remove a section in the config file. Silently do nothing if the section doesn't exist.""" Run('git', 'config', '--remove-section', name ).returns([0, 1, 128]).discard_stderr().discard_output() self.__cache.clear() def set(self, name, value): Run('git', 'config', name, value).run() self.__cache[name] = value def unset(self, name): Run('git', 'config', '--unset', name).run() self.__cache[name] = [None] def sections_matching(self, regexp): """Takes a regexp with a single group, matches it against all config variables, and returns a list whose members are the group contents, for all variable names matching the regexp. """ result = [] for line in Run('git', 'config', '--get-regexp', '"^%s$"' % regexp ).returns([0, 1]).output_lines(): m = re.match('^%s ' % regexp, line) if m: result.append(m.group(1)) return result def get_colorbool(self, name, stdout_is_tty): """Invoke 'git config --get-colorbool' and return the result.""" return Run('git', 'config', '--get-colorbool', name, stdout_is_tty).output_one_line() config = GitConfig() def config_setup(): global config os.environ.setdefault('PAGER', config.get('stgit.pager')) os.environ.setdefault('LESS', '-FRSX') # FIXME: handle EDITOR the same way ? stgit-0.19/stgit/exception.py000066400000000000000000000004531337022307200163000ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) class StgException(Exception): """Base class for all StGit exceptions.""" class StackException(StgException): """Exception raised by L{stack} objects.""" stgit-0.19/stgit/git.py000066400000000000000000000655621337022307200151010ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Python GIT interface""" from __future__ import (absolute_import, division, print_function, unicode_literals) import io import os import re import sys from stgit import basedir from stgit.compat import environ_get from stgit.config import config from stgit.exception import StgException from stgit.out import out from stgit.run import Run from stgit.utils import rename, strip_prefix __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ # git exception class class GitException(StgException): pass # When a subprocess has a problem, we want the exception to be a # subclass of GitException. class GitRunException(GitException): pass class GRun(Run): exc = GitRunException def __init__(self, *cmd): """Initialise the Run object and insert the 'git' command name. """ Run.__init__(self, 'git', *cmd) # # Classes # class Person(object): """An author, committer, etc.""" def __init__(self, name = None, email = None, date = '', desc = None): self.name = self.email = self.date = None if name or email or date: assert not desc self.name = name self.email = email self.date = date elif desc: assert not (name or email or date) def parse_desc(s): m = re.match(r'^(.+)<(.+)>(.*)$', s) assert m return [x.strip() or None for x in m.groups()] self.name, self.email, self.date = parse_desc(desc) def set_name(self, val): if val: self.name = val def set_email(self, val): if val: self.email = val def set_date(self, val): if val: self.date = val def __str__(self): if self.name and self.email: return '%s <%s>' % (self.name, self.email) else: raise GitException('not enough identity data') class Commit(object): """Handle the commit objects """ def __init__(self, id_hash): self.__id_hash = id_hash lines = GRun('cat-file', 'commit', id_hash).output_lines() for i in range(len(lines)): line = lines[i] if not line: break # we've seen all the header fields key, val = line.split(' ', 1) if key == 'tree': self.__tree = val elif key == 'author': self.__author = val elif key == 'committer': self.__committer = val else: pass # ignore other headers self.__log = '\n'.join(lines[i+1:]) def get_id_hash(self): return self.__id_hash def get_tree(self): return self.__tree def get_parent(self): parents = self.get_parents() if parents: return parents[0] else: return None def get_parents(self): return GRun('rev-list', '--parents', '--max-count=1', self.__id_hash ).output_one_line().split()[1:] def get_author(self): return self.__author def get_committer(self): return self.__committer def get_log(self): return self.__log def __str__(self): return self.get_id_hash() # dictionary of Commit objects, used to avoid multiple calls to git __commits = dict() # # Functions # def get_commit(id_hash): """Commit objects factory. Save/look-up them in the __commits dictionary """ global __commits if id_hash in __commits: return __commits[id_hash] else: commit = Commit(id_hash) __commits[id_hash] = commit return commit def get_conflicts(): """Return the list of file conflicts """ names = set() for line in GRun('ls-files', '-z', '--unmerged').output_lines('\0'): stat, path = line.split('\t', 1) names.add(path) return list(names) def ls_files(files, tree = 'HEAD', full_name = True): """Return the files known to GIT or raise an error otherwise. It also converts the file to the full path relative the the .git directory. """ if not files: return [] args = [] if tree: args.append('--with-tree=%s' % tree) if full_name: args.append('--full-name') args.append('--') args.extend(files) try: # use a set to avoid file names duplication due to different stages fileset = set(GRun('ls-files', '--error-unmatch', *args).output_lines()) except GitRunException: # just hide the details of the 'git ls-files' command we use raise GitException( 'Some of the given paths are either missing or not known to GIT') return list(fileset) def parse_git_ls(lines): """Parse the output of git diff-index, diff-files, etc. Doesn't handle rename/copy output, so don't feed it output generated with the -M or -C flags.""" t = None for line in lines: if t is None: mode_a, mode_b, sha1_a, sha1_b, t = line.split(' ') else: yield (t, line) t = None def tree_status(files=None, tree_id='HEAD', verbose=False): """Get the status of all changed files, or of a selected set of files. Returns a list of pairs - (status, filename). If 'not files', it will check all files. If 'files' is a list, it will only check the files in the list. """ if verbose: out.start('Checking for changes in the working directory') refresh_index() if files is None: files = [] cache_files = [] # conflicted files conflicts = get_conflicts() cache_files += [('C', filename) for filename in conflicts if not files or filename in files] reported_files = set(conflicts) files_left = [f for f in files if f not in reported_files] # files in the index. Only execute this code if no files were # specified when calling the function (i.e. report all files) or # files were specified but already found in the previous step if not files or files_left: args = [tree_id] if files_left: args += ['--'] + files_left diff_index_lines = GRun('diff-index', '-z', *args).output_lines('\0') for t, fn in parse_git_ls(diff_index_lines): # the condition is needed in case files is emtpy and # diff-index lists those already reported if fn not in reported_files: cache_files.append((t, fn)) reported_files.add(fn) files_left = [f for f in files if f not in reported_files] # files in the index but changed on (or removed from) disk. Only # execute this code if no files were specified when calling the # function (i.e. report all files) or files were specified but # already found in the previous step if not files or files_left: args = [] if files_left: args += ['--'] + files_left diff_files_lines = GRun('diff-files', '-z', *args).output_lines('\0') for t, fn in parse_git_ls(diff_files_lines): # the condition is needed in case files is empty and # diff-files lists those already reported if fn not in reported_files: cache_files.append((t, fn)) reported_files.add(fn) if verbose: out.done() return cache_files def local_changes(verbose = True): """Return true if there are local changes in the tree """ return len(tree_status(verbose = verbose)) != 0 def get_heads(): heads = [] hr = re.compile(r'^[0-9a-f]{40} refs/heads/(.+)$') for line in GRun('show-ref', '--heads').output_lines(): m = hr.match(line) heads.append(m.group(1)) return heads # HEAD value cached __head = None def get_head(): """Verifies the HEAD and returns the SHA1 id that represents it """ global __head if not __head: __head = rev_parse('HEAD') return __head class DetachedHeadException(GitException): def __init__(self): GitException.__init__(self, 'Not on any branch') def get_head_file(): """Return the name of the file pointed to by the HEAD symref. Throw an exception if HEAD is detached.""" try: return strip_prefix( 'refs/heads/', GRun('symbolic-ref', '-q', 'HEAD' ).output_one_line()) except GitRunException: raise DetachedHeadException() def set_head_file(ref): """Resets HEAD to point to a new ref """ # head cache flushing is needed since we might have a different value # in the new head __clear_head_cache() try: GRun('symbolic-ref', 'HEAD', 'refs/heads/%s' % ref).run() except GitRunException: raise GitException('Could not set head to "%s"' % ref) def set_ref(ref, val): """Point ref at a new commit object.""" try: GRun('update-ref', ref, val).run() except GitRunException: raise GitException('Could not update %s to "%s".' % (ref, val)) def set_branch(branch, val): set_ref('refs/heads/%s' % branch, val) def __set_head(val): """Sets the HEAD value """ global __head if not __head or __head != val: set_ref('HEAD', val) __head = val # only allow SHA1 hashes assert(len(__head) == 40) def __clear_head_cache(): """Sets the __head to None so that a re-read is forced """ global __head __head = None def refresh_index(): """Refresh index with stat() information from the working directory. """ GRun('update-index', '-q', '--unmerged', '--refresh').run() def rev_parse(git_id): """Parse the string and return a verified SHA1 id """ try: return GRun('rev-parse', '--verify', git_id ).discard_stderr().output_one_line() except GitRunException: raise GitException('Unknown revision: %s' % git_id) def ref_exists(ref): try: rev_parse(ref) return True except GitException: return False def branch_exists(branch): return ref_exists('refs/heads/%s' % branch) def create_branch(new_branch, tree_id = None): """Create a new branch in the git repository """ if branch_exists(new_branch): raise GitException('Branch "%s" already exists' % new_branch) current_head_file = get_head_file() current_head = get_head() set_head_file(new_branch) __set_head(current_head) # a checkout isn't needed if new branch points to the current head if tree_id: try: switch(tree_id) except GitException: # Tree switching failed. Revert the head file set_head_file(current_head_file) delete_branch(new_branch) raise if os.path.isfile(os.path.join(basedir.get(), 'MERGE_HEAD')): os.remove(os.path.join(basedir.get(), 'MERGE_HEAD')) def switch_branch(new_branch): """Switch to a git branch """ global __head if not branch_exists(new_branch): raise GitException('Branch "%s" does not exist' % new_branch) tree_id = rev_parse('refs/heads/%s^{commit}' % new_branch) if tree_id != get_head(): refresh_index() try: GRun('read-tree', '-u', '-m', get_head(), tree_id).run() except GitRunException: raise GitException('read-tree failed (local changes maybe?)') __head = tree_id set_head_file(new_branch) if os.path.isfile(os.path.join(basedir.get(), 'MERGE_HEAD')): os.remove(os.path.join(basedir.get(), 'MERGE_HEAD')) def delete_ref(ref): if not ref_exists(ref): raise GitException('%s does not exist' % ref) sha1 = GRun('show-ref', '-s', ref).output_one_line() try: GRun('update-ref', '-d', ref, sha1).run() except GitRunException: raise GitException('Failed to delete ref %s' % ref) def delete_branch(name): delete_ref('refs/heads/%s' % name) def rename_ref(from_ref, to_ref): if not ref_exists(from_ref): raise GitException('"%s" does not exist' % from_ref) if ref_exists(to_ref): raise GitException('"%s" already exists' % to_ref) sha1 = GRun('show-ref', '-s', from_ref).output_one_line() try: GRun('update-ref', to_ref, sha1, '0'*40).run() except GitRunException: raise GitException('Failed to create new ref %s' % to_ref) try: GRun('update-ref', '-d', from_ref, sha1).run() except GitRunException: raise GitException('Failed to delete ref %s' % from_ref) def rename_branch(from_name, to_name): """Rename a git branch.""" rename_ref('refs/heads/%s' % from_name, 'refs/heads/%s' % to_name) try: if get_head_file() == from_name: set_head_file(to_name) except DetachedHeadException: pass # detached HEAD, so the renamee can't be the current branch reflog_dir = os.path.join(basedir.get(), 'logs', 'refs', 'heads') if os.path.exists(reflog_dir) \ and os.path.exists(os.path.join(reflog_dir, from_name)): rename(reflog_dir, from_name, to_name) # Persons caching __user = None __author = None __committer = None def user(): """Return the user information. """ global __user if not __user: name=config.get('user.name') email=config.get('user.email') __user = Person(name, email) return __user def author(): """Return the author information. """ global __author if not __author: # the environment variables take priority over config name = environ_get('GIT_AUTHOR_NAME') email = environ_get('GIT_AUTHOR_EMAIL') if name is None or email is None: __author = user() else: date = environ_get('GIT_AUTHOR_DATE', '') __author = Person(name, email, date) return __author def committer(): """Return the author information. """ global __committer if not __committer: # the environment variables take priority over config name = environ_get('GIT_COMMITTER_NAME') email = environ_get('GIT_COMMITTER_EMAIL') if name is None or email is None: __committer = user() else: date = environ_get('GIT_COMMITTER_DATE', '') __committer = Person(name, email, date) return __committer def update_cache(files = None, force = False): """Update the cache information for the given files """ cache_files = tree_status(files, verbose = False) # everything is up-to-date if len(cache_files) == 0: return False # check for unresolved conflicts if not force and [x for x in cache_files if x[0] not in ['M', 'N', 'A', 'D']]: raise GitException('Updating cache failed: unresolved conflicts') # update the cache add_files = [x[1] for x in cache_files if x[0] in ['N', 'A']] rm_files = [x[1] for x in cache_files if x[0] in ['D']] m_files = [x[1] for x in cache_files if x[0] in ['M']] GRun('update-index', '--add', '--').xargs(add_files) GRun('update-index', '--force-remove', '--').xargs(rm_files) GRun('update-index', '--').xargs(m_files) return True def commit(message, files = None, parents = None, allowempty = False, cache_update = True, tree_id = None, set_head = False, author_name = None, author_email = None, author_date = None, committer_name = None, committer_email = None): """Commit the current tree to repository """ if not parents: parents = [] # Get the tree status if cache_update and parents != []: changes = update_cache(files) if not changes and not allowempty: raise GitException('No changes to commit') # get the commit message if not message: message = '\n' elif message[-1:] != '\n': message += '\n' # write the index to repository if tree_id is None: tree_id = GRun('write-tree').output_one_line() set_head = True # the commit env = {} if author_name: env['GIT_AUTHOR_NAME'] = author_name if author_email: env['GIT_AUTHOR_EMAIL'] = author_email if author_date: env['GIT_AUTHOR_DATE'] = author_date if committer_name: env['GIT_COMMITTER_NAME'] = committer_name if committer_email: env['GIT_COMMITTER_EMAIL'] = committer_email commit_id = GRun('commit-tree', tree_id, *sum([['-p', p] for p in parents], []) ).env(env).raw_input(message).output_one_line() if set_head: __set_head(commit_id) return commit_id def apply_diff(rev1, rev2, check_index = True, files = None): """Apply the diff between rev1 and rev2 onto the current index. This function doesn't need to raise an exception since it is only used for fast-pushing a patch. If this operation fails, the pushing would fall back to the three-way merge. """ if check_index: index_opt = ['--index'] else: index_opt = [] if not files: files = [] diff_str = diff(files, rev1, rev2) if diff_str: try: GRun('apply', *index_opt).encoding(None).raw_input( diff_str).discard_stderr().no_output() except GitRunException: return False return True stages_re = re.compile('^([0-7]+) ([0-9a-f]{40}) ([1-3])\t(.*)$', re.S) def merge_recursive(base, head1, head2): """Perform a 3-way merge between base, head1 and head2 into the local tree """ refresh_index() p = GRun('merge-recursive', base, '--', head1, head2).env( { 'GITHEAD_%s' % base: 'ancestor', 'GITHEAD_%s' % head1: 'current', 'GITHEAD_%s' % head2: 'patched'}).returns([0, 1]) output = p.output_lines() if p.exitcode: # There were conflicts if config.getbool('stgit.autoimerge'): mergetool() else: conflicts = [l for l in output if l.startswith('CONFLICT')] out.info(*conflicts) raise GitException("%d conflict(s)" % len(conflicts)) def mergetool(files = ()): """Invoke 'git mergetool' to resolve any outstanding conflicts. If 'not files', all the files in an unmerged state will be processed.""" GRun('mergetool', *list(files)).returns([0, 1]).run() # check for unmerged entries (prepend 'CONFLICT ' for consistency with # merge_recursive()) conflicts = ['CONFLICT ' + f for f in get_conflicts()] if conflicts: out.info(*conflicts) raise GitException("%d conflict(s)" % len(conflicts)) def diff(files = None, rev1 = 'HEAD', rev2 = None, diff_flags = [], binary = True): """Show the diff between rev1 and rev2 """ if not files: files = [] if binary and '--binary' not in diff_flags: diff_flags = diff_flags + ['--binary'] if rev1 and rev2: runner = GRun('diff-tree', '-p', *(diff_flags + [rev1, rev2, '--'] + files)) return runner.decoding(None).raw_output() elif rev1 or rev2: refresh_index() if rev2: runner = GRun('diff-index', '-p', '-R', *(diff_flags + [rev2, '--'] + files)) else: runner = GRun('diff-index', '-p', *(diff_flags + [rev1, '--'] + files)) return runner.decoding(None).raw_output() else: return b'' def files(rev1, rev2, diff_flags = []): """Return the files modified between rev1 and rev2 """ result = [] for line in GRun('diff-tree', *(diff_flags + ['-r', rev1, rev2]) ).output_lines(): result.append('%s %s' % tuple(line.split(' ', 4)[-1].split('\t', 1))) return '\n'.join(result) def barefiles(rev1, rev2): """Return the files modified between rev1 and rev2, without status info """ result = [] for line in GRun('diff-tree', '-r', rev1, rev2).output_lines(): result.append(line.split(' ', 4)[-1].split('\t', 1)[-1]) return '\n'.join(result) def checkout(tree_id): """Check out the given tree_id """ try: GRun('read-tree', '--reset', '-u', tree_id).run() except GitRunException: raise GitException('Failed "git read-tree" --reset %s' % tree_id) def switch(tree_id, keep = False): """Switch the tree to the given id """ if keep: # only update the index while keeping the local changes GRun('read-tree', tree_id).run() else: refresh_index() try: GRun('read-tree', '-u', '-m', get_head(), tree_id).run() except GitRunException: raise GitException('read-tree failed (local changes maybe?)') __set_head(tree_id) def reset(tree_id = None): """Revert the tree changes relative to the given tree_id. It removes any local changes """ if not tree_id: tree_id = get_head() checkout(tree_id) __set_head(tree_id) def fetch(repository = 'origin', refspec = None): """Fetches changes from the remote repository, using 'git fetch' by default. """ # we update the HEAD __clear_head_cache() args = [repository] if refspec: args.append(refspec) command = config.get('branch.%s.stgit.fetchcmd' % get_head_file()) or \ config.get('stgit.fetchcmd') Run(*(command.split() + args)).run() def pull(repository = 'origin', refspec = None): """Fetches changes from the remote repository, using 'git pull' by default. """ # we update the HEAD __clear_head_cache() args = [repository] if refspec: args.append(refspec) command = config.get('branch.%s.stgit.pullcmd' % get_head_file()) or \ config.get('stgit.pullcmd') Run(*(command.split() + args)).run() def rebase(tree_id = None): """Rebase the current tree to the give tree_id. The tree_id argument may be something other than a GIT id if an external command is invoked. """ command = config.get('branch.%s.stgit.rebasecmd' % get_head_file()) \ or config.get('stgit.rebasecmd') if tree_id: args = [tree_id] elif command: args = [] else: raise GitException('Default rebasing requires a commit id') if command: # clear the HEAD cache as the custom rebase command will update it __clear_head_cache() Run(*(command.split() + args)).run() else: # default rebasing reset(tree_id) def repack(): """Repack all objects into a single pack """ GRun('repack', '-a', '-d', '-f').run() def apply_patch(filename = None, diff = None, base = None, reject = False, strip = None): """Apply a patch onto the current or given index. There must not be any local changes in the tree, otherwise the command fails """ if diff is None: if filename: with io.open(filename, 'rb') as f: diff = f.read() else: if hasattr(sys.stdin, 'buffer'): diff = sys.stdin.buffer.read() else: diff = sys.stdin.read() if base: orig_head = get_head() switch(base) else: refresh_index() cmd = ['apply', '--index'] if reject: cmd += ['--reject'] if strip is not None: cmd += ['-p%s' % (strip,)] try: GRun(*cmd).encoding(None).raw_input(diff).no_output() except GitRunException: if base: switch(orig_head) raise GitException('Diff does not apply cleanly') if base: top = commit(message = 'temporary commit used for applying a patch', parents = [base]) switch(orig_head) merge_recursive(base, orig_head, top) def modifying_revs(files, base_rev, head_rev): """Return the revisions from the list modifying the given files.""" return GRun('rev-list', '%s..%s' % (base_rev, head_rev), '--', *files ).output_lines() def refspec_localpart(refspec): m = re.match('^[^:]*:([^:]*)$', refspec) if m: return m.group(1) else: raise GitException('Cannot parse refspec "%s"' % refspec) def __remotes_from_config(): return config.sections_matching(r'remote\.(.*)\.url') def __remotes_from_dir(dir): d = os.path.join(basedir.get(), dir) if os.path.exists(d): return os.listdir(d) else: return [] def remotes_list(): """Return the list of remotes in the repository """ return (set(__remotes_from_config()) | set(__remotes_from_dir('remotes')) | set(__remotes_from_dir('branches'))) def remotes_local_branches(remote): """Returns the list of local branches fetched from given remote """ branches = [] if remote in __remotes_from_config(): for line in config.getall('remote.%s.fetch' % remote): branches.append(refspec_localpart(line)) elif remote in __remotes_from_dir('remotes'): stream = open(os.path.join(basedir.get(), 'remotes', remote), 'r') for line in stream: # Only consider Pull lines m = re.match('^Pull: (.*)\n$', line) if m: branches.append(refspec_localpart(m.group(1))) stream.close() elif remote in __remotes_from_dir('branches'): # old-style branches only declare one branch branches.append('refs/heads/'+remote) else: raise GitException('Unknown remote "%s"' % remote) return branches def identify_remote(branchname): """Return the name for the remote to pull the given branchname from, or None if we believe it is a local branch. """ for remote in remotes_list(): if branchname in remotes_local_branches(remote): return remote # if we get here we've found nothing, the branch is a local one return None def fetch_head(): """Return the git id for the tip of the parent branch as left by 'git fetch'. """ fetch_head=None stream = open(os.path.join(basedir.get(), 'FETCH_HEAD'), "r") for line in stream: # Only consider lines not tagged not-for-merge m = re.match('^([^\t]*)\t\t', line) if m: if fetch_head: raise GitException('StGit does not support multiple FETCH_HEAD') else: fetch_head=m.group(1) stream.close() if not fetch_head: out.warn('No for-merge remote head found in FETCH_HEAD') # here we are sure to have a single fetch_head return fetch_head def all_refs(): """Return a list of all refs in the current repository. """ return [line.split()[1] for line in GRun('show-ref').output_lines()] stgit-0.19/stgit/lib/000077500000000000000000000000001337022307200144745ustar00rootroot00000000000000stgit-0.19/stgit/lib/__init__.py000066400000000000000000000013721337022307200166100ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) __copyright__ = """ Copyright (C) 2007, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ stgit-0.19/stgit/lib/edit.py000066400000000000000000000106011337022307200157710ustar00rootroot00000000000000# -*- coding: utf-8 -*- """This module contains utility functions for patch editing.""" from __future__ import (absolute_import, division, print_function, unicode_literals) from stgit import utils from stgit.commands import common from stgit.lib import git def update_patch_description(repo, cd, text, contains_diff): """Update the given L{CommitData} with the given text description, which may contain author name and time stamp in addition to a new commit message. If C{contains_diff} is true, it may also contain a replacement diff. Return a pair: the new L{CommitData}; and the diff text if it didn't apply, or C{None} otherwise.""" (message, authname, authemail, authdate, diff ) = common.parse_patch(text, contains_diff) a = cd.author for val, setter in [(authname, 'set_name'), (authemail, 'set_email'), (git.Date.maybe(authdate), 'set_date')]: if val is not None: a = getattr(a, setter)(val) cd = cd.set_message(message).set_author(a) failed_diff = None if diff: tree = repo.apply(cd.parent.data.tree, diff, quiet = False) if tree is None: failed_diff = diff else: cd = cd.set_tree(tree) return cd, failed_diff def patch_desc(repo, cd, append_diff, diff_flags, replacement_diff): """Return a description text for the patch, suitable for editing and/or reimporting with L{update_patch_description()}. @param cd: The L{CommitData} to generate a description of @param append_diff: Whether to append the patch diff to the description @type append_diff: C{bool} @param diff_flags: Extra parameters to pass to C{git diff} @param replacement_diff: Diff text to use; or C{None} if it should be computed from C{cd} @type replacement_diff: C{str} or C{None}""" desc = '\n'.join([ 'From: %s <%s>' % (cd.author.name, cd.author.email), 'Date: %s' % cd.author.date.isoformat(), '', cd.message]).encode('utf-8') if append_diff: if replacement_diff: diff = replacement_diff else: just_diff = repo.diff_tree(cd.parent.data.tree, cd.tree, diff_flags) diff = b'\n'.join([git.diffstat(just_diff).encode('utf-8'), just_diff]) desc += b'\n'.join([b'', b'---', b'', diff]) return desc def interactive_edit_patch(repo, cd, edit_diff, diff_flags, replacement_diff): """Edit the patch interactively. If C{edit_diff} is true, edit the diff as well. If C{replacement_diff} is not C{None}, it contains a diff to edit instead of the patch's real diff. Return a pair: the new L{CommitData}; and the diff text if it didn't apply, or C{None} otherwise.""" return update_patch_description( repo, cd, utils.edit_bytes( patch_desc(repo, cd, edit_diff, diff_flags, replacement_diff), '.stgit-edit.' + ['txt', 'patch'][bool(edit_diff)]), edit_diff) def auto_edit_patch(repo, cd, msg, contains_diff, author, committer, sign_str): """Edit the patch noninteractively in a couple of ways: - If C{msg} is not C{None}, parse it to find a replacement message, and possibly also replacement author and timestamp. If C{contains_diff} is true, also look for a replacement diff. - C{author} and C{committer} are two functions that take the original L{Person} value as argument, and return the new one. - C{sign_str}, if not C{None}, is a sign string to append to the message. Return a pair: the new L{CommitData}; and the diff text if it didn't apply, or C{None} otherwise.""" if msg is None: failed_diff = None else: cd, failed_diff = update_patch_description(repo, cd, msg, contains_diff) a, c = author(cd.author), committer(cd.committer) if (a, c) != (cd.author, cd.committer): cd = cd.set_author(a).set_committer(c) if sign_str is not None: cd = cd.set_message(utils.add_sign_line( cd.message, sign_str, git.Person.committer().name, git.Person.committer().email)) return cd, failed_diff stgit-0.19/stgit/lib/git.py000066400000000000000000001244441337022307200156420ustar00rootroot00000000000000# -*- coding: utf-8 -*- """A Python class hierarchy wrapping a git repository and its contents.""" from __future__ import (absolute_import, division, print_function, unicode_literals) from datetime import datetime, timedelta, tzinfo import atexit import os import re import signal from stgit import exception, utils from stgit.run import Run, RunException from stgit.compat import environ_get, text from stgit.config import config class Immutable(object): """I{Immutable} objects cannot be modified once created. Any modification methods will return a new object, leaving the original object as it was. The reason for this is that we want to be able to represent git objects, which are immutable, and want to be able to create new git objects that are just slight modifications of other git objects. (Such as, for example, modifying the commit message of a commit object while leaving the rest of it intact. This involves creating a whole new commit object that's exactly like the old one except for the commit message.) The L{Immutable} class doesn't actually enforce immutability -- that is up to the individual immutable subclasses. It just serves as documentation.""" class RepositoryException(exception.StgException): """Base class for all exceptions due to failed L{Repository} operations.""" class BranchException(exception.StgException): """Exception raised by failed L{Branch} operations.""" class DateException(exception.StgException): """Exception raised when a date+time string could not be parsed.""" def __init__(self, string, type): exception.StgException.__init__( self, '"%s" is not a valid %s' % (string, type)) class DetachedHeadException(RepositoryException): """Exception raised when HEAD is detached (that is, there is no current branch).""" def __init__(self): RepositoryException.__init__(self, 'Not on any branch') class Repr(object): """Utility class that defines C{__reps__} in terms of C{__str__}.""" def __repr__(self): return str(self) class NoValue(object): """A handy default value that is guaranteed to be distinct from any real argument value.""" pass def make_defaults(defaults): def d(val, attr, default_fun = lambda: None): if val != NoValue: return val elif defaults != NoValue: return getattr(defaults, attr) else: return default_fun() return d class TimeZone(tzinfo, Repr): """A simple time zone class for static offsets from UTC. (We have to define our own since Python's standard library doesn't define any time zone classes.)""" def __init__(self, tzstring): m = re.match(r'^([+-])(\d{2}):?(\d{2})$', tzstring) if not m: raise DateException(tzstring, 'time zone') sign = int(m.group(1) + '1') try: self.__offset = timedelta(hours = sign*int(m.group(2)), minutes = sign*int(m.group(3))) except OverflowError: raise DateException(tzstring, 'time zone') self.__name = tzstring def utcoffset(self, dt): return self.__offset def tzname(self, dt): return self.__name def dst(self, dt): return timedelta(0) def __str__(self): return self.__name def system_date(datestring): m = re.match(r"^(.+)([+-]\d\d:?\d\d)$", datestring) if m: # Time zone included; we parse it ourselves, since "date" # would convert it to the local time zone. (ds, z) = m.groups() try: t = Run("date", "+%Y-%m-%d-%H-%M-%S", "-d", ds ).output_one_line() except RunException: return None else: # Time zone not included; we ask "date" to provide it for us. try: d = Run("date", "+%Y-%m-%d-%H-%M-%S_%z", "-d", datestring ).output_one_line() except RunException: return None (t, z) = d.split("_") year, month, day, hour, minute, second = [int(x) for x in t.split("-")] try: return datetime(year, month, day, hour, minute, second, tzinfo=TimeZone(z)) except ValueError: raise DateException(datestring, "date") class Date(Immutable, Repr): """Represents a timestamp used in git commits.""" def __init__(self, datestring): # Try git-formatted date. m = re.match(r'^(\d+)\s+([+-]\d\d:?\d\d)$', datestring) if m: try: self.__time = datetime.fromtimestamp(int(m.group(1)), TimeZone(m.group(2))) except ValueError: raise DateException(datestring, 'date') return # Try iso-formatted date. m = re.match(r'^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})\s+' + r'([+-]\d\d:?\d\d)$', datestring) if m: try: self.__time = datetime( *[int(m.group(i + 1)) for i in range(6)], **{'tzinfo': TimeZone(m.group(7))}) except ValueError: raise DateException(datestring, 'date') return # Try parsing with the system's "date" command. sd = system_date(datestring) if sd: self.__time = sd return raise DateException(datestring, 'date') def __str__(self): return self.isoformat() def isoformat(self): """Human-friendly ISO 8601 format.""" return '%s %s' % (self.__time.replace(tzinfo=None).isoformat(str(' ')), self.__time.tzinfo) @classmethod def maybe(cls, datestring): """Return a new object initialized with the argument if it contains a value (otherwise, just return the argument).""" if datestring in [None, NoValue]: return datestring return cls(datestring) class Person(Immutable, Repr): """Represents an author or committer in a git commit object. Contains name, email and timestamp.""" def __init__(self, name = NoValue, email = NoValue, date = NoValue, defaults = NoValue): d = make_defaults(defaults) self.__name = d(name, 'name') self.__email = d(email, 'email') self.__date = d(date, 'date') assert isinstance(self.__date, Date) or self.__date in [None, NoValue] @property def name(self): return self.__name @property def email(self): return self.__email @property def name_email(self): return '%s <%s>' % (self.name, self.email) @property def date(self): return self.__date def set_name(self, name): return type(self)(name = name, defaults = self) def set_email(self, email): return type(self)(email = email, defaults = self) def set_date(self, date): return type(self)(date = date, defaults = self) def __str__(self): return '%s %s' % (self.name_email, self.date) @classmethod def parse(cls, s): m = re.match(r'^([^<]*)<([^>]*)>\s+(\d+\s+[+-]\d{4})$', s) assert m name = m.group(1).strip() email = m.group(2) date = Date(m.group(3)) return cls(name, email, date) @classmethod def user(cls): if not hasattr(cls, '__user'): cls.__user = cls(name = config.get('user.name'), email = config.get('user.email')) return cls.__user @classmethod def author(cls): if not hasattr(cls, '__author'): cls.__author = cls( name=environ_get('GIT_AUTHOR_NAME', NoValue), email=environ_get('GIT_AUTHOR_EMAIL', NoValue), date=Date.maybe(environ_get('GIT_AUTHOR_DATE', NoValue)), defaults=cls.user()) return cls.__author @classmethod def committer(cls): if not hasattr(cls, '__committer'): cls.__committer = cls( name=environ_get('GIT_COMMITTER_NAME', NoValue), email=environ_get('GIT_COMMITTER_EMAIL', NoValue), date=Date.maybe(environ_get('GIT_COMMITTER_DATE', NoValue)), defaults=cls.user()) return cls.__committer class GitObject(Immutable, Repr): """Base class for all git objects. One git object is represented by at most one C{GitObject}, which makes it possible to compare them using normal Python object comparison; it also ensures we don't waste more memory than necessary.""" class BlobData(Immutable, Repr): """Represents the data contents of a git blob object.""" def __init__(self, data): assert isinstance(data, bytes) self.__bytes = data @property def bytes(self): return self.__bytes def commit(self, repository): """Commit the blob. @return: The committed blob @rtype: L{Blob}""" runner = repository.run(['git', 'hash-object', '-w', '--stdin']) sha1 = runner.encoding(None).raw_input(self.bytes).output_one_line() return repository.get_blob(sha1) class Blob(GitObject): """Represents a git blob object. All the actual data contents of the blob object is stored in the L{data} member, which is a L{BlobData} object.""" typename = 'blob' default_perm = '100644' def __init__(self, repository, sha1): self.__repository = repository self.__sha1 = sha1 @property def sha1(self): return self.__sha1 def __str__(self): return 'Blob<%s>' % self.sha1 @property def data(self): return BlobData(self.__repository.cat_object(self.sha1, encoding=None)) class ImmutableDict(dict): """A dictionary that cannot be modified once it's been created.""" def error(*args, **kwargs): raise TypeError('Cannot modify immutable dict') __delitem__ = error __setitem__ = error clear = error pop = error popitem = error setdefault = error update = error class TreeData(Immutable, Repr): """Represents the data contents of a git tree object.""" @staticmethod def __x(po): if isinstance(po, GitObject): perm, object = po.default_perm, po else: perm, object = po return perm, object def __init__(self, entries): """Create a new L{TreeData} object from the given mapping from names (strings) to either (I{permission}, I{object}) tuples or just objects.""" self.__entries = ImmutableDict((name, self.__x(po)) for (name, po) in entries.items()) @property def entries(self): return self.__entries def commit(self, repository): """Commit the tree. @return: The committed tree @rtype: L{Tree}""" listing = ['%s %s %s\t%s' % (mode, obj.typename, obj.sha1, name) for (name, (mode, obj)) in self.entries.items()] sha1 = repository.run(['git', 'mktree', '-z'] ).input_nulterm(listing).output_one_line() return repository.get_tree(sha1) @classmethod def parse(cls, repository, lines): """Parse a raw git tree description. @return: A new L{TreeData} object @rtype: L{TreeData}""" entries = {} for line in lines: m = re.match(r'^([0-7]{6}) ([a-z]+) ([0-9a-f]{40})\t(.*)$', line) assert m perm, type, sha1, name = m.groups() entries[name] = (perm, repository.get_object(type, sha1)) return cls(entries) class Tree(GitObject): """Represents a git tree object. All the actual data contents of the tree object is stored in the L{data} member, which is a L{TreeData} object.""" typename = 'tree' default_perm = '040000' def __init__(self, repository, sha1): self.__sha1 = sha1 self.__repository = repository self.__data = None @property def sha1(self): return self.__sha1 @property def data(self): if self.__data is None: self.__data = TreeData.parse( self.__repository, self.__repository.run(['git', 'ls-tree', '-z', self.sha1] ).output_lines('\0')) return self.__data def __str__(self): return 'Tree' % self.sha1 class CommitData(Immutable, Repr): """Represents the data contents of a git commit object.""" def __init__(self, tree = NoValue, parents = NoValue, author = NoValue, committer = NoValue, message = NoValue, defaults = NoValue): d = make_defaults(defaults) self.__tree = d(tree, 'tree') self.__parents = d(parents, 'parents') self.__author = d(author, 'author', Person.author) self.__committer = d(committer, 'committer', Person.committer) self.__message = d(message, 'message') @property def env(self): env = {} for p, v1 in ((self.author, 'AUTHOR'), (self.committer, 'COMMITTER')): if p is not None: for attr, v2 in (('name', 'NAME'), ('email', 'EMAIL'), ('date', 'DATE')): if getattr(p, attr) is not None: env['GIT_%s_%s' % (v1, v2)] = text(getattr(p, attr)) return env @property def tree(self): return self.__tree @property def parents(self): return self.__parents @property def parent(self): assert len(self.__parents) == 1 return self.__parents[0] @property def author(self): return self.__author @property def committer(self): return self.__committer @property def message(self): return self.__message def set_tree(self, tree): return type(self)(tree = tree, defaults = self) def set_parents(self, parents): return type(self)(parents = parents, defaults = self) def add_parent(self, parent): return type(self)(parents = list(self.parents or []) + [parent], defaults = self) def set_parent(self, parent): return self.set_parents([parent]) def set_author(self, author): return type(self)(author = author, defaults = self) def set_committer(self, committer): return type(self)(committer = committer, defaults = self) def set_message(self, message): return type(self)(message = message, defaults = self) def is_nochange(self): return len(self.parents) == 1 and self.tree == self.parent.data.tree def __str__(self): if self.tree is None: tree = None else: tree = self.tree.sha1 if self.parents is None: parents = None else: parents = [p.sha1 for p in self.parents] return ('CommitData' ) % (tree, parents, self.author, self.committer, self.message) def commit(self, repository): """Commit the commit. @return: The committed commit @rtype: L{Commit}""" c = ['git', 'commit-tree', self.tree.sha1] for p in self.parents: c.append('-p') c.append(p.sha1) sha1 = repository.run(c, env = self.env).raw_input(self.message ).output_one_line() return repository.get_commit(sha1) @classmethod def parse(cls, repository, s): """Parse a raw git commit description. @return: A new L{CommitData} object @rtype: L{CommitData}""" cd = cls(parents = []) lines = [] raw_lines = s.split('\n') # Collapse multi-line header lines for i, line in enumerate(raw_lines): if not line: cd = cd.set_message('\n'.join(raw_lines[i+1:])) break if line.startswith(' '): # continuation line lines[-1] += '\n' + line[1:] else: lines.append(line) for line in lines: if ' ' in line: key, value = line.split(' ', 1) if key == 'tree': cd = cd.set_tree(repository.get_tree(value)) elif key == 'parent': cd = cd.add_parent(repository.get_commit(value)) elif key == 'author': cd = cd.set_author(Person.parse(value)) elif key == 'committer': cd = cd.set_committer(Person.parse(value)) return cd class Commit(GitObject): """Represents a git commit object. All the actual data contents of the commit object is stored in the L{data} member, which is a L{CommitData} object.""" typename = 'commit' def __init__(self, repository, sha1): self.__sha1 = sha1 self.__repository = repository self.__data = None @property def sha1(self): return self.__sha1 @property def data(self): if self.__data is None: self.__data = CommitData.parse( self.__repository, self.__repository.cat_object(self.sha1)) return self.__data def __str__(self): return 'Commit' % (self.sha1, self.__data) class Refs(object): """Accessor for the refs stored in a git repository. Will transparently cache the values of all refs.""" def __init__(self, repository): self.__repository = repository self.__refs = None def __cache_refs(self): """(Re-)Build the cache of all refs in the repository.""" self.__refs = {} runner = self.__repository.run(['git', 'show-ref']) try: lines = runner.output_lines() except RunException: # as this happens both in non-git trees and empty git # trees, we silently ignore this error return for line in lines: m = re.match(r'^([0-9a-f]{40})\s+(\S+)$', line) sha1, ref = m.groups() self.__refs[ref] = sha1 def get(self, ref): """Get the Commit the given ref points to. Throws KeyError if ref doesn't exist.""" if self.__refs is None: self.__cache_refs() return self.__repository.get_commit(self.__refs[ref]) def exists(self, ref): """Check if the given ref exists.""" try: self.get(ref) except KeyError: return False else: return True def set(self, ref, commit, msg): """Write the sha1 of the given Commit to the ref. The ref may or may not already exist.""" if self.__refs is None: self.__cache_refs() old_sha1 = self.__refs.get(ref, '0'*40) new_sha1 = commit.sha1 if old_sha1 != new_sha1: self.__repository.run(['git', 'update-ref', '-m', msg, ref, new_sha1, old_sha1]).no_output() self.__refs[ref] = new_sha1 def delete(self, ref): """Delete the given ref. Throws KeyError if ref doesn't exist.""" if self.__refs is None: self.__cache_refs() self.__repository.run(['git', 'update-ref', '-d', ref, self.__refs[ref]]).no_output() del self.__refs[ref] class ObjectCache(object): """Cache for Python objects, for making sure that we create only one Python object per git object. This reduces memory consumption and makes object comparison very cheap.""" def __init__(self, create): self.__objects = {} self.__create = create def __getitem__(self, name): if name not in self.__objects: self.__objects[name] = self.__create(name) return self.__objects[name] def __contains__(self, name): return name in self.__objects def __setitem__(self, name, val): assert name not in self.__objects self.__objects[name] = val class RunWithEnv(object): def run(self, args, env = {}): """Run the given command with an environment given by self.env. @type args: list of strings @param args: Command and argument vector @type env: dict @param env: Extra environment""" return Run(*args).env(utils.add_dict(self.env, env)) class RunWithEnvCwd(RunWithEnv): def run(self, args, env = {}): """Run the given command with an environment given by self.env, and current working directory given by self.cwd. @type args: list of strings @param args: Command and argument vector @type env: dict @param env: Extra environment""" return RunWithEnv.run(self, args, env).cwd(self.cwd) def run_in_cwd(self, args): """Run the given command with an environment given by self.env and self.env_in_cwd, without changing the current working directory. @type args: list of strings @param args: Command and argument vector""" return RunWithEnv.run(self, args, self.env_in_cwd) class CatFileProcess(object): def __init__(self, repo): self.__repo = repo self.__proc = None atexit.register(self.__shutdown) def __get_process(self): if not self.__proc: self.__proc = self.__repo.run(['git', 'cat-file', '--batch'] ).run_background() return self.__proc def __shutdown(self): p = self.__proc if p: p.stdin.close() os.kill(p.pid(), signal.SIGTERM) p.wait() def cat_file(self, sha1, encoding): p = self.__get_process() p.stdin.write('%s\n' % sha1) p.stdin.flush() # Read until we have the entire status line. s = b'' while b'\n' not in s: s += os.read(p.stdout.fileno(), 4096) h, b = s.split(b'\n', 1) header = h.decode('utf-8') if header == '%s missing' % sha1: raise RepositoryException('Cannot cat %s' % sha1) name, type_, size = header.split() assert name == sha1 size = int(size) # Read until we have the entire object plus the trailing # newline. while len(b) < size + 1: b += os.read(p.stdout.fileno(), 4096) content = b[:size] if encoding: return type_, content.decode(encoding) else: return type_, content class DiffTreeProcesses(object): def __init__(self, repo): self.__repo = repo self.__procs = {} atexit.register(self.__shutdown) def __get_process(self, args): args = tuple(args) if args not in self.__procs: self.__procs[args] = self.__repo.run( ['git', 'diff-tree', '--stdin', '--encoding=utf-8'] + list(args)).run_background() return self.__procs[args] def __shutdown(self): for p in self.__procs.values(): os.kill(p.pid(), signal.SIGTERM) p.wait() def diff_trees(self, args, sha1a, sha1b): p = self.__get_process(args) query = '%s %s\n' % (sha1a, sha1b) b_query = query.encode('utf-8') end = 'EOF\n' # arbitrary string that's not a 40-digit hex number b_end = end.encode('utf-8') os.write(p.stdin.fileno(), b_query + b_end) p.stdin.flush() data = bytes() while not (data.endswith(b'\n' + b_end) or data.endswith(b'\0' + b_end)): data += os.read(p.stdout.fileno(), 4096) assert data.startswith(b_query) assert data.endswith(b_end) return data[len(b_query):-len(b_end)] class Repository(RunWithEnv): """Represents a git repository.""" def __init__(self, directory): self.__git_dir = directory self.__refs = Refs(self) self.__blobs = ObjectCache(lambda sha1: Blob(self, sha1)) self.__trees = ObjectCache(lambda sha1: Tree(self, sha1)) self.__commits = ObjectCache(lambda sha1: Commit(self, sha1)) self.__default_index = None self.__default_worktree = None self.__default_iw = None self.__catfile = CatFileProcess(self) self.__difftree = DiffTreeProcesses(self) @property def env(self): return {'GIT_DIR': self.__git_dir} @classmethod def default(cls): """Return the default repository.""" try: return cls(Run('git', 'rev-parse', '--git-dir').output_one_line()) except RunException: raise RepositoryException('Cannot find git repository') @property def current_branch_name(self): """Return the name of the current branch.""" return utils.strip_prefix('refs/heads/', self.head_ref) @property def default_index(self): """An L{Index} object representing the default index file for the repository.""" if self.__default_index is None: self.__default_index = Index( self, (environ_get('GIT_INDEX_FILE', None) or os.path.join(self.__git_dir, 'index'))) return self.__default_index def temp_index(self): """Return an L{Index} object representing a new temporary index file for the repository.""" return Index(self, self.__git_dir) @property def default_worktree(self): """A L{Worktree} object representing the default work tree.""" if self.__default_worktree is None: path = environ_get('GIT_WORK_TREE', None) if not path: o = Run('git', 'rev-parse', '--show-cdup').output_lines() o = o or ['.'] assert len(o) == 1 path = o[0] self.__default_worktree = Worktree(path) return self.__default_worktree @property def default_iw(self): """An L{IndexAndWorktree} object representing the default index and work tree for this repository.""" if self.__default_iw is None: self.__default_iw = IndexAndWorktree(self.default_index, self.default_worktree) return self.__default_iw @property def directory(self): return self.__git_dir @property def refs(self): return self.__refs def cat_object(self, sha1, encoding='utf-8'): return self.__catfile.cat_file(sha1, encoding)[1] def rev_parse(self, rev, discard_stderr = False, object_type = 'commit'): assert object_type in ('commit', 'tree', 'blob') getter = getattr(self, 'get_' + object_type) try: return getter(self.run( ['git', 'rev-parse', '%s^{%s}' % (rev, object_type)] ).discard_stderr(discard_stderr).output_one_line()) except RunException: raise RepositoryException('%s: No such %s' % (rev, object_type)) def get_blob(self, sha1): return self.__blobs[sha1] def get_tree(self, sha1): return self.__trees[sha1] def get_commit(self, sha1): return self.__commits[sha1] def get_object(self, type, sha1): return { Blob.typename: self.get_blob, Tree.typename: self.get_tree, Commit.typename: self.get_commit }[type](sha1) def commit(self, objectdata): return objectdata.commit(self) @property def head_ref(self): try: return self.run(['git', 'symbolic-ref', '-q', 'HEAD'] ).output_one_line() except RunException: raise DetachedHeadException() def set_head_ref(self, ref, msg): self.run(['git', 'symbolic-ref', '-m', msg, 'HEAD', ref]).no_output() def get_merge_bases(self, commit1, commit2): """Return a set of merge bases of two commits.""" sha1_list = self.run(['git', 'merge-base', '--all', commit1.sha1, commit2.sha1]).output_lines() return [self.get_commit(sha1) for sha1 in sha1_list] def describe(self, commit): """Use git describe --all on the given commit.""" return self.run(['git', 'describe', '--all', commit.sha1] ).discard_stderr().discard_exitcode().raw_output() def simple_merge(self, base, ours, theirs): index = self.temp_index() try: result, index_tree = index.merge(base, ours, theirs) finally: index.delete() return result def apply(self, tree, patch_bytes, quiet): """Given a L{Tree} and a patch, will either return the new L{Tree} that results when the patch is applied, or None if the patch couldn't be applied.""" assert isinstance(tree, Tree) if not patch_bytes: return tree index = self.temp_index() try: index.read_tree(tree) try: index.apply(patch_bytes, quiet) return index.write_tree() except MergeException: return None finally: index.delete() def submodules(self, tree): """Given a L{Tree}, return list of paths which are submodules.""" assert isinstance(tree, Tree) # A simple regex to match submodule entries regex = re.compile(r'160000 commit [0-9a-f]{40}\t(.*)$') # First, use ls-tree to get all the trees and links files = self.run(['git', 'ls-tree', '-d', '-r', '-z', tree.sha1]).output_lines('\0') # Then extract the paths of any submodules return set(m.group(1) for m in map(regex.match, files) if m) def diff_tree(self, t1, t2, diff_opts, binary = True): """Given two L{Tree}s C{t1} and C{t2}, return the patch that takes C{t1} to C{t2}. @type diff_opts: list of strings @param diff_opts: Extra diff options @rtype: String @return: Patch text""" assert isinstance(t1, Tree) assert isinstance(t2, Tree) diff_opts = list(diff_opts) if binary and '--binary' not in diff_opts: diff_opts.append('--binary') return self.__difftree.diff_trees(['-p'] + diff_opts, t1.sha1, t2.sha1) def diff_tree_files(self, t1, t2): """Given two L{Tree}s C{t1} and C{t2}, iterate over all files for which they differ. For each file, yield a tuple with the old file mode, the new file mode, the old blob, the new blob, the status, the old filename, and the new filename. Except in case of a copy or a rename, the old and new filenames are identical.""" assert isinstance(t1, Tree) assert isinstance(t2, Tree) dt = self.__difftree.diff_trees(['-r', '-z'], t1.sha1, t2.sha1) i = iter(dt.decode('utf-8').split('\0')) try: while True: x = next(i) if not x: continue omode, nmode, osha1, nsha1, status = x[1:].split(' ') fn1 = next(i) if status[0] in ['C', 'R']: fn2 = next(i) else: fn2 = fn1 yield (omode, nmode, self.get_blob(osha1), self.get_blob(nsha1), status, fn1, fn2) except StopIteration: pass class MergeException(exception.StgException): """Exception raised when a merge fails for some reason.""" class MergeConflictException(MergeException): """Exception raised when a merge fails due to conflicts.""" def __init__(self, conflicts): MergeException.__init__(self) self.conflicts = conflicts class Index(RunWithEnv): """Represents a git index file.""" def __init__(self, repository, filename): self.__repository = repository if os.path.isdir(filename): # Create a temp index in the given directory. self.__filename = os.path.join( filename, 'index.temp-%d-%x' % (os.getpid(), id(self))) self.delete() else: self.__filename = filename @property def env(self): return utils.add_dict(self.__repository.env, {'GIT_INDEX_FILE': self.__filename}) def read_tree(self, tree): self.run(['git', 'read-tree', tree.sha1]).no_output() def write_tree(self): """Write the index contents to the repository. @return: The resulting L{Tree} @rtype: L{Tree}""" try: return self.__repository.get_tree( self.run(['git', 'write-tree']).discard_stderr( ).output_one_line()) except RunException: raise MergeException('Conflicting merge') def is_clean(self, tree): """Check whether the index is clean relative to the given treeish.""" try: self.run(['git', 'diff-index', '--quiet', '--cached', tree.sha1] ).discard_output() except RunException: return False else: return True def apply(self, patch_bytes, quiet): """In-index patch application, no worktree involved.""" try: r = self.run(['git', 'apply', '--cached']) r.encoding(None).raw_input(patch_bytes) if quiet: r = r.discard_stderr() r.no_output() except RunException: raise MergeException('Patch does not apply cleanly') def apply_treediff(self, tree1, tree2, quiet): """Apply the diff from C{tree1} to C{tree2} to the index.""" # Passing --full-index here is necessary to support binary # files. It is also sufficient, since the repository already # contains all involved objects; in other words, we don't have # to use --binary. self.apply(self.__repository.diff_tree(tree1, tree2, ['--full-index']), quiet) def merge(self, base, ours, theirs, current = None): """Use the index (and only the index) to do a 3-way merge of the L{Tree}s C{base}, C{ours} and C{theirs}. The merge will either succeed (in which case the first half of the return value is the resulting tree) or fail cleanly (in which case the first half of the return value is C{None}). If C{current} is given (and not C{None}), it is assumed to be the L{Tree} currently stored in the index; this information is used to avoid having to read the right tree (either of C{ours} and C{theirs}) into the index if it's already there. The second half of the return value is the tree now stored in the index, or C{None} if unknown. If the merge succeeded, this is often the merge result.""" assert isinstance(base, Tree) assert isinstance(ours, Tree) assert isinstance(theirs, Tree) assert current is None or isinstance(current, Tree) # Take care of the really trivial cases. if base == ours: return (theirs, current) if base == theirs: return (ours, current) if ours == theirs: return (ours, current) if current == theirs: # Swap the trees. It doesn't matter since merging is # symmetric, and will allow us to avoid the read_tree() # call below. ours, theirs = theirs, ours if current != ours: self.read_tree(ours) try: self.apply_treediff(base, theirs, quiet = True) result = self.write_tree() return (result, result) except MergeException: return (None, ours) def delete(self): if os.path.isfile(self.__filename): os.remove(self.__filename) def conflicts(self): """The set of conflicting paths.""" paths = set() for line in self.run(['git', 'ls-files', '-z', '--unmerged'] ).output_lines('\0'): stat, path = line.split('\t', 1) paths.add(path) return paths class Worktree(object): """Represents a git worktree (that is, a checked-out file tree).""" def __init__(self, directory): self.__directory = directory @property def env(self): return {'GIT_WORK_TREE': '.'} @property def env_in_cwd(self): return {'GIT_WORK_TREE': self.directory} @property def directory(self): return self.__directory class CheckoutException(exception.StgException): """Exception raised when a checkout fails.""" class IndexAndWorktree(RunWithEnvCwd): """Represents a git index and a worktree. Anything that an index or worktree can do on their own are handled by the L{Index} and L{Worktree} classes; this class concerns itself with the operations that require both.""" def __init__(self, index, worktree): self.__index = index self.__worktree = worktree @property def index(self): return self.__index @property def env(self): return utils.add_dict(self.__index.env, self.__worktree.env) @property def env_in_cwd(self): return self.__worktree.env_in_cwd @property def cwd(self): return self.__worktree.directory def checkout_hard(self, tree): assert isinstance(tree, Tree) self.run(['git', 'read-tree', '--reset', '-u', tree.sha1] ).discard_output() def checkout(self, old_tree, new_tree): # TODO: Optionally do a 3-way instead of doing nothing when we # have a problem. Or maybe we should stash changes in a patch? assert isinstance(old_tree, Tree) assert isinstance(new_tree, Tree) try: self.run(['git', 'read-tree', '-u', '-m', '--exclude-per-directory=.gitignore', old_tree.sha1, new_tree.sha1] ).discard_output() except RunException: raise CheckoutException('Index/workdir dirty') def merge(self, base, ours, theirs, interactive = False): assert isinstance(base, Tree) assert isinstance(ours, Tree) assert isinstance(theirs, Tree) try: r = self.run(['git', 'merge-recursive', base.sha1, '--', ours.sha1, theirs.sha1], env = { 'GITHEAD_%s' % base.sha1: 'ancestor', 'GITHEAD_%s' % ours.sha1: 'current', 'GITHEAD_%s' % theirs.sha1: 'patched'}) r.returns([0, 1]) output = r.output_lines() if r.exitcode: # There were conflicts if interactive: self.mergetool() else: conflicts = [l for l in output if l.startswith('CONFLICT')] raise MergeConflictException(conflicts) except RunException: raise MergeException('Index/worktree dirty') def mergetool(self, files = ()): """Invoke 'git mergetool' on the current IndexAndWorktree to resolve any outstanding conflicts. If 'not files', all the files in an unmerged state will be processed.""" self.run(['git', 'mergetool'] + list(files)).returns([0, 1]).run() # check for unmerged entries (prepend 'CONFLICT ' for consistency with # merge()) conflicts = ['CONFLICT ' + f for f in self.index.conflicts()] if conflicts: raise MergeConflictException(conflicts) def changed_files(self, tree, pathlimits = []): """Return the set of files in the worktree that have changed with respect to C{tree}. The listing is optionally restricted to those files that match any of the path limiters given. The path limiters are relative to the current working directory; the returned file names are relative to the repository root.""" assert isinstance(tree, Tree) return set(self.run_in_cwd( ['git', 'diff-index', tree.sha1, '--name-only', '-z', '--'] + list(pathlimits)).output_lines('\0')) def update_index(self, paths): """Update the index with files from the worktree. C{paths} is an iterable of paths relative to the root of the repository.""" cmd = ['git', 'update-index', '--remove'] self.run(cmd + ['-z', '--stdin'] ).input_nulterm(paths).discard_output() def worktree_clean(self): """Check whether the worktree is clean relative to index.""" try: self.run(['git', 'update-index', '--ignore-submodules', '--refresh']).discard_output() except RunException: return False else: return True class Branch(object): """Represents a Git branch.""" def __init__(self, repository, name): self.__repository = repository self.__name = name try: self.head except KeyError: raise BranchException('%s: no such branch' % name) @property def name(self): return self.__name @property def repository(self): return self.__repository def __ref(self): return 'refs/heads/%s' % self.__name @property def head(self): return self.__repository.refs.get(self.__ref()) def set_head(self, commit, msg): self.__repository.refs.set(self.__ref(), commit, msg) def set_parent_remote(self, name): config.set('branch.%s.remote' % self.__name, name) def set_parent_branch(self, name): if config.get('branch.%s.remote' % self.__name): # Never set merge if remote is not set to avoid # possibly-erroneous lookups into 'origin' config.set('branch.%s.merge' % self.__name, name) @classmethod def create(cls, repository, name, create_at = None): """Create a new Git branch and return the corresponding L{Branch} object.""" try: branch = cls(repository, name) except BranchException: branch = None if branch: raise BranchException('%s: branch already exists' % name) cmd = ['git', 'branch'] if create_at: cmd.append(create_at.sha1) repository.run(['git', 'branch', create_at.sha1]).discard_output() return cls(repository, name) def diffstat(diff): """Return the diffstat of the supplied diff.""" return (Run('git', 'apply', '--stat', '--summary') .encoding(None).raw_input(diff) .decoding('utf-8').raw_output()) def clone(remote, local): """Clone a remote repository using 'git clone'.""" Run('git', 'clone', remote, local).run() stgit-0.19/stgit/lib/log.py000066400000000000000000000442741337022307200156420ustar00rootroot00000000000000# -*- coding: utf-8 -*- """This module contains functions and classes for manipulating I{patch stack logs} (or just I{stack logs}). A stack log is a git branch. Each commit contains the complete state of the stack at the moment it was written; the most recent commit has the most recent state. For a branch C{I{foo}}, the stack log is stored in C{I{foo}.stgit}. Each log entry makes sure to have proper references to everything it needs, which means that it is safe against garbage collection -- you can even pull it from one repository to another. Stack log format (version 0) ============================ Version 0 was an experimental version of the stack log format; it is no longer supported. Stack log format (version 1) ============================ Commit message -------------- The commit message is mostly for human consumption; in most cases it is just a subject line: the stg subcommand name and possibly some important command-line flag. An exception to this is log commits for undo and redo. Their subject line is "C{undo I{n}}" and "C{redo I{n}}"; the positive integer I{n} says how many steps were undone or redone. Tree ---- - One blob, C{meta}, that contains the log data: - C{Version:} I{n} where I{n} must be 1. (Future versions of StGit might change the log format; when this is done, this version number will be incremented.) - C{Previous:} I{sha1 or C{None}} The commit of the previous log entry, or C{None} if this is the first entry. - C{Head:} I{sha1} The current branch head. - C{Applied:} Marks the start of the list of applied patches. They are listed in order, each on its own line: first one or more spaces, then the patch name, then a colon, space, then the patch's sha1. - C{Unapplied:} Same as C{Applied:}, but for the unapplied patches. - C{Hidden:} Same as C{Applied:}, but for the hidden patches. - One subtree, C{patches}, that contains one blob per patch:: Bottom: Top: Author: Date: --- Following the message is a newline, three dashes, and another newline. Then come, each on its own line, Parents ------- - The first parent is the I{simplified log}, described below. - The rest of the parents are just there to make sure that all the commits referred to in the log entry -- patches, branch head, previous log entry -- are ancestors of the log commit. (This is necessary to make the log safe with regard to garbage collection and pulling.) Simplified log -------------- The simplified log is exactly like the full log, except that its only parent is the (simplified) previous log entry, if any. It's purpose is mainly ease of visualization.""" from __future__ import (absolute_import, division, print_function, unicode_literals) from io import StringIO import re from stgit import utils from stgit.exception import StgException, StackException from stgit.lib import git, stack as libstack from stgit.out import out class LogException(StgException): pass class LogParseException(LogException): pass def patch_file(repo, cd): metadata = '\n'.join([ 'Bottom: %s' % cd.parent.data.tree.sha1, 'Top: %s' % cd.tree.sha1, 'Author: %s' % cd.author.name_email, 'Date: %s' % cd.author.date, '', cd.message, '', '---', '', ]).encode('utf-8') diff = repo.diff_tree(cd.parent.data.tree, cd.tree, ['-M']).strip() return repo.commit(git.BlobData(metadata + diff + b'\n')) def log_ref(branch): return 'refs/heads/%s.stgit' % branch class LogEntry(object): __separator = '\n---\n' __max_parents = 16 def __init__(self, repo, prev, head, applied, unapplied, hidden, patches, message): self.__repo = repo self.__prev = prev self.__simplified = None self.head = head self.applied = applied self.unapplied = unapplied self.hidden = hidden self.patches = patches self.message = message @property def simplified(self): if not self.__simplified: self.__simplified = self.commit.data.parents[0] return self.__simplified @property def prev(self): if self.__prev is not None and not isinstance(self.__prev, LogEntry): self.__prev = self.from_commit(self.__repo, self.__prev) return self.__prev @property def base(self): if self.applied: return self.patches[self.applied[0]].data.parent else: return self.head @property def top(self): if self.applied: return self.patches[self.applied[-1]] else: return self.head @property def all_patches(self): return self.applied + self.unapplied + self.hidden @classmethod def from_stack(cls, prev, stack, message): return cls( repo = stack.repository, prev = prev, head = stack.head, applied = list(stack.patchorder.applied), unapplied = list(stack.patchorder.unapplied), hidden = list(stack.patchorder.hidden), patches = dict((pn, stack.patches.get(pn).commit) for pn in stack.patchorder.all), message = message) @staticmethod def __parse_metadata(repo, metadata): """Parse a stack log metadata string.""" if not metadata.startswith('Version:'): raise LogParseException('Malformed log metadata') metadata = metadata.splitlines() version_str = utils.strip_prefix('Version:', metadata.pop(0)).strip() try: version = int(version_str) except ValueError: raise LogParseException( 'Malformed version number: %r' % version_str) if version < 1: raise LogException('Log is version %d, which is too old' % version) if version > 1: raise LogException('Log is version %d, which is too new' % version) parsed = {} key = None for line in metadata: if line.startswith(' '): assert key is not None parsed[key].append(line.strip()) else: key, val = [x.strip() for x in line.split(':', 1)] if val: parsed[key] = val else: parsed[key] = [] prev = parsed['Previous'] if prev == 'None': prev = None else: prev = repo.get_commit(prev) head = repo.get_commit(parsed['Head']) lists = { 'Applied': [], 'Unapplied': [], 'Hidden': [] } patches = {} for lst in lists: for entry in parsed[lst]: pn, sha1 = [x.strip() for x in entry.split(':')] lists[lst].append(pn) patches[pn] = repo.get_commit(sha1) return (prev, head, lists['Applied'], lists['Unapplied'], lists['Hidden'], patches) @classmethod def from_commit(cls, repo, commit): """Parse a (full or simplified) stack log commit.""" message = commit.data.message try: perm, meta = commit.data.tree.data.entries['meta'] except KeyError: raise LogParseException('Not a stack log') (prev, head, applied, unapplied, hidden, patches ) = cls.__parse_metadata(repo, meta.data.bytes.decode('utf-8')) lg = cls(repo, prev, head, applied, unapplied, hidden, patches, message) lg.commit = commit return lg def __metadata_string(self): e = StringIO() e.write('Version: 1\n') if self.prev is None: e.write('Previous: None\n') else: e.write('Previous: %s\n' % self.prev.commit.sha1) e.write('Head: %s\n' % self.head.sha1) for lst, title in [(self.applied, 'Applied'), (self.unapplied, 'Unapplied'), (self.hidden, 'Hidden')]: e.write('%s:\n' % title) for pn in lst: e.write(' %s: %s\n' % (pn, self.patches[pn].sha1)) return e.getvalue() def __parents(self): """Return the set of parents this log entry needs in order to be a descendant of all the commits it refers to.""" xp = set([self.head]) | set(self.patches[pn] for pn in self.unapplied + self.hidden) if self.applied: xp.add(self.patches[self.applied[-1]]) if self.prev is not None: xp.add(self.prev.commit) xp -= set(self.prev.patches.values()) return xp def __tree(self, metadata): if self.prev is None: def pf(c): return patch_file(self.__repo, c.data) else: prev_top_tree = self.prev.commit.data.tree perm, prev_patch_tree = prev_top_tree.data.entries['patches'] # Map from Commit object to patch_file() results taken # from the previous log entry. c2b = dict((self.prev.patches[pn], pf) for pn, pf in prev_patch_tree.data.entries.items()) def pf(c): r = c2b.get(c, None) if not r: r = patch_file(self.__repo, c.data) return r patches = dict((pn, pf(c)) for pn, c in self.patches.items()) return self.__repo.commit(git.TreeData({ 'meta': self.__repo.commit(git.BlobData(metadata.encode('utf-8'))), 'patches': self.__repo.commit(git.TreeData(patches)) })) def write_commit(self): metadata = self.__metadata_string() tree = self.__tree(metadata) self.__simplified = self.__repo.commit(git.CommitData( tree = tree, message = self.message, parents = [prev.simplified for prev in [self.prev] if prev is not None])) parents = list(self.__parents()) while len(parents) >= self.__max_parents: g = self.__repo.commit(git.CommitData( tree = tree, parents = parents[-self.__max_parents:], message = 'Stack log parent grouping')) parents[-self.__max_parents:] = [g] self.commit = self.__repo.commit(git.CommitData( tree = tree, message = self.message, parents = [self.simplified] + parents)) def get_log_entry(repo, ref, commit): try: return LogEntry.from_commit(repo, commit) except LogException as e: raise LogException('While reading log from %s: %s' % (ref, e)) def same_state(log1, log2): """Check whether two log entries describe the same current state.""" s = [[lg.head, lg.applied, lg.unapplied, lg.hidden, lg.patches] for lg in [log1, log2]] return s[0] == s[1] def log_entry(stack, msg): """Write a new log entry for the stack.""" ref = log_ref(stack.name) try: last_log_commit = stack.repository.refs.get(ref) except KeyError: last_log_commit = None try: if last_log_commit: last_log = get_log_entry(stack.repository, ref, last_log_commit) else: last_log = None new_log = LogEntry.from_stack(last_log, stack, msg) except LogException as e: out.warn(str(e), 'No log entry written.') return if last_log and same_state(last_log, new_log): return new_log.write_commit() stack.repository.refs.set(ref, new_log.commit, msg) class Fakestack(object): """Imitates a real L{Stack}, but with the topmost patch popped.""" def __init__(self, stack): appl = list(stack.patchorder.applied) unappl = list(stack.patchorder.unapplied) hidd = list(stack.patchorder.hidden) class patchorder(object): applied = appl[:-1] unapplied = [appl[-1]] + unappl hidden = hidd all = appl + unappl + hidd self.patchorder = patchorder class patches(object): @staticmethod def get(pn): if pn == appl[-1]: class patch(object): commit = stack.patches.get(pn).old_commit return patch else: return stack.patches.get(pn) self.patches = patches self.head = stack.head.data.parent self.top = stack.top.data.parent self.base = stack.base self.name = stack.name self.repository = stack.repository def compat_log_entry(msg): """Write a new log entry. (Convenience function intended for use by code not yet converted to the new infrastructure.)""" try: repo = default_repo() stack = repo.get_stack(repo.current_branch_name) except (StackException, git.RepositoryException) as e: out.warn(str(e), 'Could not write to stack log') else: if repo.default_index.conflicts() and stack.patchorder.applied: log_entry(Fakestack(stack), msg) log_entry(stack, msg + ' (CONFLICT)') else: log_entry(stack, msg) def delete_log(repo, branch): ref = log_ref(branch) if repo.refs.exists(ref): repo.refs.delete(ref) def rename_log(repo, old_branch, new_branch, msg): old_ref = log_ref(old_branch) new_ref = log_ref(new_branch) if repo.refs.exists(old_ref): repo.refs.set(new_ref, repo.refs.get(old_ref), msg) repo.refs.delete(old_ref) def copy_log(repo, src_branch, dst_branch, msg): src_ref = log_ref(src_branch) dst_ref = log_ref(dst_branch) if repo.refs.exists(src_ref): repo.refs.set(dst_ref, repo.refs.get(src_ref), msg) def default_repo(): return libstack.Repository.default() def reset_stack(trans, iw, state): """Reset the stack to a given previous state.""" for pn in trans.all_patches: trans.patches[pn] = None for pn in state.all_patches: trans.patches[pn] = state.patches[pn] trans.applied = state.applied trans.unapplied = state.unapplied trans.hidden = state.hidden trans.base = state.base trans.head = state.head def reset_stack_partially(trans, iw, state, only_patches): """Reset the stack to a given previous state -- but only the given patches, not anything else. @param only_patches: Touch only these patches @type only_patches: iterable""" only_patches = set(only_patches) patches_to_reset = set(state.all_patches) & only_patches existing_patches = set(trans.all_patches) original_applied_order = list(trans.applied) to_delete = (existing_patches - patches_to_reset) & only_patches # In one go, do all the popping we have to in order to pop the # patches we're going to delete or modify. def mod(pn): if pn not in only_patches: return False if pn in to_delete: return True if trans.patches[pn] != state.patches.get(pn, None): return True return False trans.pop_patches(mod) # Delete and modify/create patches. We've previously popped all # patches that we touch in this step. trans.delete_patches(lambda pn: pn in to_delete) for pn in patches_to_reset: if pn in existing_patches: if trans.patches[pn] == state.patches[pn]: continue else: out.info('Resetting %s' % pn) else: if pn in state.hidden: trans.hidden.append(pn) else: trans.unapplied.append(pn) out.info('Resurrecting %s' % pn) trans.patches[pn] = state.patches[pn] # Push all the patches that we've popped, if they still # exist. pushable = set(trans.unapplied + trans.hidden) for pn in original_applied_order: if pn in pushable: trans.push_patch(pn, iw) def undo_state(stack, undo_steps): """Find the log entry C{undo_steps} steps in the past. (Successive undo operations are supposed to "add up", so if we find other undo operations along the way we have to add those undo steps to C{undo_steps}.) If C{undo_steps} is negative, redo instead of undo. @return: The log entry that is the destination of the undo operation @rtype: L{LogEntry}""" ref = log_ref(stack.name) try: commit = stack.repository.refs.get(ref) except KeyError: raise LogException('Log is empty') log = get_log_entry(stack.repository, ref, commit) while undo_steps != 0: msg = log.message.strip() um = re.match(r'^undo\s+(\d+)$', msg) if undo_steps > 0: if um: undo_steps += int(um.group(1)) else: undo_steps -= 1 else: rm = re.match(r'^redo\s+(\d+)$', msg) if um: undo_steps += 1 elif rm: undo_steps -= int(rm.group(1)) else: raise LogException('No more redo information available') if not log.prev: raise LogException('Not enough undo information available') log = log.prev return log def log_external_mods(stack): ref = log_ref(stack.name) try: log_commit = stack.repository.refs.get(ref) except KeyError: # No log exists yet. log_entry(stack, 'start of log') return try: log = get_log_entry(stack.repository, ref, log_commit) except LogException: # Something's wrong with the log, so don't bother. return if log.head == stack.head: # No external modifications. return log_entry(stack, '\n'.join([ 'external modifications', '', 'Modifications by tools other than StGit (e.g. git).'])) def compat_log_external_mods(): try: repo = default_repo() except git.RepositoryException: # No repository, so we couldn't log even if we wanted to. return try: stack = repo.get_stack(repo.current_branch_name) except StgException: # Stack doesn't exist, so we can't log. return log_external_mods(stack) stgit-0.19/stgit/lib/stack.py000066400000000000000000000247321337022307200161630ustar00rootroot00000000000000# -*- coding: utf-8 -*- """A Python class hierarchy wrapping the StGit on-disk metadata.""" from __future__ import (absolute_import, division, print_function, unicode_literals) import os from stgit import utils from stgit.compat import text from stgit.config import config from stgit.exception import StackException from stgit.lib import git, stackupgrade class Patch(object): """Represents an StGit patch. This class is mainly concerned with reading and writing the on-disk representation of a patch.""" def __init__(self, stack, name): self.__stack = stack self.__name = name @property def name(self): return self.__name @property def __ref(self): return 'refs/patches/%s/%s' % (self.__stack.name, self.__name) @property def __log_ref(self): return self.__ref + '.log' @property def commit(self): return self.__stack.repository.refs.get(self.__ref) @property def old_commit(self): """Return the previous commit for this patch.""" fn = os.path.join(self.__compat_dir, 'top.old') if not os.path.isfile(fn): return None return self.__stack.repository.get_commit(utils.read_string(fn)) @property def __compat_dir(self): return os.path.join(self.__stack.directory, 'patches', self.__name) def __write_compat_files(self, new_commit, msg): """Write files used by the old infrastructure.""" def write(name, val, multiline = False): fn = os.path.join(self.__compat_dir, name) if val: utils.write_string(fn, val, multiline) elif os.path.isfile(fn): os.remove(fn) def write_patchlog(): try: old_log = [self.__stack.repository.refs.get(self.__log_ref)] except KeyError: old_log = [] cd = git.CommitData(tree = new_commit.data.tree, parents = old_log, message = '%s\t%s' % (msg, new_commit.sha1)) c = self.__stack.repository.commit(cd) self.__stack.repository.refs.set(self.__log_ref, c, msg) return c d = new_commit.data write('authname', d.author.name) write('authemail', d.author.email) write('authdate', d.author.date) write('commname', d.committer.name) write('commemail', d.committer.email) write('description', d.message, multiline = True) write('log', write_patchlog().sha1) write('top', new_commit.sha1) write('bottom', d.parent.sha1) try: old_top_sha1 = self.commit.sha1 old_bottom_sha1 = self.commit.data.parent.sha1 except KeyError: old_top_sha1 = None old_bottom_sha1 = None write('top.old', old_top_sha1) write('bottom.old', old_bottom_sha1) def __delete_compat_files(self): if os.path.isdir(self.__compat_dir): for f in os.listdir(self.__compat_dir): os.remove(os.path.join(self.__compat_dir, f)) os.rmdir(self.__compat_dir) try: # this compatibility log ref might not exist self.__stack.repository.refs.delete(self.__log_ref) except KeyError: pass def set_commit(self, commit, msg): self.__write_compat_files(commit, msg) self.__stack.repository.refs.set(self.__ref, commit, msg) def delete(self): self.__delete_compat_files() self.__stack.repository.refs.delete(self.__ref) def is_applied(self): return self.name in self.__stack.patchorder.applied def is_empty(self): return self.commit.data.is_nochange() def files(self): """Return the set of files this patch touches.""" fs = set() for (_, _, _, _, _, oldname, newname ) in self.__stack.repository.diff_tree_files( self.commit.data.tree, self.commit.data.parent.data.tree): fs.add(oldname) fs.add(newname) return fs class PatchOrder(object): """Keeps track of patch order, and which patches are applied. Works with patch names, not actual patches.""" def __init__(self, stack): self.__stack = stack self.__lists = {} def __read_file(self, fn): return tuple(utils.read_strings( os.path.join(self.__stack.directory, fn))) def __write_file(self, fn, val): utils.write_strings(os.path.join(self.__stack.directory, fn), val) def __get_list(self, name): if name not in self.__lists: self.__lists[name] = self.__read_file(name) return self.__lists[name] def __set_list(self, name, val): val = tuple(val) if val != self.__lists.get(name, None): self.__lists[name] = val self.__write_file(name, val) @property def applied(self): return self.__get_list('applied') @applied.setter def applied(self, value): self.__set_list('applied', value) @property def unapplied(self): return self.__get_list('unapplied') @unapplied.setter def unapplied(self, value): self.__set_list('unapplied', value) @property def hidden(self): return self.__get_list('hidden') @hidden.setter def hidden(self, value): self.__set_list('hidden', value) @property def all(self): return self.applied + self.unapplied + self.hidden @property def all_visible(self): return self.applied + self.unapplied @staticmethod def create(stackdir): """Create the PatchOrder specific files """ utils.create_empty_file(os.path.join(stackdir, 'applied')) utils.create_empty_file(os.path.join(stackdir, 'unapplied')) utils.create_empty_file(os.path.join(stackdir, 'hidden')) class Patches(object): """Creates L{Patch} objects. Makes sure there is only one such object per patch.""" def __init__(self, stack): self.__stack = stack def create_patch(name): p = Patch(self.__stack, name) p.commit # raise exception if the patch doesn't exist return p self.__patches = git.ObjectCache(create_patch) # name -> Patch def exists(self, name): try: self.get(name) return True except KeyError: return False def get(self, name): return self.__patches[name] def new(self, name, commit, msg): assert name not in self.__patches p = Patch(self.__stack, name) p.set_commit(commit, msg) self.__patches[name] = p return p class Stack(git.Branch): """Represents an StGit stack (that is, a git branch with some extra metadata).""" __repo_subdir = 'patches' def __init__(self, repository, name): git.Branch.__init__(self, repository, name) self.__patchorder = PatchOrder(self) self.__patches = Patches(self) if not stackupgrade.update_to_current_format_version(repository, name): raise StackException('%s: branch not initialized' % name) @property def patchorder(self): return self.__patchorder @property def patches(self): return self.__patches @property def directory(self): return os.path.join(self.repository.directory, self.__repo_subdir, self.name) @property def base(self): if self.patchorder.applied: return self.patches.get(self.patchorder.applied[0] ).commit.data.parent else: return self.head @property def top(self): """Commit of the topmost patch, or the stack base if no patches are applied.""" if self.patchorder.applied: return self.patches.get(self.patchorder.applied[-1]).commit else: # When no patches are applied, base == head. return self.head def head_top_equal(self): if not self.patchorder.applied: return True return self.head == self.patches.get(self.patchorder.applied[-1]).commit def set_parents(self, remote, branch): if remote: self.set_parent_remote(remote) if branch: self.set_parent_branch(branch) @classmethod def initialise(cls, repository, name = None): """Initialise a Git branch to handle patch series. @param repository: The L{Repository} where the L{Stack} will be created @param name: The name of the L{Stack} """ if not name: name = repository.current_branch_name # make sure that the corresponding Git branch exists git.Branch(repository, name) dir = os.path.join(repository.directory, cls.__repo_subdir, name) compat_dir = os.path.join(dir, 'patches') if os.path.exists(dir): raise StackException('%s: branch already initialized' % name) # create the stack directory and files utils.create_dirs(dir) utils.create_dirs(compat_dir) PatchOrder.create(dir) config.set(stackupgrade.format_version_key(name), text(stackupgrade.FORMAT_VERSION)) return repository.get_stack(name) @classmethod def create(cls, repository, name, create_at = None, parent_remote = None, parent_branch = None): """Create and initialise a Git branch returning the L{Stack} object. @param repository: The L{Repository} where the L{Stack} will be created @param name: The name of the L{Stack} @param create_at: The Git id used as the base for the newly created Git branch @param parent_remote: The name of the remote Git branch @param parent_branch: The name of the parent Git branch """ git.Branch.create(repository, name, create_at = create_at) stack = cls.initialise(repository, name) stack.set_parents(parent_remote, parent_branch) return stack class Repository(git.Repository): """A git L{Repository} with some added StGit-specific operations.""" def __init__(self, *args, **kwargs): git.Repository.__init__(self, *args, **kwargs) self.__stacks = {} # name -> Stack @property def current_stack(self): return self.get_stack() def get_stack(self, name = None): if not name: name = self.current_branch_name if name not in self.__stacks: self.__stacks[name] = Stack(self, name) return self.__stacks[name] stgit-0.19/stgit/lib/stackupgrade.py000066400000000000000000000106511337022307200175260ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os from stgit import utils from stgit.config import config from stgit.exception import StackException from stgit.out import out # The current StGit metadata format version. FORMAT_VERSION = 2 def format_version_key(branch): return 'branch.%s.stgit.stackformatversion' % branch def update_to_current_format_version(repository, branch): """Update a potentially older StGit directory structure to the latest version. Note: This function should depend as little as possible on external functions that may change during a format version bump, since it must remain able to process older formats.""" branch_dir = os.path.join(repository.directory, 'patches', branch) key = format_version_key(branch) old_key = 'branch.%s.stgitformatversion' % branch def get_format_version(): """Return the integer format version number, or None if the branch doesn't have any StGit metadata at all, of any version.""" fv = config.get(key) ofv = config.get(old_key) if fv: # Great, there's an explicitly recorded format version # number, which means that the branch is initialized and # of that exact version. return int(fv) elif ofv: # Old name for the version info: upgrade it. config.set(key, ofv) config.unset(old_key) return int(ofv) elif os.path.isdir(os.path.join(branch_dir, 'patches')): # There's a .git/patches//patches dirctory, which # means this is an initialized version 1 branch. return 1 elif os.path.isdir(branch_dir): # There's a .git/patches/ directory, which means # this is an initialized version 0 branch. return 0 else: # The branch doesn't seem to be initialized at all. return None def set_format_version(v): out.info('Upgraded branch %s to format version %d' % (branch, v)) config.set(key, '%d' % v) def mkdir(d): if not os.path.isdir(d): os.makedirs(d) def rm(f): if os.path.exists(f): os.remove(f) def rm_ref(ref): if repository.refs.exists(ref): repository.refs.delete(ref) # Update 0 -> 1. if get_format_version() == 0: mkdir(os.path.join(branch_dir, 'trash')) patch_dir = os.path.join(branch_dir, 'patches') mkdir(patch_dir) refs_base = 'refs/patches/%s' % branch with open(os.path.join(branch_dir, 'unapplied')) as f: patches = f.readlines() with open(os.path.join(branch_dir, 'applied')) as f: patches.extend(f.readlines()) for patch in patches: patch = patch.strip() os.rename(os.path.join(branch_dir, patch), os.path.join(patch_dir, patch)) topfield = os.path.join(patch_dir, patch, 'top') if os.path.isfile(topfield): top = utils.read_string(topfield, False) else: top = None if top: repository.refs.set(refs_base + '/' + patch, repository.get_commit(top), 'StGit upgrade') set_format_version(1) # Update 1 -> 2. if get_format_version() == 1: desc_file = os.path.join(branch_dir, 'description') if os.path.isfile(desc_file): desc = utils.read_string(desc_file) if desc: config.set('branch.%s.description' % branch, desc) rm(desc_file) rm(os.path.join(branch_dir, 'current')) rm_ref('refs/bases/%s' % branch) set_format_version(2) # compatibility with the new infrastructure. The changes here do not # affect the compatibility with the old infrastructure (format version 2) if get_format_version() == 2: hidden_file = os.path.join(branch_dir, 'hidden') if not os.path.isfile(hidden_file): utils.create_empty_file(hidden_file) # Make sure we're at the latest version. fv = get_format_version() if fv not in [None, FORMAT_VERSION]: raise StackException('Branch %s is at format version %d, expected %d' % (branch, fv, FORMAT_VERSION)) return fv is not None # true if branch is initialized stgit-0.19/stgit/lib/transaction.py000066400000000000000000000422221337022307200173750ustar00rootroot00000000000000# -*- coding: utf-8 -*- """The L{StackTransaction} class makes it possible to make complex updates to an StGit stack in a safe and convenient way.""" from __future__ import (absolute_import, division, print_function, unicode_literals) from itertools import takewhile import atexit from stgit import exception, utils from stgit.config import config from stgit.lib import git, log from stgit.out import out class TransactionException(exception.StgException): """Exception raised when something goes wrong with a L{StackTransaction}.""" class TransactionHalted(TransactionException): """Exception raised when a L{StackTransaction} stops part-way through. Used to make a non-local jump from the transaction setup to the part of the transaction code where the transaction is run.""" def _print_current_patch(old_applied, new_applied): def now_at(pn): out.info('Now at patch "%s"' % pn) if not old_applied and not new_applied: pass elif not old_applied: now_at(new_applied[-1]) elif not new_applied: out.info('No patch applied') elif old_applied[-1] == new_applied[-1]: pass else: now_at(new_applied[-1]) class _TransPatchMap(dict): """Maps patch names to Commit objects.""" def __init__(self, stack): dict.__init__(self) self.__stack = stack def __getitem__(self, pn): try: return dict.__getitem__(self, pn) except KeyError: return self.__stack.patches.get(pn).commit class StackTransaction(object): """A stack transaction, used for making complex updates to an StGit stack in one single operation that will either succeed or fail cleanly. The basic theory of operation is the following: 1. Create a transaction object. 2. Inside a:: try ... except TransactionHalted: pass block, update the transaction with e.g. methods like L{pop_patches} and L{push_patch}. This may create new git objects such as commits, but will not write any refs; this means that in case of a fatal error we can just walk away, no clean-up required. (Some operations may need to touch your index and working tree, though. But they are cleaned up when needed.) 3. After the C{try} block -- wheher or not the setup ran to completion or halted part-way through by raising a L{TransactionHalted} exception -- call the transaction's L{run} method. This will either succeed in writing the updated state to your refs and index+worktree, or fail without having done anything.""" def __init__(self, stack, msg, discard_changes = False, allow_conflicts = False, allow_bad_head = False, check_clean_iw = None): """Create a new L{StackTransaction}. @param discard_changes: Discard any changes in index+worktree @type discard_changes: bool @param allow_conflicts: Whether to allow pre-existing conflicts @type allow_conflicts: bool or function of L{StackTransaction}""" self.__stack = stack self.__msg = msg self.__patches = _TransPatchMap(stack) self.__applied = list(self.__stack.patchorder.applied) self.__unapplied = list(self.__stack.patchorder.unapplied) self.__hidden = list(self.__stack.patchorder.hidden) self.__error = None self.__current_tree = self.__stack.head.data.tree self.__base = self.__stack.base self.__discard_changes = discard_changes self.__bad_head = None self.__conflicts = None if isinstance(allow_conflicts, bool): self.__allow_conflicts = lambda trans: allow_conflicts else: self.__allow_conflicts = allow_conflicts self.__temp_index = self.temp_index_tree = None if not allow_bad_head: self.__assert_head_top_equal() if check_clean_iw: self.__assert_index_worktree_clean(check_clean_iw) @property def stack(self): return self.__stack @property def patches(self): return self.__patches @property def applied(self): return self.__applied @applied.setter def applied(self, value): self.__applied = list(value) @property def unapplied(self): return self.__unapplied @unapplied.setter def unapplied(self, value): self.__unapplied = list(value) @property def hidden(self): return self.__hidden @hidden.setter def hidden(self, value): self.__hidden = list(value) @property def all_patches(self): return self.__applied + self.__unapplied + self.__hidden @property def base(self): return self.__base @base.setter def base(self, value): assert (not self.__applied or self.patches[self.applied[0]].data.parent == value) self.__base = value @property def temp_index(self): if not self.__temp_index: self.__temp_index = self.__stack.repository.temp_index() atexit.register(self.__temp_index.delete) return self.__temp_index @property def top(self): if self.__applied: return self.__patches[self.__applied[-1]] else: return self.__base @property def head(self): if self.__bad_head: return self.__bad_head else: return self.top @head.setter def head(self, value): self.__bad_head = value def __assert_head_top_equal(self): if not self.__stack.head_top_equal(): out.error( 'HEAD and top are not the same.', 'This can happen if you modify a branch with git.', '"stg repair --help" explains more about what to do next.') self.__abort() def __assert_index_worktree_clean(self, iw): if not iw.worktree_clean(): self.__halt('Worktree not clean. Use "refresh" or "reset --hard"') if not iw.index.is_clean(self.stack.head): self.__halt('Index not clean. Use "refresh" or "reset --hard"') def __checkout(self, tree, iw, allow_bad_head): if not allow_bad_head: self.__assert_head_top_equal() if self.__current_tree == tree and not self.__discard_changes: # No tree change, but we still want to make sure that # there are no unresolved conflicts. Conflicts # conceptually "belong" to the topmost patch, and just # carrying them along to another patch is confusing. if (self.__allow_conflicts(self) or iw is None or not iw.index.conflicts()): return out.error('Need to resolve conflicts first') self.__abort() assert iw is not None if self.__discard_changes: iw.checkout_hard(tree) else: iw.checkout(self.__current_tree, tree) self.__current_tree = tree @staticmethod def __abort(): raise TransactionException( 'Command aborted (all changes rolled back)') def __check_consistency(self): remaining = set(self.all_patches) for pn, commit in self.__patches.items(): if commit is None: assert self.__stack.patches.exists(pn) else: assert pn in remaining def abort(self, iw = None): # The only state we need to restore is index+worktree. if iw: self.__checkout(self.__stack.head.data.tree, iw, allow_bad_head = True) def run(self, iw = None, set_head = True, allow_bad_head = False, print_current_patch = True): """Execute the transaction. Will either succeed, or fail (with an exception) and do nothing.""" self.__check_consistency() log.log_external_mods(self.__stack) new_head = self.head # Set branch head. if set_head: if iw: try: self.__checkout(new_head.data.tree, iw, allow_bad_head) except git.CheckoutException: # We have to abort the transaction. self.abort(iw) self.__abort() self.__stack.set_head(new_head, self.__msg) if self.__error: if self.__conflicts: out.error(*([self.__error] + self.__conflicts)) else: out.error(self.__error) # Write patches. def write(msg): for pn, commit in self.__patches.items(): if self.__stack.patches.exists(pn): p = self.__stack.patches.get(pn) if commit is None: p.delete() else: p.set_commit(commit, msg) else: self.__stack.patches.new(pn, commit, msg) self.__stack.patchorder.applied = self.__applied self.__stack.patchorder.unapplied = self.__unapplied self.__stack.patchorder.hidden = self.__hidden log.log_entry(self.__stack, msg) old_applied = self.__stack.patchorder.applied if not self.__conflicts: write(self.__msg) else: write(self.__msg + ' (CONFLICT)') if print_current_patch: _print_current_patch(old_applied, self.__applied) if self.__error: return utils.STGIT_CONFLICT else: return utils.STGIT_SUCCESS def __halt(self, msg): self.__error = msg raise TransactionHalted(msg) @staticmethod def __print_popped(popped): if len(popped) == 0: pass elif len(popped) == 1: out.info('Popped %s' % popped[0]) else: out.info('Popped %s -- %s' % (popped[-1], popped[0])) def pop_patches(self, p): """Pop all patches pn for which p(pn) is true. Return the list of other patches that had to be popped to accomplish this. Always succeeds.""" popped = [] for i in range(len(self.applied)): if p(self.applied[i]): popped = self.applied[i:] del self.applied[i:] break popped1 = [pn for pn in popped if not p(pn)] popped2 = [pn for pn in popped if p(pn)] self.unapplied = popped1 + popped2 + self.unapplied self.__print_popped(popped) return popped1 def delete_patches(self, p, quiet = False): """Delete all patches pn for which p(pn) is true. Return the list of other patches that had to be popped to accomplish this. Always succeeds.""" popped = [] all_patches = self.applied + self.unapplied + self.hidden for i in range(len(self.applied)): if p(self.applied[i]): popped = self.applied[i:] del self.applied[i:] break popped = [pn for pn in popped if not p(pn)] self.unapplied = popped + [pn for pn in self.unapplied if not p(pn)] self.hidden = [pn for pn in self.hidden if not p(pn)] self.__print_popped(popped) for pn in all_patches: if p(pn): s = ['', ' (empty)'][self.patches[pn].data.is_nochange()] self.patches[pn] = None if not quiet: out.info('Deleted %s%s' % (pn, s)) return popped def push_patch(self, pn, iw = None, allow_interactive = False, already_merged = False): """Attempt to push the named patch. If this results in conflicts, halts the transaction. If index+worktree are given, spill any conflicts to them.""" out.start('Pushing patch "%s"' % pn) orig_cd = self.patches[pn].data cd = orig_cd.set_committer(None) oldparent = cd.parent cd = cd.set_parent(self.top) if already_merged: # the resulting patch is empty tree = cd.parent.data.tree else: base = oldparent.data.tree ours = cd.parent.data.tree theirs = cd.tree tree, self.temp_index_tree = self.temp_index.merge( base, ours, theirs, self.temp_index_tree) s = '' merge_conflict = False if not tree: if iw is None: self.__halt('%s does not apply cleanly' % pn) try: self.__checkout(ours, iw, allow_bad_head = False) except git.CheckoutException: self.__halt('Index/worktree dirty') try: interactive = (allow_interactive and config.getbool('stgit.autoimerge')) iw.merge(base, ours, theirs, interactive = interactive) tree = iw.index.write_tree() self.__current_tree = tree s = 'modified' except git.MergeConflictException as e: tree = ours merge_conflict = True self.__conflicts = e.conflicts s = 'conflict' except git.MergeException as e: self.__halt(str(e)) cd = cd.set_tree(tree) if any(getattr(cd, a) != getattr(orig_cd, a) for a in ['parent', 'tree', 'author', 'message']): comm = self.__stack.repository.commit(cd) if merge_conflict: # When we produce a conflict, we'll run the update() # function defined below _after_ having done the # checkout in run(). To make sure that we check out # the real stack top (as it will look after update() # has been run), set it hard here. self.head = comm else: comm = None s = 'unmodified' if already_merged: s = 'merged' elif not merge_conflict and cd.is_nochange(): s = 'empty' out.done(s) if merge_conflict: # We've just caused conflicts, so we must allow them in # the final checkout. self.__allow_conflicts = lambda trans: True # Update the stack state if comm: self.patches[pn] = comm if pn in self.hidden: x = self.hidden else: x = self.unapplied del x[x.index(pn)] self.applied.append(pn) if merge_conflict: self.__halt("%d merge conflict(s)" % len(self.__conflicts)) def push_tree(self, pn): """Push the named patch without updating its tree.""" orig_cd = self.patches[pn].data cd = orig_cd.set_committer(None).set_parent(self.top) s = '' if any(getattr(cd, a) != getattr(orig_cd, a) for a in ['parent', 'tree', 'author', 'message']): self.patches[pn] = self.__stack.repository.commit(cd) else: s = ' (unmodified)' if cd.is_nochange(): s = ' (empty)' out.info('Pushed %s%s' % (pn, s)) if pn in self.hidden: x = self.hidden else: x = self.unapplied del x[x.index(pn)] self.applied.append(pn) def reorder_patches(self, applied, unapplied, hidden = None, iw = None, allow_interactive = False): """Push and pop patches to attain the given ordering.""" if hidden is None: hidden = self.hidden common = len(list(takewhile(lambda a: a[0] == a[1], zip(self.applied, applied)))) to_pop = set(self.applied[common:]) self.pop_patches(lambda pn: pn in to_pop) for pn in applied[common:]: self.push_patch(pn, iw, allow_interactive = allow_interactive) # We only get here if all the pushes succeeded. assert self.applied == applied assert set(self.unapplied + self.hidden) == set(unapplied + hidden) self.unapplied = unapplied self.hidden = hidden def check_merged(self, patches, tree = None, quiet = False): """Return a subset of patches already merged.""" if not quiet: out.start('Checking for patches merged upstream') merged = [] if tree: self.temp_index.read_tree(tree) self.temp_index_tree = tree elif self.temp_index_tree != self.stack.head.data.tree: self.temp_index.read_tree(self.stack.head.data.tree) self.temp_index_tree = self.stack.head.data.tree for pn in reversed(patches): # check whether patch changes can be reversed in the current index cd = self.patches[pn].data if cd.is_nochange(): continue try: self.temp_index.apply_treediff(cd.tree, cd.parent.data.tree, quiet = True) merged.append(pn) # The self.temp_index was modified by apply_treediff() so # force read_tree() the next time merge() is used. self.temp_index_tree = None except git.MergeException: pass if not quiet: out.done('%d found' % len(merged)) return merged stgit-0.19/stgit/main.py000066400000000000000000000155761337022307200152420ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Basic quilt-like functionality""" from __future__ import (absolute_import, division, print_function, unicode_literals) import os import sys import traceback from stgit import argparse, run, utils from stgit.compat import environ_get, fsdecode_utf8 from stgit.config import config from stgit.out import out from stgit.pager import pager import stgit.commands __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ class CommandAlias(object): def __init__(self, name, command): self.__command = command self.__name__ = name self.usage = [''] self.help = 'Alias for "%s ".' % self.__command self.options = [] def func(self, args): cmd = self.__command.split() + args p = run.Run(*cmd) p.discard_exitcode().run() return p.exitcode def is_cmd_alias(cmd): return isinstance(cmd, CommandAlias) def append_alias_commands(cmd_list): for (name, command) in config.getstartswith('stgit.alias.'): name = utils.strip_prefix('stgit.alias.', name) cmd_list[name] = (CommandAlias(name, command), 'Alias commands', command) # # The commands map # class Commands(dict): """Commands class. It performs on-demand module loading """ def canonical_cmd(self, key): """Return the canonical name for a possibly-shortenned command name. """ candidates = [cmd for cmd in self if cmd.startswith(key)] if not candidates: out.error('Unknown command: %s' % key, 'Try "%s help" for a list of supported commands' % prog) sys.exit(utils.STGIT_GENERAL_ERROR) elif len(candidates) > 1: out.error('Ambiguous command: %s' % key, 'Candidates are: %s' % ', '.join(candidates)) sys.exit(utils.STGIT_GENERAL_ERROR) return candidates[0] def __getitem__(self, key): cmd_mod = self.get(key) or self.get(self.canonical_cmd(key)) if is_cmd_alias(cmd_mod): return cmd_mod else: return stgit.commands.get_command(cmd_mod) cmd_list = stgit.commands.get_commands() append_alias_commands(cmd_list) commands = Commands((cmd, mod) for cmd, (mod, kind, help) in cmd_list.items()) def print_help(): print('usage: %s [options]' % os.path.basename(sys.argv[0])) print() print('Generic commands:') print(' help print the detailed command usage') print(' version display version information') print(' copyright display copyright information') print() stgit.commands.pretty_command_list(cmd_list, sys.stdout) # # The main function (command dispatcher) # def _main(): """The main function """ global prog sys.argv = list(map(fsdecode_utf8, sys.argv)) prog = os.path.basename(sys.argv[0]) if len(sys.argv) < 2: print('usage: %s ' % prog, file=sys.stderr) print(' Try "%s --help" for a list of supported commands' % prog, file=sys.stderr) sys.exit(utils.STGIT_GENERAL_ERROR) cmd = sys.argv[1] if cmd in ['-h', '--help']: if len(sys.argv) >= 3: cmd = commands.canonical_cmd(sys.argv[2]) sys.argv[2] = '--help' else: print_help() sys.exit(utils.STGIT_SUCCESS) if cmd == 'help': if len(sys.argv) == 3 and not sys.argv[2] in ['-h', '--help']: cmd = commands.canonical_cmd(sys.argv[2]) sys.argv[0] += ' %s' % cmd command = commands[cmd] parser = argparse.make_option_parser(command) if is_cmd_alias(command): parser.remove_option('-h') pager(parser.format_help().encode()) else: print_help() sys.exit(utils.STGIT_SUCCESS) if cmd in ['-v', '--version', 'version']: from stgit.version import get_version print('Stacked GIT %s' % get_version()) os.system('git --version') print('Python version %s' % sys.version) sys.exit(utils.STGIT_SUCCESS) if cmd in ['copyright']: print(__copyright__) sys.exit(utils.STGIT_SUCCESS) # re-build the command line arguments cmd = commands.canonical_cmd(cmd) sys.argv[0] += ' %s' % cmd del sys.argv[1] command = commands[cmd] if is_cmd_alias(command): sys.exit(command.func(sys.argv[1:])) parser = argparse.make_option_parser(command) directory = command.directory # These modules are only used from this point onwards and do not # need to be imported earlier try: from configparser import ParsingError, NoSectionError except ImportError: from ConfigParser import ParsingError, NoSectionError from stgit.exception import StgException from stgit.config import config_setup from stgit.stack import Series try: debug_level = int(environ_get('STGIT_DEBUG_LEVEL', 0)) except ValueError: out.error('Invalid STGIT_DEBUG_LEVEL environment variable') sys.exit(utils.STGIT_GENERAL_ERROR) try: (options, args) = parser.parse_args() directory.setup() config_setup() # Some commands don't (always) need an initialized series. if directory.needs_current_series: if hasattr(options, 'branch') and options.branch: command.crt_series = Series(options.branch) else: command.crt_series = Series() ret = command.func(parser, options, args) except (StgException, IOError, ParsingError, NoSectionError) as err: directory.write_log(cmd) if debug_level > 0: traceback.print_exc(file=sys.stderr) out.error(str(err), title = '%s %s' % (prog, cmd)) sys.exit(utils.STGIT_COMMAND_ERROR) except SystemExit: # Triggered by the option parser when it finds bad commandline # parameters. sys.exit(utils.STGIT_COMMAND_ERROR) except KeyboardInterrupt: sys.exit(utils.STGIT_GENERAL_ERROR) except: out.error('Unhandled exception:') traceback.print_exc(file=sys.stderr) sys.exit(utils.STGIT_BUG_ERROR) directory.write_log(cmd) sys.exit(ret or utils.STGIT_SUCCESS) def main(): try: _main() finally: run.finish_logging() stgit-0.19/stgit/out.py000066400000000000000000000111411337022307200151050ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import io import sys import textwrap __copyright__ = """ Copyright (C) 2007, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ class Output(object): def __init__(self, file): if file is not None: self.write = file.write self.write_bytes = file.buffer.write self.flush = file.flush else: self.write = self.write_bytes = lambda s: None self.flush = lambda: None self.at_start_of_line = True self.level = 0 def new_line(self): """Ensure that we're at the beginning of a line.""" if not self.at_start_of_line: self.write('\n') self.at_start_of_line = True def single_line(self, msg, print_newline=True, need_newline=True): """Write a single line. Newline before and after are separately configurable.""" if need_newline: self.new_line() if self.at_start_of_line: self.write(' '*self.level) self.write(msg) if print_newline: self.write('\n') self.at_start_of_line = True else: self.flush() self.at_start_of_line = False def tagged_lines(self, tag, lines): tag += ': ' width = 79 - 2*self.level - len(tag) lines = [wl for line in lines for wl in textwrap.wrap(line, width, break_long_words=False)] for line in lines: self.single_line(tag + line) tag = ' '*len(tag) def write_line(self, line): """Write one line of text on a lines of its own, not indented.""" self.new_line() self.write('%s\n' % line) self.at_start_of_line = True def write_raw(self, string): """Write an arbitrary string, possibly containing newlines.""" self.new_line() self.write(string) self.at_start_of_line = string.endswith('\n') def write_bytes(self, byte_data): self.new_line() self.write_bytes(byte_data) self.at_start_of_line = byte_data.endswith(b'\n') class MessagePrinter(object): def __init__(self, file=None): if file: self.__stdout = self.__stderr = Output(file) else: self.__stdout = Output(io.open(sys.stdout.fileno(), 'w', buffering=1, encoding='utf-8')) self.__stderr = Output(io.open(sys.stderr.fileno(), 'w', buffering=1, encoding='utf-8')) if file or sys.stdout.isatty(): self.__out = self.__stdout else: self.__out = Output(None) def stdout(self, line): """Write a line to stdout.""" self.__stdout.write_line(line) def stdout_raw(self, string): """Write a string possibly containing newlines to stdout.""" self.__stdout.write_raw(string) def stdout_bytes(self, byte_data): self.__stdout.write_bytes(byte_data) def err_raw(self, string): """Write a string possibly containing newlines to the error output.""" self.__stderr.write_raw(string) def info(self, *msgs): for msg in msgs: self.__out.single_line(msg) def note(self, *msgs, **kw): self.__out.tagged_lines(kw.get('title', 'Notice'), msgs) def warn(self, *msgs, **kw): self.__stderr.tagged_lines(kw.get('title', 'Warning'), msgs) def error(self, *msgs, **kw): self.__stderr.tagged_lines(kw.get('title', 'Error'), msgs) def start(self, msg): """Start a long-running operation.""" self.__out.single_line('%s ... ' % msg, print_newline=False) self.__out.level += 1 def done(self, extramsg = None): """Finish long-running operation.""" self.__out.level -= 1 if extramsg: msg = 'done (%s)' % extramsg else: msg = 'done' self.__out.single_line(msg, need_newline=False) out = MessagePrinter() stgit-0.19/stgit/pager.py000066400000000000000000000024071337022307200154010ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os import subprocess import sys from stgit.out import out def pager(msg): if any([not hasattr(sys.stdin, 'isatty'), not hasattr(sys.stdout, 'isatty'), not sys.stdin.isatty(), not sys.stdout.isatty()]): return out.stdout_bytes(msg) pager = _choose_pager() if pager: return _run_pager(pager, msg) else: return out.stdout_bytes(msg) def _run_pager(pager, msg): proc = subprocess.Popen(pager, shell=True, stdin=subprocess.PIPE) try: proc.stdin.write(msg) except (KeyboardInterrupt, OSError): pass finally: proc.stdin.close() while True: try: proc.wait() break except KeyboardInterrupt: pass def _choose_pager(): for k in ['GIT_PAGER', 'PAGER', 'MANPAGER']: pager = os.environ.get(k) if pager: return pager if hasattr(os, 'system'): for pager in ['less', 'more']: if os.system('{pager} -V >{null} 2>{null}'.format( pager=pager, null=os.devnull)) == 0: return pager return None stgit-0.19/stgit/run.py000066400000000000000000000220361337022307200151070ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import datetime import io import subprocess from stgit.compat import (text, environ_get, environ_copy, file_wrapper, fsencode_utf8) from stgit.exception import StgException from stgit.out import out, MessagePrinter __copyright__ = """ Copyright (C) 2007, Karl Hasselström This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ class RunException(StgException): """Thrown when something bad happened when we tried to run the subprocess.""" pass def get_log_mode(spec): if ':' not in spec: spec += ':' (log_mode, outfile) = spec.split(':', 1) all_log_modes = ['debug', 'profile'] if log_mode and log_mode not in all_log_modes: out.warn(('Unknown log mode "%s" specified in $STGIT_SUBPROCESS_LOG.' % log_mode), 'Valid values are: %s' % ', '.join(all_log_modes)) if outfile: f = MessagePrinter(io.open(outfile, 'a', encoding='utf-8')) else: f = out return (log_mode, f) _log_mode, _logfile = get_log_mode(environ_get('STGIT_SUBPROCESS_LOG', '')) if _log_mode == 'profile': _log_starttime = datetime.datetime.now() _log_subproctime = 0.0 def duration(t1, t2): d = t2 - t1 return 86400*d.days + d.seconds + 1e-6*d.microseconds def finish_logging(): if _log_mode != 'profile': return ttime = duration(_log_starttime, datetime.datetime.now()) rtime = ttime - _log_subproctime _logfile.info('Total time: %1.3f s' % ttime, 'Time spent in subprocess calls: %1.3f s (%1.1f%%)' % (_log_subproctime, 100*_log_subproctime/ttime), 'Remaining time: %1.3f s (%1.1f%%)' % (rtime, 100*rtime/ttime)) class Run(object): exc = RunException def __init__(self, *cmd): self.__cmd = list(cmd) for c in cmd: if not isinstance(c, text): raise Exception('Bad command: %r' % (cmd, )) self.__good_retvals = [0] self.__env = self.__cwd = None self.__indata = None self.__in_encoding = 'utf-8' self.__out_encoding = 'utf-8' self.__discard_stderr = False def __prep_cmd(self): return [fsencode_utf8(c) for c in self.__cmd] def __prep_env(self): if self.__env: return dict((fsencode_utf8(k), fsencode_utf8(v)) for k, v in self.__env.items()) else: return self.__env def __log_start(self): if _log_mode == 'debug': _logfile.start('Running subprocess %s' % self.__cmd) if self.__cwd is not None: _logfile.info('cwd: %s' % self.__cwd) if self.__env is not None: for k in sorted(self.__env): v = environ_get(k) if v is None or v != self.__env[k]: _logfile.info('%s: %s' % (k, self.__env[k])) elif _log_mode == 'profile': _logfile.start('Running subprocess %s' % self.__cmd) self.__starttime = datetime.datetime.now() def __log_end(self, retcode): global _log_subproctime, _log_starttime if _log_mode == 'debug': _logfile.done('return code: %d' % retcode) elif _log_mode == 'profile': n = datetime.datetime.now() d = duration(self.__starttime, n) _logfile.done('%1.3f s' % d) _log_subproctime += d _logfile.info('Time since program start: %1.3f s' % duration(_log_starttime, n)) def __check_exitcode(self): if self.__good_retvals is None: return if self.exitcode not in self.__good_retvals: raise self.exc('%s failed with code %d' % (self.__cmd[0], self.exitcode)) def __run_io(self): """Run with captured IO.""" self.__log_start() try: p = subprocess.Popen(self.__prep_cmd(), env=self.__prep_env(), cwd=self.__cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) outdata, errdata = p.communicate(self.__indata) self.exitcode = p.returncode except OSError as e: raise self.exc('%s failed: %s' % (self.__cmd[0], e)) if errdata and not self.__discard_stderr: out.err_raw(errdata.decode(self.__out_encoding)) self.__log_end(self.exitcode) self.__check_exitcode() if self.__out_encoding: return outdata.decode(self.__out_encoding) else: return outdata def __run_noio(self): """Run without captured IO.""" assert self.__indata is None self.__log_start() try: p = subprocess.Popen(self.__prep_cmd(), env=self.__prep_env(), cwd=self.__cwd) self.exitcode = p.wait() except OSError as e: raise self.exc('%s failed: %s' % (self.__cmd[0], e)) self.__log_end(self.exitcode) self.__check_exitcode() def run_background(self): """Run as a background process.""" assert self.__indata is None try: p = subprocess.Popen(self.__prep_cmd(), env=self.__prep_env(), cwd=self.__cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as e: raise self.exc('%s failed: %s' % (self.__cmd[0], e)) if self.__in_encoding: if hasattr(p.stdin, 'readable'): self.stdin = io.TextIOWrapper( p.stdin, encoding=self.__in_encoding) else: self.stdin = io.TextIOWrapper( file_wrapper(p.stdin, writable=True), encoding=self.__in_encoding) else: self.stdin = p.stdin self.stdout = p.stdout self.stderr = p.stderr self.wait = p.wait self.pid = lambda: p.pid return self def returns(self, retvals): self.__good_retvals = retvals return self def discard_exitcode(self): self.__good_retvals = None return self def discard_stderr(self, discard=True): self.__discard_stderr = discard return self def env(self, env): self.__env = environ_copy() self.__env.update(env) return self def cwd(self, cwd): self.__cwd = cwd return self def encoding(self, encoding): self.__in_encoding = encoding return self def decoding(self, encoding): self.__out_encoding = encoding return self def raw_input(self, indata): if self.__in_encoding: self.__indata = indata.encode(self.__in_encoding) else: self.__indata = indata return self def input_nulterm(self, lines): return self.raw_input('\0'.join(lines)) def no_output(self): outdata = self.__run_io() if outdata: raise self.exc('%s produced output' % self.__cmd[0]) def discard_output(self): self.__run_io() def raw_output(self): return self.__run_io() def output_lines(self, sep='\n'): outdata = self.__run_io() if outdata.endswith(sep): outdata = outdata[:-1] if outdata: return outdata.split(sep) else: return [] def output_one_line(self, sep='\n'): outlines = self.output_lines(sep) if len(outlines) == 1: return outlines[0] else: raise self.exc('%s produced %d lines, expected 1' % (self.__cmd[0], len(outlines))) def run(self): """Just run, with no IO redirection.""" self.__run_noio() def xargs(self, xargs): """Just run, with no IO redirection. The extra arguments are appended to the command line a few at a time; the command is run as many times as needed to consume them all.""" step = 100 basecmd = self.__cmd for i in range(0, len(xargs), step): self.__cmd = basecmd + xargs[i:i+step] self.__run_noio() self.__cmd = basecmd stgit-0.19/stgit/stack.py000066400000000000000000001155241337022307200154150ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Basic quilt-like functionality""" from __future__ import (absolute_import, division, print_function, unicode_literals) from email.utils import formatdate import os import re from stgit import git, basedir, templates from stgit.compat import text from stgit.config import config from stgit.exception import StackException from stgit.lib import git as libgit, stackupgrade from stgit.out import out from stgit.run import Run from stgit.utils import (add_sign_line, append_string, append_strings, call_editor, create_empty_file, insert_string, make_patch_name, read_string, read_strings, rename, write_string, write_strings) __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ class FilterUntil(object): def __init__(self): self.should_print = True def __call__(self, x, until_test, prefix): if until_test(x): self.should_print = False if self.should_print: return x[0:len(prefix)] != prefix return False # # Functions # __comment_prefix = 'STG:' __patch_prefix = 'STG_PATCH:' def __clean_comments(f): """Removes lines marked for status in a commit file """ f.seek(0) # remove status-prefixed lines lines = f.readlines() patch_filter = FilterUntil() until_test = lambda t: t == (__patch_prefix + '\n') lines = [l for l in lines if patch_filter(l, until_test, __comment_prefix)] # remove empty lines at the end while len(lines) != 0 and lines[-1] == '\n': del lines[-1] f.seek(0) f.truncate() f.writelines(lines) # TODO: move this out of the stgit.stack module, it is really for # higher level commands to handle the user interaction def edit_file(series, line, comment, show_patch = True): fname = '.stgitmsg.txt' tmpl = templates.get_template('patchdescr.tmpl') with open(fname, 'w+') as f: if line: print(line, file=f) elif tmpl: print(tmpl, end=' ', file=f) else: print(file=f) print(__comment_prefix, comment, file=f) print(__comment_prefix, 'Lines prefixed with "%s" will be automatically removed.' % __comment_prefix, file=f) print(__comment_prefix, 'Trailing empty lines will be automatically removed.', file=f) if show_patch: print(__patch_prefix, file=f) # series.get_patch(series.get_current()).get_top() diff_str = git.diff(rev1 = series.get_patch(series.get_current()).get_bottom()) f.write(diff_str) #Vim modeline must be near the end. print(__comment_prefix, 'vi: set textwidth=75 filetype=diff nobackup:', file=f) call_editor(fname) with open(fname, 'r+') as f: __clean_comments(f) f.seek(0) result = f.read() os.remove(fname) return result # # Classes # class StgitObject(object): """An object with stgit-like properties stored as files in a directory """ def _set_dir(self, dir): self.__dir = dir def _dir(self): return self.__dir def create_empty_field(self, name): create_empty_file(os.path.join(self.__dir, name)) def _get_field(self, name, multiline = False): id_file = os.path.join(self.__dir, name) if os.path.isfile(id_file): line = read_string(id_file, multiline) if line == '': return None else: return line else: return None def _set_field(self, name, value, multiline = False): fname = os.path.join(self.__dir, name) if value and value != '': write_string(fname, value, multiline) elif os.path.isfile(fname): os.remove(fname) class Patch(StgitObject): """Basic patch implementation """ def __init_refs(self): self.__top_ref = self.__refs_base + '/' + self.__name self.__log_ref = self.__top_ref + '.log' def __init__(self, name, series_dir, refs_base): self.__series_dir = series_dir self.__name = name self._set_dir(os.path.join(self.__series_dir, self.__name)) self.__refs_base = refs_base self.__init_refs() def create(self): os.mkdir(self._dir()) def delete(self, keep_log = False): if os.path.isdir(self._dir()): for f in os.listdir(self._dir()): os.remove(os.path.join(self._dir(), f)) os.rmdir(self._dir()) else: out.warn('Patch directory "%s" does not exist' % self._dir()) try: # the reference might not exist if the repository was corrupted git.delete_ref(self.__top_ref) except git.GitException as e: out.warn(str(e)) if not keep_log and git.ref_exists(self.__log_ref): git.delete_ref(self.__log_ref) def get_name(self): return self.__name def rename(self, newname): olddir = self._dir() old_top_ref = self.__top_ref old_log_ref = self.__log_ref self.__name = newname self._set_dir(os.path.join(self.__series_dir, self.__name)) self.__init_refs() git.rename_ref(old_top_ref, self.__top_ref) if git.ref_exists(old_log_ref): git.rename_ref(old_log_ref, self.__log_ref) os.rename(olddir, self._dir()) def __update_top_ref(self, ref): git.set_ref(self.__top_ref, ref) self._set_field('top', ref) self._set_field('bottom', git.get_commit(ref).get_parent()) def __update_log_ref(self, ref): git.set_ref(self.__log_ref, ref) def get_bottom(self): return git.get_commit(self.get_top()).get_parent() def get_top(self): return git.rev_parse(self.__top_ref) def set_top(self, value, backup = False): if backup: curr_top = self.get_top() self._set_field('top.old', curr_top) self._set_field('bottom.old', git.get_commit(curr_top).get_parent()) self.__update_top_ref(value) def get_description(self): return self._get_field('description', True) def set_description(self, line): self._set_field('description', line, True) def get_authname(self): return self._get_field('authname') def set_authname(self, name): self._set_field('authname', name or git.author().name) def get_authemail(self): return self._get_field('authemail') def set_authemail(self, email): self._set_field('authemail', email or git.author().email) def get_authdate(self): date = self._get_field('authdate') if not date: return date if re.match(r'[0-9]+\s+[+-][0-9]+', date): # Unix time (seconds) + time zone secs_tz = date.split() date = formatdate(int(secs_tz[0]))[:-5] + secs_tz[1] return date def set_authdate(self, date): self._set_field('authdate', date or git.author().date) def get_commname(self): return self._get_field('commname') def set_commname(self, name): self._set_field('commname', name or git.committer().name) def get_commemail(self): return self._get_field('commemail') def set_commemail(self, email): self._set_field('commemail', email or git.committer().email) def get_log(self): return self._get_field('log') def set_log(self, value, backup = False): self._set_field('log', value) self.__update_log_ref(value) class PatchSet(StgitObject): def __init__(self, name = None): try: if name: self.set_name (name) else: self.set_name (git.get_head_file()) self.__base_dir = basedir.get() except git.GitException as ex: raise StackException('GIT tree not initialised: %s' % ex) self._set_dir(os.path.join(self.__base_dir, 'patches', self.get_name())) def get_name(self): return self.__name def set_name(self, name): self.__name = name def _basedir(self): return self.__base_dir def get_head(self): """Return the head of the branch """ crt = self.get_current_patch() if crt: return crt.get_top() else: return self.get_base() def get_protected(self): return os.path.isfile(os.path.join(self._dir(), 'protected')) def protect(self): protect_file = os.path.join(self._dir(), 'protected') if not os.path.isfile(protect_file): create_empty_file(protect_file) def unprotect(self): protect_file = os.path.join(self._dir(), 'protected') if os.path.isfile(protect_file): os.remove(protect_file) def __branch_descr(self): return 'branch.%s.description' % self.get_name() def get_description(self): return config.get(self.__branch_descr()) or '' def set_description(self, line): if line: config.set(self.__branch_descr(), line) else: config.unset(self.__branch_descr()) def head_top_equal(self): """Return true if the head and the top are the same """ crt = self.get_current_patch() if not crt: # we don't care, no patches applied return True return git.get_head() == crt.get_top() def is_initialised(self): """Checks if series is already initialised """ return config.get(stackupgrade.format_version_key(self.get_name()) ) is not None def shortlog(patches): log = ''.join(Run('git', 'log', '--pretty=short', p.get_top(), '^%s' % p.get_bottom()).raw_output() for p in patches) return Run('git', 'shortlog').raw_input(log).raw_output() class Series(PatchSet): """Class including the operations on series """ def __init__(self, name = None): """Takes a series name as the parameter. """ PatchSet.__init__(self, name) # Update the branch to the latest format version if it is # initialized, but don't touch it if it isn't. stackupgrade.update_to_current_format_version( libgit.Repository.default(), self.get_name()) self.__refs_base = 'refs/patches/%s' % self.get_name() self.__applied_file = os.path.join(self._dir(), 'applied') self.__unapplied_file = os.path.join(self._dir(), 'unapplied') self.__hidden_file = os.path.join(self._dir(), 'hidden') # where this series keeps its patches self.__patch_dir = os.path.join(self._dir(), 'patches') # trash directory self.__trash_dir = os.path.join(self._dir(), 'trash') def __patch_name_valid(self, name): """Raise an exception if the patch name is not valid. """ if not name or re.search(r'[^\w.-]', name): raise StackException('Invalid patch name: "%s"' % name) def get_patch(self, name): """Return a Patch object for the given name """ return Patch(name, self.__patch_dir, self.__refs_base) def get_current_patch(self): """Return a Patch object representing the topmost patch, or None if there is no such patch.""" crt = self.get_current() if not crt: return None return self.get_patch(crt) def get_current(self): """Return the name of the topmost patch, or None if there is no such patch.""" try: applied = self.get_applied() except StackException: # No "applied" file: branch is not initialized. return None try: return applied[-1] except IndexError: # No patches applied. return None def get_applied(self): if not os.path.isfile(self.__applied_file): raise StackException('Branch "%s" not initialised' % self.get_name()) return read_strings(self.__applied_file) def set_applied(self, applied): write_strings(self.__applied_file, applied) def get_unapplied(self): if not os.path.isfile(self.__unapplied_file): raise StackException('Branch "%s" not initialised' % self.get_name()) return read_strings(self.__unapplied_file) def set_unapplied(self, unapplied): write_strings(self.__unapplied_file, unapplied) def get_hidden(self): if not os.path.isfile(self.__hidden_file): return [] return read_strings(self.__hidden_file) def set_hidden(self, hidden): write_strings(self.__hidden_file, hidden) def get_base(self): # Return the parent of the bottommost patch, if there is one. if os.path.isfile(self.__applied_file): with open(self.__applied_file) as f: bottommost = f.readline().strip() if bottommost: return self.get_patch(bottommost).get_bottom() # No bottommost patch, so just return HEAD return git.get_head() def get_parent_remote(self): value = config.get('branch.%s.remote' % self.get_name()) if value: return value elif 'origin' in git.remotes_list(): out.note(('No parent remote declared for stack "%s",' ' defaulting to "origin".' % self.get_name()), ('Consider setting "branch.%s.remote" and' ' "branch.%s.merge" with "git config".' % (self.get_name(), self.get_name()))) return 'origin' else: raise StackException('Cannot find a parent remote for "%s"' % self.get_name()) def __set_parent_remote(self, remote): config.set('branch.%s.remote' % self.get_name(), remote) def get_parent_branch(self): value = config.get('branch.%s.stgit.parentbranch' % self.get_name()) if value: return value elif git.rev_parse('heads/origin'): out.note(('No parent branch declared for stack "%s",' ' defaulting to "heads/origin".' % self.get_name()), ('Consider setting "branch.%s.stgit.parentbranch"' ' with "git config".' % self.get_name())) return 'heads/origin' else: raise StackException('Cannot find a parent branch for "%s"' % self.get_name()) def __set_parent_branch(self, name): if config.get('branch.%s.remote' % self.get_name()): # Never set merge if remote is not set to avoid # possibly-erroneous lookups into 'origin' config.set('branch.%s.merge' % self.get_name(), name) config.set('branch.%s.stgit.parentbranch' % self.get_name(), name) def set_parent(self, remote, localbranch): if localbranch: if remote: self.__set_parent_remote(remote) self.__set_parent_branch(localbranch) # We'll enforce this later # else: # raise StackException('Parent branch (%s) should be specified for %s' % # localbranch, self.get_name()) def __patch_is_current(self, patch): return patch.get_name() == self.get_current() def patch_applied(self, name): """Return true if the patch exists in the applied list """ return name in self.get_applied() def patch_unapplied(self, name): """Return true if the patch exists in the unapplied list """ return name in self.get_unapplied() def patch_hidden(self, name): """Return true if the patch is hidden. """ return name in self.get_hidden() def patch_exists(self, name): """Return true if there is a patch with the given name, false otherwise.""" return self.patch_applied(name) or self.patch_unapplied(name) \ or self.patch_hidden(name) def init(self, create_at=False, parent_remote=None, parent_branch=None): """Initialises the stgit series """ if self.is_initialised(): raise StackException('%s already initialized' % self.get_name()) for d in [self._dir()]: if os.path.exists(d): raise StackException('%s already exists' % d) if (create_at!=False): git.create_branch(self.get_name(), create_at) os.makedirs(self.__patch_dir) self.set_parent(parent_remote, parent_branch) self.create_empty_field('applied') self.create_empty_field('unapplied') config.set(stackupgrade.format_version_key(self.get_name()), text(stackupgrade.FORMAT_VERSION)) def rename(self, to_name): """Renames a series """ to_stack = Series(to_name) if to_stack.is_initialised(): raise StackException('"%s" already exists' % to_stack.get_name()) patches = self.get_applied() + self.get_unapplied() git.rename_branch(self.get_name(), to_name) for patch in patches: git.rename_ref('refs/patches/%s/%s' % (self.get_name(), patch), 'refs/patches/%s/%s' % (to_name, patch)) git.rename_ref('refs/patches/%s/%s.log' % (self.get_name(), patch), 'refs/patches/%s/%s.log' % (to_name, patch)) if os.path.isdir(self._dir()): rename(os.path.join(self._basedir(), 'patches'), self.get_name(), to_stack.get_name()) # Rename the config section for k in ['branch.%s', 'branch.%s.stgit']: config.rename_section(k % self.get_name(), k % to_name) self.__init__(to_name) def clone(self, target_series): """Clones a series """ try: # allow cloning of branches not under StGIT control base = self.get_base() except: base = git.get_head() Series(target_series).init(create_at = base) new_series = Series(target_series) # generate an artificial description file new_series.set_description('clone of "%s"' % self.get_name()) # clone self's entire series as unapplied patches try: # allow cloning of branches not under StGIT control applied = self.get_applied() unapplied = self.get_unapplied() patches = applied + unapplied patches.reverse() except: patches = applied = unapplied = [] for p in patches: patch = self.get_patch(p) newpatch = new_series.new_patch(p, message = patch.get_description(), can_edit = False, unapplied = True, bottom = patch.get_bottom(), top = patch.get_top(), author_name = patch.get_authname(), author_email = patch.get_authemail(), author_date = patch.get_authdate()) if patch.get_log(): out.info('Setting log to %s' % patch.get_log()) newpatch.set_log(patch.get_log()) else: out.info('No log for %s' % p) # fast forward the cloned series to self's top new_series.forward_patches(applied) # Clone parent informations value = config.get('branch.%s.remote' % self.get_name()) if value: config.set('branch.%s.remote' % target_series, value) value = config.get('branch.%s.merge' % self.get_name()) if value: config.set('branch.%s.merge' % target_series, value) value = config.get('branch.%s.stgit.parentbranch' % self.get_name()) if value: config.set('branch.%s.stgit.parentbranch' % target_series, value) def delete(self, force = False, cleanup = False): """Deletes an stgit series """ if self.is_initialised(): patches = self.get_unapplied() + self.get_applied() + \ self.get_hidden() if not force and patches: raise StackException( 'Cannot %s: the series still contains patches' % ('delete', 'clean up')[cleanup]) for p in patches: self.get_patch(p).delete() # remove the trash directory if any if os.path.exists(self.__trash_dir): for fname in os.listdir(self.__trash_dir): os.remove(os.path.join(self.__trash_dir, fname)) os.rmdir(self.__trash_dir) # FIXME: find a way to get rid of those manual removals # (move functionality to StgitObject ?) if os.path.exists(self.__applied_file): os.remove(self.__applied_file) if os.path.exists(self.__unapplied_file): os.remove(self.__unapplied_file) if os.path.exists(self.__hidden_file): os.remove(self.__hidden_file) if os.path.exists(self._dir()+'/orig-base'): os.remove(self._dir()+'/orig-base') if not os.listdir(self.__patch_dir): os.rmdir(self.__patch_dir) else: out.warn('Patch directory %s is not empty' % self.__patch_dir) try: os.removedirs(self._dir()) except OSError: raise StackException('Series directory %s is not empty' % self._dir()) if not cleanup: try: git.delete_branch(self.get_name()) except git.GitException: out.warn('Could not delete branch "%s"' % self.get_name()) config.remove_section('branch.%s' % self.get_name()) config.remove_section('branch.%s.stgit' % self.get_name()) def refresh_patch(self, files = None, message = None, edit = False, empty = False, show_patch = False, cache_update = True, author_name = None, author_email = None, author_date = None, committer_name = None, committer_email = None, backup = True, sign_str = None, log = 'refresh', notes = None, bottom = None): """Generates a new commit for the topmost patch """ patch = self.get_current_patch() if not patch: raise StackException('No patches applied') descr = patch.get_description() if not (message or descr): edit = True descr = '' elif message: descr = message # TODO: move this out of the stgit.stack module, it is really # for higher level commands to handle the user interaction if not message and edit: descr = edit_file(self, descr.rstrip(), \ 'Please edit the description for patch "%s" ' \ 'above.' % patch.get_name(), show_patch) if not author_name: author_name = patch.get_authname() if not author_email: author_email = patch.get_authemail() if not committer_name: committer_name = patch.get_commname() if not committer_email: committer_email = patch.get_commemail() descr = add_sign_line(descr, sign_str, committer_name, committer_email) if not bottom: bottom = patch.get_bottom() if empty: tree_id = git.get_commit(bottom).get_tree() else: tree_id = None commit_id = git.commit(files = files, message = descr, parents = [bottom], cache_update = cache_update, tree_id = tree_id, set_head = True, allowempty = True, author_name = author_name, author_email = author_email, author_date = author_date, committer_name = committer_name, committer_email = committer_email) patch.set_top(commit_id, backup = backup) patch.set_description(descr) patch.set_authname(author_name) patch.set_authemail(author_email) patch.set_authdate(author_date) patch.set_commname(committer_name) patch.set_commemail(committer_email) if log: self.log_patch(patch, log, notes) return commit_id def new_patch(self, name, message = None, can_edit = True, unapplied = False, show_patch = False, top = None, bottom = None, commit = True, author_name = None, author_email = None, author_date = None, committer_name = None, committer_email = None, before_existing = False, sign_str = None): """Creates a new patch, either pointing to an existing commit object, or by creating a new commit object. """ assert commit or (top and bottom) assert not before_existing or (top and bottom) assert not (commit and before_existing) assert (top and bottom) or (not top and not bottom) assert commit or (not top or (bottom == git.get_commit(top).get_parent())) if name is not None: self.__patch_name_valid(name) if self.patch_exists(name): raise StackException('Patch "%s" already exists' % name) # TODO: move this out of the stgit.stack module, it is really # for higher level commands to handle the user interaction def sign(msg): return add_sign_line(msg, sign_str, committer_name or git.committer().name, committer_email or git.committer().email) if not message and can_edit: descr = edit_file( self, sign(''), 'Please enter the description for the patch above.', show_patch) else: descr = sign(message) head = git.get_head() if name is None: name = make_patch_name(descr, self.patch_exists) patch = self.get_patch(name) patch.create() patch.set_description(descr) patch.set_authname(author_name) patch.set_authemail(author_email) patch.set_authdate(author_date) patch.set_commname(committer_name) patch.set_commemail(committer_email) if before_existing: insert_string(self.__applied_file, patch.get_name()) elif unapplied: patches = [patch.get_name()] + self.get_unapplied() write_strings(self.__unapplied_file, patches) set_head = False else: append_string(self.__applied_file, patch.get_name()) set_head = True if commit: if top: top_commit = git.get_commit(top) else: bottom = head top_commit = git.get_commit(head) # create a commit for the patch (may be empty if top == bottom); # only commit on top of the current branch assert(unapplied or bottom == head) commit_id = git.commit(message = descr, parents = [bottom], cache_update = False, tree_id = top_commit.get_tree(), allowempty = True, set_head = set_head, author_name = author_name, author_email = author_email, author_date = author_date, committer_name = committer_name, committer_email = committer_email) # set the patch top to the new commit patch.set_top(commit_id) else: patch.set_top(top) self.log_patch(patch, 'new') return patch def delete_patch(self, name, keep_log = False): """Deletes a patch """ self.__patch_name_valid(name) patch = self.get_patch(name) if self.__patch_is_current(patch): self.pop_patch(name) elif self.patch_applied(name): raise StackException('Cannot remove an applied patch, "%s", ' 'which is not current' % name) elif name not in self.get_unapplied(): raise StackException('Unknown patch "%s"' % name) # save the commit id to a trash file write_string(os.path.join(self.__trash_dir, name), patch.get_top()) patch.delete(keep_log = keep_log) unapplied = self.get_unapplied() unapplied.remove(name) write_strings(self.__unapplied_file, unapplied) def forward_patches(self, names): """Try to fast-forward an array of patches. On return, patches in names[0:returned_value] have been pushed on the stack. Apply the rest with push_patch """ unapplied = self.get_unapplied() forwarded = 0 top = git.get_head() for name in names: assert(name in unapplied) patch = self.get_patch(name) head = top bottom = patch.get_bottom() top = patch.get_top() # top != bottom always since we have a commit for each patch if head == bottom: # reset the backup information. No logging since the # patch hasn't changed patch.set_top(top, backup = True) else: head_tree = git.get_commit(head).get_tree() bottom_tree = git.get_commit(bottom).get_tree() if head_tree == bottom_tree: # We must just reparent this patch and create a new commit # for it descr = patch.get_description() author_name = patch.get_authname() author_email = patch.get_authemail() author_date = patch.get_authdate() committer_name = patch.get_commname() committer_email = patch.get_commemail() top_tree = git.get_commit(top).get_tree() top = git.commit(message = descr, parents = [head], cache_update = False, tree_id = top_tree, allowempty = True, author_name = author_name, author_email = author_email, author_date = author_date, committer_name = committer_name, committer_email = committer_email) patch.set_top(top, backup = True) self.log_patch(patch, 'push(f)') else: top = head # stop the fast-forwarding, must do a real merge break forwarded+=1 unapplied.remove(name) if forwarded == 0: return 0 git.switch(top) append_strings(self.__applied_file, names[0:forwarded]) write_strings(self.__unapplied_file, unapplied) return forwarded def merged_patches(self, names): """Test which patches were merged upstream by reverse-applying them in reverse order. The function returns the list of patches detected to have been applied. The state of the tree is restored to the original one """ patches = [self.get_patch(name) for name in names] patches.reverse() merged = [] for p in patches: if git.apply_diff(p.get_top(), p.get_bottom()): merged.append(p.get_name()) merged.reverse() git.reset() return merged def push_empty_patch(self, name): """Pushes an empty patch on the stack """ unapplied = self.get_unapplied() assert(name in unapplied) # patch = self.get_patch(name) head = git.get_head() append_string(self.__applied_file, name) unapplied.remove(name) write_strings(self.__unapplied_file, unapplied) self.refresh_patch(bottom = head, cache_update = False, log = 'push(m)') def push_patch(self, name): """Pushes a patch on the stack """ unapplied = self.get_unapplied() assert(name in unapplied) patch = self.get_patch(name) head = git.get_head() bottom = patch.get_bottom() top = patch.get_top() # top != bottom always since we have a commit for each patch if head == bottom: # A fast-forward push. Just reset the backup # information. No need for logging patch.set_top(top, backup = True) git.switch(top) append_string(self.__applied_file, name) unapplied.remove(name) write_strings(self.__unapplied_file, unapplied) return False # Need to create a new commit an merge in the old patch ex = None modified = False # Try the fast applying first. If this fails, fall back to the # three-way merge if not git.apply_diff(bottom, top): # if git.apply_diff() fails, the patch requires a diff3 # merge and can be reported as modified modified = True # merge can fail but the patch needs to be pushed try: git.merge_recursive(bottom, head, top) except git.GitException: out.error('The merge failed during "push".', 'Revert the operation with "stg undo".') append_string(self.__applied_file, name) unapplied.remove(name) write_strings(self.__unapplied_file, unapplied) if not ex: # if the merge was OK and no conflicts, just refresh the patch # The GIT cache was already updated by the merge operation if modified: log = 'push(m)' else: log = 'push' self.refresh_patch(bottom = head, cache_update = False, log = log) else: # we make the patch empty, with the merged state in the # working tree. self.refresh_patch(bottom = head, cache_update = False, empty = True, log = 'push(c)') raise StackException(str(ex)) return modified def pop_patch(self, name, keep = False): """Pops the top patch from the stack """ applied = self.get_applied() applied.reverse() assert(name in applied) patch = self.get_patch(name) if git.get_head_file() == self.get_name(): if keep and not git.apply_diff(git.get_head(), patch.get_bottom(), check_index = False): raise StackException( 'Failed to pop patches while preserving the local changes') git.switch(patch.get_bottom(), keep) else: git.set_branch(self.get_name(), patch.get_bottom()) # save the new applied list idx = applied.index(name) + 1 popped = applied[:idx] popped.reverse() unapplied = popped + self.get_unapplied() write_strings(self.__unapplied_file, unapplied) del applied[:idx] applied.reverse() write_strings(self.__applied_file, applied) def empty_patch(self, name): """Returns True if the patch is empty """ self.__patch_name_valid(name) patch = self.get_patch(name) bottom = patch.get_bottom() top = patch.get_top() if bottom == top: return True elif git.get_commit(top).get_tree() \ == git.get_commit(bottom).get_tree(): return True return False def rename_patch(self, oldname, newname): self.__patch_name_valid(newname) applied = self.get_applied() unapplied = self.get_unapplied() if oldname == newname: raise StackException('"To" name and "from" name are the same') if newname in applied or newname in unapplied: raise StackException('Patch "%s" already exists' % newname) if oldname in unapplied: self.get_patch(oldname).rename(newname) unapplied[unapplied.index(oldname)] = newname write_strings(self.__unapplied_file, unapplied) elif oldname in applied: self.get_patch(oldname).rename(newname) applied[applied.index(oldname)] = newname write_strings(self.__applied_file, applied) else: raise StackException('Unknown patch "%s"' % oldname) def log_patch(self, patch, message, notes = None): """Generate a log commit for a patch """ top = git.get_commit(patch.get_top()) old_log = patch.get_log() if message is None: # replace the current log entry if not old_log: raise StackException('No log entry to annotate for patch "%s"' % patch.get_name()) log_commit = git.get_commit(old_log) msg = log_commit.get_log().split('\n')[0] log_parent = log_commit.get_parent() if log_parent: parents = [log_parent] else: parents = [] else: # generate a new log entry msg = '%s\t%s' % (message, top.get_id_hash()) if old_log: parents = [old_log] else: parents = [] if notes: msg += '\n\n' + notes log = git.commit(message = msg, parents = parents, cache_update = False, tree_id = top.get_tree(), allowempty = True) patch.set_log(log) stgit-0.19/stgit/templates.py000066400000000000000000000043621337022307200163030ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Template files look-up""" from __future__ import (absolute_import, division, print_function, unicode_literals) import io import os import sys from stgit import basedir __copyright__ = """ Copyright (C) 2006, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ def get_template(tfile): """Return the string in the template file passed as argument or None if the file wasn't found. """ tmpl_dirs = [ basedir.get(), os.path.join(os.path.expanduser('~'), '.stgit', 'templates'), os.path.join(sys.prefix, 'share', 'stgit', 'templates'), os.path.join(os.path.dirname(__file__), os.pardir, 'templates'), ] for d in tmpl_dirs: tmpl_path = os.path.join(d, tfile) if os.path.isfile(tmpl_path): with io.open(tmpl_path, 'r') as f: return f.read() else: return None def specialize_template(tmpl, tmpl_dict): """Specialize template string using template dict. Returns specialized template as bytes. Since Python 3.3 and 3.4 do not support the interpolation operator (%) on bytes objects; and since we expect at least one tmpl_dict value (diff) to be bytes (not str); we use a recursive approach to specialize the str specifiers using normal interpolation while handling interpolation of bytes values ourselves. """ for k, v in tmpl_dict.items(): if v is None: tmpl_dict[k] = '' elif isinstance(v, bytes): tmpl_dict.pop(k) return v.join(specialize_template(part, tmpl_dict) for part in tmpl.split('%%(%s)s' % k)) else: return (tmpl % tmpl_dict).encode('utf-8') stgit-0.19/stgit/utils.py000066400000000000000000000265451337022307200154540ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Common utility functions""" from __future__ import (absolute_import, division, print_function, unicode_literals) from io import open import errno import os import re import sys import tempfile from stgit.compat import text, environ_get from stgit.config import config from stgit.exception import StgException from stgit.out import out __copyright__ = """ Copyright (C) 2005, Catalin Marinas This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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/. """ def mkdir_file(filename, mode, encoding='utf-8'): """Opens filename with the given mode, creating the directory it's in if it doesn't already exist.""" create_dirs(os.path.dirname(filename)) return open(filename, mode, encoding=encoding) def read_strings(filename, encoding='utf-8'): """Reads the lines from a file """ with open(filename, encoding=encoding) as f: return [line.strip() for line in f.readlines()] def read_string(filename, multiline=False, encoding='utf-8'): """Reads the first line from a file """ with open(filename, encoding=encoding) as f: if multiline: return f.read() else: return f.readline().strip() def write_strings(filename, lines, encoding='utf-8'): """Write 'lines' sequence to file """ with open(filename, 'w+', encoding=encoding) as f: for line in lines: print(line, file=f) def write_string(filename, line, multiline=False, encoding='utf-8'): """Writes 'line' to file and truncates it """ with mkdir_file(filename, 'w+', encoding) as f: line = text(line) print(line, end='' if multiline else '\n', file=f) def append_strings(filename, lines, encoding='utf-8'): """Appends 'lines' sequence to file """ with mkdir_file(filename, 'a+', encoding) as f: for line in lines: print(line, file=f) def append_string(filename, line, encoding='utf-8'): """Appends 'line' to file """ with mkdir_file(filename, 'a+', encoding) as f: print(line, file=f) def insert_string(filename, line, encoding='utf-8'): """Inserts 'line' at the beginning of the file """ with mkdir_file(filename, 'r+', encoding) as f: lines = f.readlines() f.seek(0) f.truncate() print(line, file=f) f.writelines(lines) def create_empty_file(name): """Creates an empty file """ mkdir_file(name, 'w+').close() def list_files_and_dirs(path): """Return the sets of filenames and directory names in a directory.""" files, dirs = [], [] for fd in os.listdir(path): full_fd = os.path.join(path, fd) if os.path.isfile(full_fd): files.append(fd) elif os.path.isdir(full_fd): dirs.append(fd) return files, dirs def walk_tree(basedir): """Starting in the given directory, iterate through all its subdirectories. For each subdirectory, yield the name of the subdirectory (relative to the base directory), the list of filenames in the subdirectory, and the list of directory names in the subdirectory.""" subdirs = [''] while subdirs: subdir = subdirs.pop() files, dirs = list_files_and_dirs(os.path.join(basedir, subdir)) for d in dirs: subdirs.append(os.path.join(subdir, d)) yield subdir, files, dirs def strip_prefix(prefix, string): """Return string, without the prefix. Blow up if string doesn't start with prefix.""" assert string.startswith(prefix) return string[len(prefix):] def strip_suffix(suffix, string): """Return string, without the suffix. Blow up if string doesn't end with suffix.""" assert string.endswith(suffix) return string[:-len(suffix)] def remove_file_and_dirs(basedir, file): """Remove join(basedir, file), and then remove the directory it was in if empty, and try the same with its parent, until we find a nonempty directory or reach basedir.""" os.remove(os.path.join(basedir, file)) try: os.removedirs(os.path.join(basedir, os.path.dirname(file))) except OSError: # file's parent dir may not be empty after removal pass def create_dirs(directory): """Create the given directory, if the path doesn't already exist.""" if directory and not os.path.isdir(directory): create_dirs(os.path.dirname(directory)) try: os.mkdir(directory) except OSError as e: if e.errno != errno.EEXIST: raise e def rename(basedir, file1, file2): """Rename join(basedir, file1) to join(basedir, file2), not leaving any empty directories behind and creating any directories necessary.""" full_file2 = os.path.join(basedir, file2) create_dirs(os.path.dirname(full_file2)) os.rename(os.path.join(basedir, file1), full_file2) try: os.removedirs(os.path.join(basedir, os.path.dirname(file1))) except OSError: # file1's parent dir may not be empty after move pass class EditorException(StgException): pass def get_editor(): for editor in [environ_get('GIT_EDITOR'), config.get('stgit.editor'), # legacy config.get('core.editor'), environ_get('VISUAL'), environ_get('EDITOR'), 'vi']: if editor: return editor def call_editor(filename): """Run the editor on the specified filename.""" cmd = '%s %s' % (get_editor(), filename) out.start('Invoking the editor: "%s"' % cmd) err = os.system(cmd) if err: raise EditorException('editor failed, exit code: %d' % err) out.done() def get_hook(repository, hook_name, extra_env={}): hook_path = os.path.join(repository.directory, 'hooks', hook_name) if not (os.path.isfile(hook_path) and os.access(hook_path, os.X_OK)): return None default_iw = repository.default_iw prefix_dir = os.path.relpath(os.getcwd(), default_iw.cwd) if prefix_dir == os.curdir: prefix = '' else: prefix = os.path.join(prefix_dir, '') extra_env = add_dict(extra_env, {'GIT_PREFIX': prefix}) def hook(*parameters): argv = [hook_path] argv.extend(parameters) # On Windows, run the hook using "bash" explicitly if os.name != 'posix': argv.insert(0, 'bash') default_iw.run(argv, extra_env).run() hook.__name__ = str(hook_name) return hook def run_hook_on_string(hook, s, *args): if hook is not None: temp = tempfile.NamedTemporaryFile('w', delete=False) try: try: temp.write(s) finally: temp.close() if sys.version_info[0] >= 3: hook_path = temp.name else: hook_path = temp.name.decode(sys.getfilesystemencoding()) hook(hook_path, *args) output = open(hook_path, 'r') try: s = output.read() finally: output.close() finally: os.unlink(temp.name) return s def edit_string(s, filename, encoding='utf-8'): with open(filename, 'w', encoding=encoding) as f: f.write(s) call_editor(filename) with open(filename, encoding=encoding) as f: s = f.read() os.remove(filename) return s def edit_bytes(s, filename): with open(filename, 'wb') as f: f.write(s) call_editor(filename) with open(filename, 'rb') as f: s = f.read() os.remove(filename) return s def append_comment(s, comment, separator = '---'): return ('%s\n\n%s\nEverything following the line with "%s" will be' ' ignored\n\n%s' % (s, separator, separator, comment)) def strip_comment(s, separator = '---'): try: return s[:s.index('\n%s\n' % separator)] except ValueError: return s def find_patch_name(patchname, unacceptable): """Find a patch name which is acceptable.""" if unacceptable(patchname): suffix = 0 while unacceptable('%s-%d' % (patchname, suffix)): suffix += 1 patchname = '%s-%d' % (patchname, suffix) return patchname def patch_name_from_msg(msg): """Return a string to be used as a patch name. This is generated from the top line of the string passed as argument.""" if not msg: return None name_len = config.getint('stgit.namelength') if not name_len: name_len = 30 subject_line = msg.split('\n', 1)[0].lstrip().lower() words = re.sub(r'[\W]+', ' ', subject_line).split() # use loop to avoid truncating the last name name = words and words[0] or 'unknown' for word in words[1:]: new = name + '-' + word if len(new) > name_len: break name = new return name def make_patch_name(msg, unacceptable, default_name = 'patch'): """Return a patch name generated from the given commit message, guaranteed to make unacceptable(name) be false. If the commit message is empty, base the name on default_name instead.""" patchname = patch_name_from_msg(msg) if not patchname: patchname = default_name return find_patch_name(patchname, unacceptable) def add_sign_line(desc, sign_str, name, email): if not sign_str: return desc sign_str = '%s: %s <%s>' % (sign_str, name, email) if sign_str in desc: return desc desc = desc.rstrip() preamble, lastblank, lastpara = desc.rpartition('\n\n') is_signoff = re.compile(r'[A-Z][a-z]*(-[A-Za-z][a-z]*)*: ').match if not (lastblank and all(is_signoff(l) for l in lastpara.split('\n'))): desc = desc + '\n' return '%s\n%s\n' % (desc, sign_str) def parse_name_email(address): """Return a tuple consisting of the name and email parsed from a standard 'name ' or 'email (name)' string.""" address = re.sub(r'[\\"]', r'\\\g<0>', address) str_list = re.findall(r'^(.*)\s*<(.*)>\s*$', address) if not str_list: str_list = re.findall(r'^(.*)\s*\((.*)\)\s*$', address) if not str_list: return None return (str_list[0][1], str_list[0][0]) return str_list[0] def parse_name_email_date(address): """Return a tuple consisting of the name, email and date parsed from a 'name date' string.""" address = re.sub(r'[\\"]', r'\\\g<0>', address) str_list = re.findall(r'^(.*)\s*<(.*)>\s*(.*)\s*$', address) if not str_list: return None return str_list[0] # Exit codes. STGIT_SUCCESS = 0 # everything's OK STGIT_GENERAL_ERROR = 1 # seems to be non-command-specific error STGIT_COMMAND_ERROR = 2 # seems to be a command that failed STGIT_CONFLICT = 3 # merge conflict, otherwise OK STGIT_BUG_ERROR = 4 # a bug in StGit def add_dict(d1, d2): """Return a new dict with the contents of both d1 and d2. In case of conflicting mappings, d2 takes precedence.""" d = dict(d1) d.update(d2) return d stgit-0.19/stgit/version.py000066400000000000000000000037751337022307200160010ustar00rootroot00000000000000# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import os import re import sys from stgit.run import Run, RunException class VersionUnavailable(Exception): pass def git_describe_version(): root = sys.path[0] try: v = Run( 'git', 'describe', '--tags', '--abbrev=4' ).cwd(root).output_one_line() except RunException as e: raise VersionUnavailable(str(e)) m = re.match(r'^v([0-9].*)', v) if m: v = m.group(1) else: raise VersionUnavailable('bad version: %s' % v) try: dirty = Run( 'git', 'diff-index', '--name-only', 'HEAD' ).cwd(root).raw_output() except RunException as e: raise VersionUnavailable(str(e)) if dirty: v += '-dirty' return v def git_archival_version(): archival_path = os.path.join(sys.path[0], '.git_archival.txt') if not os.path.isfile(archival_path): # The archival file will not be present in sdist archives. raise VersionUnavailable('%s does not exist' % archival_path) tag_re = re.compile(r'(?<=\btag: )([^,]+)\b') with open(archival_path) as f: for line in f: if line.startswith('ref-names:'): for tag in tag_re.findall(line): if tag.startswith('v'): return tag[1:] else: raise VersionUnavailable('no tags found in %s' % archival_path) def get_builtin_version(): try: import stgit.builtin_version except ImportError: raise VersionUnavailable('could not import stgit.builtin_version') else: return stgit.builtin_version.version def get_version(): for v in [get_builtin_version, git_describe_version, git_archival_version]: try: return v() except VersionUnavailable: pass return 'unknown-version' # minimum version requirements git_min_ver = '1.5.2' python_min_ver = '2.6' stgit-0.19/t/000077500000000000000000000000001337022307200130375ustar00rootroot00000000000000stgit-0.19/t/.gitignore000066400000000000000000000000061337022307200150230ustar00rootroot00000000000000trash stgit-0.19/t/Makefile000066400000000000000000000001671337022307200145030ustar00rootroot00000000000000# Run tests # # Copyright (c) 2005 Junio C Hamano # all: $(PYTHON) test.py clean: rm -rf trash* .PHONY: all clean stgit-0.19/t/README000066400000000000000000000153231337022307200137230ustar00rootroot00000000000000Core GIT Tests ============== This directory holds many test scripts for core GIT tools. The first part of this short document describes how to run the tests and read their output. When fixing the tools or adding enhancements, you are strongly encouraged to add tests in this directory to cover what you are trying to fix or enhance. The later part of this short document describes how your test scripts should be organized. The mechanism that powers this testsuite is directly imported from the Core GIT Tests, in directory t/ of the git repository. Files are base on Core GIT version 1.3.0.rc4.g5069. Running Tests ------------- The easiest way to run tests is to say "make -C t". This runs all the tests. *** t0000-basic.sh *** * ok 1: .git/objects should be empty after git init in an empty repo. * ok 2: .git/objects should have 256 subdirectories. * ok 3: git update-index without --add should fail adding. ... * ok 23: no diff after checkout and git update-index --refresh. * passed all 23 test(s) *** t0100-environment-names.sh *** * ok 1: using old names should issue warnings. * ok 2: using old names but having new names should not issue warnings. ... Or you can run each test individually from command line, like this: $ sh ./t3001-ls-files-killed.sh * ok 1: git update-index --add to add various paths. * ok 2: git ls-files -k to show killed files. * ok 3: validate git ls-files -k output. * passed all 3 test(s) You can pass --verbose (or -v), --debug (or -d), and --immediate (or -i) command line argument to the test. --verbose:: This makes the test more verbose. Specifically, the command being run and their output if any are also output. --debug:: This may help the person who is developing a new test. It causes the command defined with test_debug to run. --immediate:: This causes the test to immediately exit upon the first failed test. Naming Tests ------------ The test files are named as: tNNNN-commandname-details.sh where N is a decimal digit. Here is a proposal for numbering, loosely based on the Core GIT numbering conventions. First two digit tells the particular command we are testing: 00 - stgit itself 10 - branch 11 - clone 12 - push Third and fourth digit (optionally) tells the particular switch or group of switches we are testing. If you create files under t/ directory (i.e. here) that is not the top-level test script, never name the file to match the above pattern. The Makefile here considers all such files as the top-level test script and tries to run all of them. A care is especially needed if you are creating a common test library file, similar to test-lib.sh, because such a library file may not be suitable for standalone execution. Writing Tests ------------- The test script is written as a shell script. It should start with the standard "#!/bin/sh" with copyright notices, and an assignment to variable 'test_description', like this: #!/bin/sh # # Copyright (c) 2005 Junio C Hamano # test_description='xxx test (option --frotz) This test registers the following structure in the cache and tries to run git ls-files with option --frotz.' Source 'test-lib.sh' -------------------- After assigning test_description, the test script should source test-lib.sh like this: . ./test-lib.sh This test harness library does the following things: - If the script is invoked with command line argument --help (or -h), it shows the test_description and exits. - Creates an empty test directory with an empty .git/objects database and chdir(2) into it. This directory is 't/trash' if you must know, but I do not think you care. - Defines standard test helper functions for your scripts to use. These functions are designed to make all scripts behave consistently when command line arguments --verbose (or -v), --debug (or -d), and --immediate (or -i) is given. End with test_done ------------------ Your script will be a sequence of tests, using helper functions from the test harness library. At the end of the script, call 'test_done'. Test harness library -------------------- There are a handful helper functions defined in the test harness library for your script to use. - test_expect_success