From: Karl Hasselström Date: Sun, 28 Sep 2008 12:38:22 +0000 (+0200) Subject: Merge branch 'stable' X-Git-Tag: v0.15-rc1~123 X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~mdw/git/stgit/commitdiff_plain/588a7414ee52328525dfcb514e580da877e4ff3c?hp=7cb253c05b509510177a1df4d5813861641968f6 Merge branch 'stable' * stable: Fix typo --- diff --git a/.gitignore b/.gitignore index 91dbad2..e7fffb0 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ patches-* release.sh setup.cfg.rpm snapshot.sh +stgit-completion.bash diff --git a/AUTHORS b/AUTHORS index 098c1d3..6617806 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,2 +1,4 @@ Catalin Marinas - http://www.procode.org/about.html + http://www.procode.org/about.html +Karl Hasselström + http://www.treskal.com/kalle/ diff --git a/Documentation/.gitignore b/Documentation/.gitignore index 6da6dc4..c72f35c 100644 --- a/Documentation/.gitignore +++ b/Documentation/.gitignore @@ -1,5 +1,6 @@ *.html *.pdf -*.7 -*.1 +*.[1-9] +stg-*.txt doc.dep +command-list.txt diff --git a/Documentation/COMMAND-TEMPLATE.txt b/Documentation/COMMAND-TEMPLATE.txt deleted file mode 100644 index 7bc029a..0000000 --- a/Documentation/COMMAND-TEMPLATE.txt +++ /dev/null @@ -1,42 +0,0 @@ -stg-NAME(1) -========== -XXX -v0.12.1, Xxxx 2007 - -NAME ----- -stg-NAME - stgdesc:NAME[] - -SYNOPSIS --------- -[verse] -'stg' NAME [OPTIONS] XXX - -DESCRIPTION ------------ - -XXX - -OPTIONS -------- - -XXX - -FILES ------ - - /XXX - -ENVIRONMENT VARIABLES ---------------------- - - XXX - -GIT CONFIGURATION VARIABLES ---------------------------- - - stgit.XXX - -StGIT ------ -Part of the StGIT suite - see gitlink:stg[1]. diff --git a/Documentation/Makefile b/Documentation/Makefile index 2e5d23c..165e222 100644 --- a/Documentation/Makefile +++ b/Documentation/Makefile @@ -1,7 +1,9 @@ -MAN1_TXT=$(wildcard stg*.txt) -MAN7_TXT= +COMMANDS = $(shell ../stg-build --commands) +COMMANDS_TXT = $(patsubst %,stg-%.txt,$(COMMANDS)) -DOC_HTML=$(patsubst %.txt,%.html,$(MAN1_TXT) $(MAN7_TXT)) +MAN1_TXT= stg.txt $(COMMANDS_TXT) + +DOC_HTML=$(patsubst %.txt,%.html,$(MAN1_TXT)) ARTICLES = # with their own formatting rules. @@ -11,12 +13,11 @@ DOC_HTML += $(patsubst %,%.html,$(ARTICLES) $(SP_ARTICLES)) DOC_PDF += $(patsubst %,%.pdf,$(ARTICLES) $(SP_ARTICLES)) DOC_MAN1=$(patsubst %.txt,%.1,$(MAN1_TXT)) -DOC_MAN7=$(patsubst %.txt,%.7,$(MAN7_TXT)) prefix?=$(HOME) -mandir?=$(prefix)/man +htmldir?=$(prefix)/share/doc/stgit +mandir?=$(prefix)/share/man man1dir=$(mandir)/man1 -man7dir=$(mandir)/man7 # DESTDIR= ASCIIDOC=asciidoc --unsafe @@ -37,16 +38,17 @@ all: html man html: $(DOC_HTML) pdf: $(DOC_PDF) -$(DOC_HTML) $(DOC_MAN1) $(DOC_MAN7): asciidoc.conf +$(DOC_HTML) $(DOC_MAN1): asciidoc.conf -man: man1 man7 +man: man1 man1: $(DOC_MAN1) -man7: $(DOC_MAN7) - install: man - $(INSTALL) -d -m755 $(DESTDIR)$(man1dir) $(DESTDIR)$(man7dir) + $(INSTALL) -d -m755 $(DESTDIR)$(man1dir) $(INSTALL) -m644 $(DOC_MAN1) $(DESTDIR)$(man1dir) - $(INSTALL) -m644 $(DOC_MAN7) $(DESTDIR)$(man7dir) + +install-html: html + $(INSTALL) -d -m755 $(DESTDIR)$(htmldir) + $(INSTALL) -m644 $(DOC_HTML) $(DESTDIR)$(htmldir) # # Determine "include::" file references in asciidoc files. # @@ -58,12 +60,20 @@ doc.dep : $(wildcard *.txt) build-docdep.perl -include doc.dep clean: - rm -f *.xml *.html *.pdf *.1 *.7 doc.dep + rm -f *.xml *.html *.pdf *.1 doc.dep $(COMMANDS_TXT) command-list.txt + +ALL_PY = $(shell find ../stgit -name '*.py') + +$(COMMANDS_TXT): $(ALL_PY) + ../stg-build --asciidoc $(basename $(subst stg-,,$@)) > $@ + +command-list.txt: $(ALL_PY) + ../stg-build --cmd-list > $@ %.html : %.txt $(ASCIIDOC) -b xhtml11 -d manpage -f asciidoc.conf $(ASCIIDOC_EXTRA) $< -%.1 %.7 : %.xml +%.1 : %.xml xmlto -m callouts.xsl man $< %.xml : %.txt diff --git a/Documentation/asciidoc.conf b/Documentation/asciidoc.conf index 3df8814..5f7a7af 100644 --- a/Documentation/asciidoc.conf +++ b/Documentation/asciidoc.conf @@ -1,59 +1,103 @@ -## gitlink: macro -# -# Usage: gitlink:command[manpage-section] -# -# Note, {0} is the manpage section, while {target} is the command. -# -# Show GIT link as: (
); if section is defined, else just show -# the command. - [attributes] -caret=^ +asterisk=* +plus=+ +caret=^ startsb=[ endsb=] tilde=~ ifdef::backend-docbook[] -[gitlink-inlinemacro] -{0%{target}} -{0#} -{0#{target}{0}} -{0#} -endif::backend-docbook[] - -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[] + +## link: macro +# +# Usage: link: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[] +[link-inlinemacro] +{0%{target}} +{0#} +{0#{target}{0}} +{0#} endif::backend-docbook[] ifdef::backend-xhtml11[] -[gitlink-inlinemacro] +[link-inlinemacro] {target}{0?({0})} endif::backend-xhtml11[] -# stglink +## stglink: macro +# +# Usage: stglink:command[] +# +# Show StGit link as: stg-(1) in man pages, stg in +# html. ifdef::backend-docbook[] [stglink-inlinemacro] -stg {target}1 + stg-{target}1 endif::backend-docbook[] ifdef::backend-xhtml11[] [stglink-inlinemacro] -stg {target}(1) +stg {target} endif::backend-xhtml11[] -# stgdesc -[stgdesc-inlinemacro] -{sys:../stg help|grep " {target}" | tr -s ' '| cut -d' ' -f3-} +## stgsublink: macro +# +# Usage: stgsublink:command[] +# +# Show StGit link as: in man pages, stg in +# html. -[stgdesc-blockmacro] -stglink:{target}[]:: - stgdesc:{target}[] +ifdef::backend-docbook[] +[stgsublink-inlinemacro] +{target} +endif::backend-docbook[] + +ifdef::backend-xhtml11[] +[stgsublink-inlinemacro] +{target} +endif::backend-xhtml11[] diff --git a/Documentation/stg-branch.txt b/Documentation/stg-branch.txt deleted file mode 100644 index 25ca951..0000000 --- a/Documentation/stg-branch.txt +++ /dev/null @@ -1,114 +0,0 @@ -stg-branch(1) -============= -Yann Dirson -v0.12.1, April 2007 - -NAME ----- -stg-branch - stgdesc:branch[] - -SYNOPSIS --------- -[verse] -'stg' branch -'stg' branch -'stg' branch --list -'stg' branch --create [] -'stg' branch --clone [] -'stg' branch --rename -'stg' branch --description= [] -'stg' branch --protect [] -'stg' branch --unprotect [] -'stg' branch --delete [--force] - -DESCRIPTION ------------ - -Assorted operations on branches. - -no command, no argument:: - Display the name of the current branch. - -no command, one argument:: - Switch to the named . - -'stg' branch [-l | --list]:: - Display the list of branches in the current repository, - suffixed by the branch description if any, and optionally - prefixed by the letter flags 's' if the branch is an StGIT - stack, and 'p' if the StGIT stack is protected. The current - branch is shown with a leading ">" character. - -'stg' branch [-c | --create]:: - Create a new StGIT stack based at the specified commit, or at - the current HEAD if not specified. The repository HEAD is - switched to the new stack. -+ -StGIT will try to detect the branch off which the new stack is forked, -as well as the remote repository from which that parent branch is -taken (if any), so running stglink:pull[] will effectively pull new -commits from the correct branch. It will warn if it cannot guess the -parent branch (eg. if you do not specify a branch name as -). - -'stg' branch --clone:: - Clone the current stack, under the name if - specified, or using the current stack's name suffixed by a - timestamp. -+ -The description of the new stack is set to tell it is a clone of the -current stack. The parent information of the new stack is copied from -the current stack. -+ -Cloning a GIT branch that is not an StGIT stack is similar to creating -a new stack off the current branch. - -'stg' branch [-r | --rename]:: - Rename the stack named to . - -'stg' branch [-d | --description=]:: - Set the branch description. - -'stg' branch [-p | --protect]:: - Protect the named stack or the current one, preventing - further StGIT operations from modifying this stack. - -'stg' branch [-u | --unprotect]:: - Remove a "protected" flag previously set with '--protect'. - -'stg' branch --delete:: - Delete the named . If there are any patches left in - the series, StGIT will refuse to delete it, unless '--force' - is specified. -+ -A protected branch cannot be deleted, it must be unprotected first -(see above). -+ -When the current branch is deleted, the repository HEAD is switched to -the "master" branch if it exists. -+ -Branch "master" is treated specially (see bug #8732), in that only the -StGIT metadata are removed, the GIT branch itself is not destroyed. - -OPTIONS -------- - ---force:: - Force a delete when the series is not empty. - -FILES ------ - - $GIT_DIR/patches//description - $GIT_DIR/patches//protected - -GIT CONFIGURATION VARIABLES ---------------------------- - - branch..remote - branch..merge - branch..stgit.parentbranch - -StGIT ------ -Part of the StGIT suite - see gitlink:stg[1]. diff --git a/Documentation/stg-clone.txt b/Documentation/stg-clone.txt deleted file mode 100644 index 19a8b79..0000000 --- a/Documentation/stg-clone.txt +++ /dev/null @@ -1,32 +0,0 @@ -stg-clone(1) -========== -Yann Dirson -v0.12.1, April 2007 - -NAME ----- -stg-clone - stgdesc:clone[] - -SYNOPSIS --------- -[verse] -'stg' clone - -DESCRIPTION ------------ - -Clone a GIT into the local (using -gitlink:git-clone[1]) and initialise the resulting "master" branch as -a patch stack. - -This operation is for example suitable to start working using the -"tracking branch" workflow (see gitlink:stg[1]). Other means to setup -an StGIT stack are stglink:init[] and the '--create' and '--clone' -commands of stglink:branch[]. - -The target directory named by will be created by this command, -and must not exist beforehand. - -StGIT ------ -Part of the StGIT suite - see gitlink:stg[1]. diff --git a/Documentation/stg-cp.txt b/Documentation/stg-cp.txt deleted file mode 100644 index 2314925..0000000 --- a/Documentation/stg-cp.txt +++ /dev/null @@ -1,63 +0,0 @@ -stg-cp(1) -========= -Yann Dirson -v0.13, March 2007 - -NAME ----- -stg-cp - stgdesc:cp[] - -SYNOPSIS --------- -[verse] -'stg' cp [OPTIONS] -'stg' cp [OPTIONS] - -DESCRIPTION ------------ - -Make git-controlled copies of git-controlled files. The copies are -added to the Git index, so you can add them to a patch with -stglink:refresh[]. - -In the first form, copy a single file or a single directory, with a -new name. The parent directory of must already exist; - itself must not already exist, or the command will be -interpreted as one of the second form. - -In the second form, copy one or several files and/or directories, into -an existing directory. - -Directories are copied recursively. Only the git-controlled files -under the named directories are copied and added to the index. Any -file not known to Git will not be copied. - -CAVEATS -------- - -This command does not allow yet to overwrite an existing file (whether -it could be recovered from Git or not). Further more, when copying a -directory, the second form does not allow to proceed if a directory by -that name already exists inside the target, even when no file inside -that directory would be overwritten. - -FUTURE OPTIONS --------------- - -No options are supported yet. The following options may be -implemented in the future. - ---all:: - Also copy files not known to Git when copying a directory. - ---force:: - Force overwriting of target files, even if overwritten files - have non-committed changes or are not known to Git. - ---dry-run:: - Show which files would be added, and which would be modified - if --force would be added. - -StGIT ------ -Part of the StGIT suite - see gitlink:stg[1]. diff --git a/Documentation/stg-init.txt b/Documentation/stg-init.txt deleted file mode 100644 index 03877e0..0000000 --- a/Documentation/stg-init.txt +++ /dev/null @@ -1,29 +0,0 @@ -stg-init(1) -========== -Yann Dirson -v0.12.1, April 2007 - -NAME ----- -stg-init - stgdesc:init[] - -SYNOPSIS --------- -[verse] -'stg' init - -DESCRIPTION ------------ - -Initialise the current GIT branch to be used as an StGIT stack. You -must already be in a GIT repository and .git/HEAD must point to a -valid file in refs/heads/. - -This operation is for example suitable to start working using the -"development branch" workflow (see gitlink:stg[1]). Other means to setup -an StGIT stack are stglink:clone[] and the '--create' and '--clone' -commands of stglink:branch[]. - -StGIT ------ -Part of the StGIT suite - see gitlink:stg[1]. diff --git a/Documentation/stg-new.txt b/Documentation/stg-new.txt deleted file mode 100644 index fbf2f67..0000000 --- a/Documentation/stg-new.txt +++ /dev/null @@ -1,115 +0,0 @@ -stg-new(1) -========== -Yann Dirson -v0.12.1, February 2007 - -NAME ----- -stg-new - stgdesc:new[] - -SYNOPSIS --------- -[verse] -'stg' new [OPTIONS] [name] - -DESCRIPTION ------------ - -Create a new, empty patch with the given 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. The local changes in the working -tree are not included in the patch. A stglink:refresh[] command is -needed for this. - -The given 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 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 is used if available to pre-fill the -editor. The editor to use is taken from the first of the following -sources of information, and defaults to 'vi': - -. the 'stgit.editor' GIT configuration variable -. the 'EDITOR' environment variable - -The message and other GIT commit attributes can be modified later -using stglink:refresh[]. - -AUTHOR AND COMMITTER INFORMATION --------------------------------- - -The author name (resp. email) to record in the StGIT patch is taken -from the first of the following sources for the information: - -. the '--authname' (resp. '--authemail') or '--author' flag on command-line -. the 'GIT_AUTHOR_NAME' (resp. 'GIT_AUTHOR_EMAIL') environment variable -. the 'user.name' (resp. 'user.email') GIT configuration variable - -Similarly, the committer name (resp. email) is taken from the first of -the following sources: - -. the '--commname' (resp. '--commemail') flag on command-line -. the 'GIT_COMMITTER_NAME' (resp. 'GIT_COMMITTER_EMAIL') environment variable -. the 'user.name' (resp. 'user.email') GIT configuration variable - -The GIT commit generated by stglink:refresh[] will use these -informations when available. If one of them is not available, GIT -will pick the value from your machine's configuration at that time, as -described in gitlink:git-commit-tree[1]. - -OPTIONS -------- - ---message=:: --m :: - Use as the patch description. - ---showpatch:: --s:: - Show the patch content in the editor buffer. This flag does - nothing if '-m' is also specified. - ---author="Name ":: --a "Name ":: - Use "Name " as the author details. This form - sets both 'authname' and 'authemail'. - ---authname=:: - Use as the author name ---authemail=:: - Use as the author e-mail ---authdate=:: - Use as the author date - ---commname=:: - Use as the committer name ---commemail=:: - Use as the committer e-mail - -FILES ------ - - /patchdescr.tmpl - -ENVIRONMENT VARIABLES ---------------------- - - GIT_AUTHOR_NAME - GIT_AUTHOR_EMAIL - GIT_AUTHOR_DATE - GIT_COMMITTER_NAME - GIT_COMMITTER_EMAIL - EDITOR - -GIT CONFIGURATION VARIABLES ---------------------------- - - user.name - user.email - stgit.editor - -StGIT ------ -Part of the StGIT suite - see gitlink:stg[1]. diff --git a/Documentation/stg-sink.txt b/Documentation/stg-sink.txt deleted file mode 100644 index 0f569be..0000000 --- a/Documentation/stg-sink.txt +++ /dev/null @@ -1,49 +0,0 @@ -stg-sink(1) -=========== -Yann Dirson -v0.13, April 2007 - -NAME ----- -stg-sink - stgdesc:sink[] - -SYNOPSIS --------- -[verse] -'stg' sink [--to=] [--nopush] [] - -DESCRIPTION ------------ - -This is the opposite operation of stglink: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 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. - - -OPTIONS -------- - ---to=:: --t :: - Specify a target patch to place the patches below, instead of - sinking them to the bottom of the stack. - ---nopush:: --n:: - Do not push back on the stack the formerly-applied patches. - Only the patches to sink are pushed. - -StGIT ------ -Part of the StGIT suite - see gitlink:stg[1]. diff --git a/Documentation/stg.txt b/Documentation/stg.txt index f6cd815..d8f7d01 100644 --- a/Documentation/stg.txt +++ b/Documentation/stg.txt @@ -105,147 +105,13 @@ description is available in individual command manpages. Those manpages are named 'stg-(1)'. endif::backend-docbook[] -Generic commands -~~~~~~~~~~~~~~~~ - -User-support commands not touching the repository. - -stg help:: - stgdesc:help[] -stg version:: - stgdesc:version[] -stg copyright:: - stgdesc:copyright[] - -Repository commands -~~~~~~~~~~~~~~~~~~~ - -stglink:clone[]:: - stgdesc:clone[] -stglink:id[]:: - stgdesc:id[] - -Stack commands -~~~~~~~~~~~~~~ - -Stack management -^^^^^^^^^^^^^^^^ - -stglink:branch[]:: - stgdesc:branch[] -stglink:init[]:: - stgdesc:init[] -stglink:clean[]:: - stgdesc:clean[] -stglink:pull[]:: - stgdesc:pull[] -stglink:rebase[]:: - stgdesc:rebase[] - -stglink:commit[]:: - stgdesc:commit[] -stglink:uncommit[]:: - stgdesc:uncommit[] -stglink:repair[]:: - stgdesc:repair[] - -Controlling what patches are applied -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -stglink:series[]:: - stgdesc:series[] -stglink:push[]:: - stgdesc:push[] -stglink:pop[]:: - stgdesc:pop[] -stglink:goto[]:: - stgdesc:goto[] -stglink:float[]:: - stgdesc:float[] -stglink:sink[]:: - stgdesc:sink[] -stglink:applied[]:: - stgdesc:applied[] -stglink:unapplied[]:: - stgdesc:unapplied[] -stglink:top[]:: - stgdesc:top[] - -stglink:hide[]:: - stgdesc:hide[] -stglink:unhide[]:: - stgdesc:unhide[] - -Miscellaneous stack commands -^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -stglink:patches[]:: - stgdesc:patches[] - - -Patch commands -~~~~~~~~~~~~~~ - -Patch management -^^^^^^^^^^^^^^^^ - -stglink:new[]:: - stgdesc:new[] -stglink:delete[]:: - stgdesc:delete[] -stglink:rename[]:: - stgdesc:rename[] -stglink:log[]:: - stgdesc:log[] - -Controlling patch contents -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -stglink:files[]:: - stgdesc:files[] -stglink:show[]:: - stgdesc:show[] -stglink:refresh[]:: - stgdesc:refresh[] -stglink:fold[]:: - stgdesc:fold[] -stglink:pick[]:: - stgdesc:pick[] -stglink:sync[]:: - stgdesc:sync[] - -Interaction with the rest of the world -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -stglink:export[]:: - stgdesc:export[] -stglink:import[]:: - stgdesc:import[] -stglink:mail[]:: - stgdesc:mail[] - - -Working-copy commands -~~~~~~~~~~~~~~~~~~~~~ - -stglink:add[]:: - stgdesc:add[] -stglink:rm[]:: - stgdesc:rm[] -stglink:cp[]:: - stgdesc:cp[] -stglink:status[]:: - stgdesc:status[] -stglink:diff[]:: - stgdesc:diff[] -stglink:resolved[]:: - stgdesc:resolved[] +include::command-list.txt[] CONFIGURATION MECHANISM ----------------------- Starting with 0.12, StGIT uses the same configuration mechanism as -GIT. See gitlink:git[7] for more details. +GIT. See link:git[7] for more details. TEMPLATES --------- diff --git a/Documentation/tutorial.txt b/Documentation/tutorial.txt index b040d29..472a5c3 100644 --- a/Documentation/tutorial.txt +++ b/Documentation/tutorial.txt @@ -123,18 +123,22 @@ You can view modified files that have already been saved into a patch: stg files The 'stg refresh' command automatically notes changes to files that -already exist in the working directory, but you have to tell StGIT -explicitly if you add, remove, or rename files. -To record the addition or deletion of files in your new patch: +already exist in the working directory (it also notices if you remove +them), but you have to tell StGIT explicitly if you add or rename a +file: - stg add [*] - stg rm [*] + git add new-file -To record the renaming of a file in your new patch, issue both of these -commands: +to add a file, and + + mv old-file new-file + git add new-file + +or simply + + git mv old-file new-file - stg rm - stg add +to move a file. Stack manipulation: managing multiple patches @@ -174,7 +178,9 @@ patches in a stack. During a push operation, merge conflicts can occur (especially if you are changing the order of the patches in your stack). If the push causes merge conflicts, they need to be fixed and 'stg resolved' run (see -below). A 'push' operation can also be reverted with 'stg push --undo'. +below). A 'push' operation can also be reverted with 'stg undo' (you +will need to give it the --hard flag, since the conflicting push will +have left your work tree dirty). A few more stack basics; to rename a patch: stg rename diff --git a/INSTALL b/INSTALL index 8d2bebd..3da4efd 100644 --- a/INSTALL +++ b/INSTALL @@ -1,13 +1,18 @@ For basic installation: - python setup.py install + $ 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. +prefix option. - python setup.py install --prefix=/usr + $ make prefix=/usr all doc #; as yourself + # make prefix=/usr install install-doc #; as root -For more information: +Issues of note: + +- To build and install the documentation, you need to have the + asciidoc/xmlto toolchain. The default build target ("make all") + does _not_ build them. - http://docs.python.org/inst/inst.html diff --git a/Makefile b/Makefile index c890b8e..7183670 100644 --- a/Makefile +++ b/Makefile @@ -1,19 +1,42 @@ -PREFIX ?= $(HOME) +prefix ?= $(HOME) DESTDIR ?= / PYTHON ?= python -all: +TEST_PATCHES ?= .. + +all: build $(PYTHON) setup.py build -install: - $(PYTHON) setup.py install --prefix=$(PREFIX) --root=$(DESTDIR) --force +build: stgit/commands/cmdlist.py stgit-completion.bash + +ALL_PY = $(shell find stgit -name '*.py') + +stgit/commands/cmdlist.py: $(ALL_PY) + $(PYTHON) stg-build --py-cmd-list > $@ + +stgit-completion.bash: $(ALL_PY) + $(PYTHON) stg-build --bash-completion > $@ + +install: build + $(PYTHON) setup.py install --prefix=$(prefix) --root=$(DESTDIR) --force doc: cd Documentation && $(MAKE) all -test: +install-doc: + $(MAKE) -C Documentation install + +install-html: + $(MAKE) -C Documentation install-html + +test: build cd t && $(MAKE) all +test_patches: build + for patch in $$(stg series --noprefix $(TEST_PATCHES)); do \ + stg goto $$patch && $(MAKE) test || break; \ + done + clean: for dir in Documentation t; do \ (cd $$dir && $(MAKE) clean); \ @@ -22,8 +45,9 @@ clean: rm -f stgit/*.pyc rm -f stgit/commands/*.pyc rm -f TAGS + rm -f stgit/commands/cmdlist.py tags: ctags -e -R stgit/* -.PHONY: all install doc test clean +.PHONY: all build install doc install-doc install-html test test_patches clean diff --git a/TODO b/TODO index 884b831..ff52a95 100644 --- a/TODO +++ b/TODO @@ -8,8 +8,6 @@ The TODO list before 1.0: - debian package support - man page - document the workflow on the StGIT wiki -- maybe a separate undo command rather than passing a --undo option to - push and refresh - use same configuration file as GIT - release 1.0 diff --git a/contrib/Makefile b/contrib/Makefile new file mode 100644 index 0000000..8556910 --- /dev/null +++ b/contrib/Makefile @@ -0,0 +1,19 @@ +EMACS = 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) diff --git a/contrib/diffcol.sh b/contrib/diffcol.sh index ea9109d..eecc87a 100755 --- a/contrib/diffcol.sh +++ b/contrib/diffcol.sh @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/bash # Code copied from Quilt (http://savannah.nongnu.org/projects/quilt) # diff --git a/contrib/stgit-completion.bash b/contrib/stgit-completion.bash deleted file mode 100644 index 8d49e21..0000000 --- a/contrib/stgit-completion.bash +++ /dev/null @@ -1,275 +0,0 @@ -# bash completion support for StGIT -*- shell-script -*- -# -# Copyright (C) 2006, Karl Hasselström -# Based on git-completion.sh -# -# 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 - -_stg_commands=" - add - applied - branch - delete - diff - clean - clone - commit - cp - edit - export - files - float - fold - goto - hide - id - import - init - log - mail - new - patches - pick - pop - pull - push - rebase - refresh - rename - repair - resolved - rm - series - show - sink - status - sync - top - unapplied - uncommit - unhide -" - -# The path to .git, or empty if we're not in a repository. -_gitdir () -{ - echo "$(git rev-parse --git-dir 2>/dev/null)" -} - -# Name of the current branch, or empty if there isn't one. -_current_branch () -{ - local b=$(git symbolic-ref HEAD 2>/dev/null) - echo ${b#refs/heads/} -} - -# List of all applied patches. -_applied_patches () -{ - local g=$(_gitdir) - [ "$g" ] && cat "$g/patches/$(_current_branch)/applied" -} - -# List of all unapplied patches. -_unapplied_patches () -{ - local g=$(_gitdir) - [ "$g" ] && cat "$g/patches/$(_current_branch)/unapplied" -} - -# List of all applied patches. -_hidden_patches () -{ - local g=$(_gitdir) - [ "$g" ] && cat "$g/patches/$(_current_branch)/hidden" -} - -# List of all patches. -_all_patches () -{ - local b=$(_current_branch) - local g=$(_gitdir) - [ "$g" ] && cat "$g/patches/$b/applied" "$g/patches/$b/unapplied" -} - -# List of all patches except the current patch. -_all_other_patches () -{ - local b=$(_current_branch) - local g=$(_gitdir) - [ "$g" ] && cat "$g/patches/$b/applied" "$g/patches/$b/unapplied" \ - | grep -v "^$(cat $g/patches/$b/current 2> /dev/null)$" -} - -_all_branches () -{ - local g=$(_gitdir) - [ "$g" ] && (cd $g/patches/ && echo *) -} - -_conflicting_files () -{ - local g=$(_gitdir) - [ "$g" ] && stg status --conflict -} - -_dirty_files () -{ - local g=$(_gitdir) - [ "$g" ] && stg status --modified --new --deleted -} - -_unknown_files () -{ - local g=$(_gitdir) - [ "$g" ] && stg status --unknown -} - -_known_files () -{ - local g=$(_gitdir) - [ "$g" ] && git ls-files -} - -# List the command options -_cmd_options () -{ - stg $1 --help 2>/dev/null | grep -e " --[A-Za-z]" | sed -e "s/.*\(--[^ =]\+\).*/\1/" -} - -# Generate completions for patches and patch ranges from the given -# patch list function, and options from the given list. -_complete_patch_range () -{ - local patchlist="$1" options="$2" - local pfx cur="${COMP_WORDS[COMP_CWORD]}" - case "$cur" in - *..*) - pfx="${cur%..*}.." - cur="${cur#*..}" - COMPREPLY=($(compgen -P "$pfx" -W "$($patchlist)" -- "$cur")) - ;; - *) - COMPREPLY=($(compgen -W "$options $($patchlist)" -- "$cur")) - ;; - esac -} - -_complete_patch_range_options () -{ - local patchlist="$1" options="$2" patch_options="$3" - local prev="${COMP_WORDS[COMP_CWORD-1]}" - local cur="${COMP_WORDS[COMP_CWORD]}" - local popt - for popt in $patch_options; do - if [ $prev == $popt ]; then - _complete_patch_range $patchlist - return - fi - done - COMPREPLY=($(compgen -W "$options" -- "$cur")) -} - -_complete_branch () -{ - COMPREPLY=($(compgen -W "$(_cmd_options $1) $($2)" -- "${COMP_WORDS[COMP_CWORD]}")) -} - -# Generate completions for options from the given list. -_complete_options () -{ - local options="$1" - COMPREPLY=($(compgen -W "$options" -- "${COMP_WORDS[COMP_CWORD]}")) -} - -_complete_files () -{ - COMPREPLY=($(compgen -W "$(_cmd_options $1) $2" -- "${COMP_WORDS[COMP_CWORD]}")) -} - -_stg_common () -{ - _complete_options "$(_cmd_options $1)" -} - -_stg_patches () -{ - _complete_patch_range "$2" "$(_cmd_options $1)" -} - -_stg_patches_options () -{ - _complete_patch_range_options "$2" "$(_cmd_options $1)" "$3" -} - -_stg_help () -{ - _complete_options "$_stg_commands" -} - -_stg () -{ - local i c=1 command - - while [ $c -lt $COMP_CWORD ]; do - if [ $c == 1 ]; then - command="${COMP_WORDS[c]}" - fi - c=$((++c)) - done - - # Complete name of subcommand. - if [ $c -eq $COMP_CWORD -a -z "$command" ]; then - COMPREPLY=($(compgen \ - -W "--help --version copyright help $_stg_commands" \ - -- "${COMP_WORDS[COMP_CWORD]}")) - return; - fi - - # Complete arguments to subcommands. - case "$command" in - # generic commands - help) _stg_help ;; - # repository commands - id) _stg_patches $command _all_patches ;; - # stack commands - float) _stg_patches $command _all_patches ;; - goto) _stg_patches $command _all_other_patches ;; - hide) _stg_patches $command _unapplied_patches ;; - pop) _stg_patches $command _applied_patches ;; - push) _stg_patches $command _unapplied_patches ;; - series) _stg_patches $command _all_patches ;; - sink) _stg_patches $command _all_patches ;; - unhide) _stg_patches $command _hidden_patches ;; - # patch commands - delete) _stg_patches $command _all_patches ;; - edit) _stg_patches $command _applied_patches ;; - export) _stg_patches $command _all_patches ;; - files) _stg_patches $command _all_patches ;; - log) _stg_patches $command _all_patches ;; - mail) _stg_patches $command _all_patches ;; - pick) _stg_patches $command _unapplied_patches ;; -# refresh)_stg_patches_options $command _applied_patches "-p --patch" ;; - refresh) _complete_files $command "$(_dirty_files)" ;; - rename) _stg_patches $command _all_patches ;; - show) _stg_patches $command _all_patches ;; - sync) _stg_patches $command _applied_patches ;; - # working-copy commands - diff) _stg_patches_options $command _applied_patches "-r --range" ;; - resolved) _complete_files $command "$(_conflicting_files)" ;; - add) _complete_files $command "$(_unknown_files)" ;; -# rm) _complete_files $command "$(_known_files)" ;; - # commands that usually raher accept branches - branch) _complete_branch $command _all_branches ;; - rebase) _complete_branch $command _all_branches ;; - # all the other commands - *) _stg_common $command ;; - esac -} - -complete -o default -F _stg stg diff --git a/contrib/stgit.el b/contrib/stgit.el new file mode 100644 index 0000000..aafefaf --- /dev/null +++ b/contrib/stgit.el @@ -0,0 +1,411 @@ +;; stgit.el: An emacs mode for StGit +;; +;; Copyright (C) 2007 David Kågedal +;; +;; To install: put this file on the load-path and place the following +;; in your .emacs file: +;; +;; (require 'stgit) +;; +;; To start: `M-x stgit' + +(defun stgit (dir) + "Manage stgit patches" + (interactive "DDirectory: \n") + (switch-to-stgit-buffer (git-get-top-dir dir)) + (stgit-refresh)) + +(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 "git" 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 switch-to-stgit-buffer (dir) + "Switch to a (possibly new) buffer displaying StGit patches for DIR" + (setq dir (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= default-directory dir))))) + (setq buffers (cdr buffers))) + (switch-to-buffer (if buffers + (car buffers) + (create-stgit-buffer dir))))) + +(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) + (setq buffer-read-only t)) + buf)) + +(defmacro stgit-capture-output (name &rest body) + "Capture StGit output and show it in a window at the end" + `(let ((output-buf (get-buffer-create ,(or name "*StGit output*"))) + (stgit-dir default-directory) + (inhibit-read-only t)) + (with-current-buffer output-buf + (erase-buffer) + (setq default-directory stgit-dir) + (setq buffer-read-only t)) + (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))))) +(put 'stgit-capture-output 'lisp-indent-function 1) + +(defun stgit-run (&rest args) + (apply 'call-process "stg" nil standard-output nil args)) + +(defun stgit-refresh () + "Update the contents of the stgit buffer" + (interactive) + (let ((inhibit-read-only t) + (curline (line-number-at-pos)) + (curpatch (stgit-patch-at-point))) + (erase-buffer) + (insert "Branch: ") + (stgit-run "branch") + (stgit-run "series" "--description") + (stgit-rescan) + (if curpatch + (stgit-goto-patch curpatch) + (goto-line curline)))) + +(defface stgit-description-face + '((((background dark)) (:foreground "tan")) + (((background light)) (:foreground "dark red"))) + "The face used for StGit desriptions") + +(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") + +(defface stgit-applied-patch-face + '((((background dark)) (:foreground "light yellow")) + (((background light)) (:foreground "purple")) + (t ())) + "The face used for applied patch names") + +(defface stgit-unapplied-patch-face + '((((background dark)) (:foreground "gray80")) + (((background light)) (:foreground "orchid")) + (t ())) + "The face used for unapplied patch names") + +(defun stgit-rescan () + "Rescan the status buffer." + (save-excursion + (let ((marked ())) + (goto-char (point-min)) + (while (not (eobp)) + (cond ((looking-at "Branch: \\(.*\\)") + (put-text-property (match-beginning 1) (match-end 1) + 'face 'bold)) + ((looking-at "\\([>+-]\\)\\( \\)\\([^ ]+\\) *[|#] \\(.*\\)") + (let ((state (match-string 1)) + (patchsym (intern (match-string 3)))) + (put-text-property + (match-beginning 3) (match-end 3) 'face + (cond ((string= state ">") 'stgit-top-patch-face) + ((string= state "+") 'stgit-applied-patch-face) + ((string= state "-") 'stgit-unapplied-patch-face))) + (put-text-property (match-beginning 4) (match-end 4) + 'face 'stgit-description-face) + (when (memq patchsym stgit-marked-patches) + (replace-match "*" nil nil nil 2) + (setq marked (cons patchsym marked))))) + ((looking-at "stg series: Branch \".*\" not initialised") + (forward-line 1) + (insert "Run M-x stgit-init to initialise"))) + (forward-line 1)) + (setq stgit-marked-patches (nreverse marked))))) + +(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 + (setq stgit-mode-map (make-keymap)) + (suppress-keymap stgit-mode-map) + (define-key stgit-mode-map " " 'stgit-mark) + (define-key stgit-mode-map "\d" 'stgit-unmark) + (define-key stgit-mode-map "?" 'stgit-help) + (define-key stgit-mode-map "h" 'stgit-help) + (define-key stgit-mode-map "p" 'previous-line) + (define-key stgit-mode-map "n" 'next-line) + (define-key stgit-mode-map "g" 'stgit-refresh) + (define-key stgit-mode-map "r" 'stgit-rename) + (define-key stgit-mode-map "e" 'stgit-edit) + (define-key stgit-mode-map "c" 'stgit-coalesce) + (define-key stgit-mode-map "N" 'stgit-new) + (define-key stgit-mode-map "R" 'stgit-repair) + (define-key stgit-mode-map "C" 'stgit-commit) + (define-key stgit-mode-map "U" 'stgit-uncommit) + (define-key stgit-mode-map ">" 'stgit-push-next) + (define-key stgit-mode-map "<" 'stgit-pop-next) + (define-key stgit-mode-map "P" 'stgit-push-or-pop) + (define-key stgit-mode-map "G" 'stgit-goto) + (define-key stgit-mode-map "=" 'stgit-show) + (define-key stgit-mode-map "D" 'stgit-delete)) + +(defun stgit-mode () + "Major mode for interacting with StGit. +Commands: +\\{stgit-mode-map}" + (kill-all-local-variables) + (buffer-disable-undo) + (setq mode-name "StGit" + major-mode 'stgit-mode + goal-column 2) + (use-local-map stgit-mode-map) + (set (make-local-variable 'list-buffers-directory) default-directory) + (set (make-local-variable 'stgit-marked-patches) nil) + (set-variable 'truncate-lines 't) + (run-hooks 'stgit-mode-hook)) + +(defun stgit-add-mark (patch) + (let ((patchsym (intern patch))) + (setq stgit-marked-patches (cons patchsym stgit-marked-patches)))) + +(defun stgit-remove-mark (patch) + (let ((patchsym (intern patch))) + (setq stgit-marked-patches (delq patchsym stgit-marked-patches)))) + +(defun stgit-marked-patches () + "Return the names of the marked patches." + (mapcar 'symbol-name stgit-marked-patches)) + +(defun stgit-patch-at-point () + "Return the patch name on the current line" + (save-excursion + (beginning-of-line) + (if (looking-at "[>+-][ *]\\([^ ]*\\)") + (match-string-no-properties 1) + nil))) + +(defun stgit-patches-marked-or-at-point () + "Return the names of the marked patches, or the patch on the current line." + (if stgit-marked-patches + (stgit-marked-patches) + (let ((patch (stgit-patch-at-point))) + (if patch + (list patch) + '())))) + +(defun stgit-goto-patch (patch) + "Move point to the line containing PATCH" + (let ((p (point))) + (goto-char (point-min)) + (if (re-search-forward (concat "^[>+-][ *]" (regexp-quote patch) " ") nil t) + (progn (move-to-column goal-column) + t) + (goto-char p) + nil))) + +(defun stgit-init () + "Run stg init" + (interactive) + (stgit-capture-output nil + (stgit-run "init")) + (stgit-refresh)) + +(defun stgit-mark () + "Mark the patch under point" + (interactive) + (let ((patch (stgit-patch-at-point))) + (stgit-add-mark patch) + (stgit-refresh)) + (next-line)) + +(defun stgit-unmark () + "Mark the patch on the previous line" + (interactive) + (forward-line -1) + (let ((patch (stgit-patch-at-point))) + (stgit-remove-mark patch) + (stgit-refresh))) + +(defun stgit-rename (name) + "Rename the patch under point" + (interactive (list (read-string "Patch name: " (stgit-patch-at-point)))) + (let ((old-name (stgit-patch-at-point))) + (unless old-name + (error "No patch on this line")) + (stgit-capture-output nil + (stgit-run "rename" old-name name)) + (stgit-refresh) + (stgit-goto-patch name))) + +(defun stgit-repair () + "Run stg repair" + (interactive) + (stgit-capture-output nil + (stgit-run "repair")) + (stgit-refresh)) + +(defun stgit-commit () + "Run stg commit." + (interactive) + (stgit-capture-output nil (stgit-run "commit")) + (stgit-refresh)) + +(defun stgit-uncommit (arg) + "Run stg uncommit. Numeric arg determines number of patches to uncommit." + (interactive "p") + (stgit-capture-output nil (stgit-run "uncommit" "-n" (number-to-string arg))) + (stgit-refresh)) + +(defun stgit-push-next () + "Push the first unapplied patch" + (interactive) + (stgit-capture-output nil (stgit-run "push")) + (stgit-refresh)) + +(defun stgit-pop-next () + "Pop the topmost applied patch" + (interactive) + (stgit-capture-output nil (stgit-run "pop")) + (stgit-refresh)) + +(defun stgit-applied-at-point () + "Is the patch on the current line applied?" + (save-excursion + (beginning-of-line) + (looking-at "[>+]"))) + +(defun stgit-push-or-pop () + "Push or pop the patch on the current line" + (interactive) + (let ((patch (stgit-patch-at-point)) + (applied (stgit-applied-at-point))) + (stgit-capture-output nil + (stgit-run (if applied "pop" "push") patch)) + (stgit-refresh))) + +(defun stgit-goto () + "Go to the patch on the current line" + (interactive) + (let ((patch (stgit-patch-at-point))) + (stgit-capture-output nil + (stgit-run "goto" patch)) + (stgit-refresh))) + +(defun stgit-show () + "Show the patch on the current line" + (interactive) + (stgit-capture-output "*StGit patch*" + (stgit-run "show" (stgit-patch-at-point)) + (with-current-buffer standard-output + (goto-char (point-min)) + (diff-mode)))) + +(defun stgit-edit () + "Edit the patch on the current line" + (interactive) + (let ((patch (stgit-patch-at-point)) + (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-patch) patch) + (setq default-directory dir) + (let ((standard-output edit-buf)) + (stgit-run "edit" "--save-template=-" patch)))) + +(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-patch)) + (with-current-buffer log-edit-parent-buffer + (stgit-refresh)))) + +(defun stgit-new () + "Create a new patch" + (interactive) + (let ((edit-buf (get-buffer-create "*StGit edit*"))) + (log-edit 'stgit-confirm-new t nil edit-buf))) + +(defun stgit-confirm-new () + (interactive) + (let ((file (make-temp-file "stgit-edit-"))) + (write-region (point-min) (point-max) file) + (stgit-capture-output nil + (stgit-run "new" "-f" file)) + (with-current-buffer log-edit-parent-buffer + (stgit-refresh)))) + +(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 (patch-names) + "Delete the named patches" + (interactive (list (stgit-patches-marked-or-at-point))) + (if (zerop (length patch-names)) + (error "No patches to delete") + (when (yes-or-no-p (format "Really delete %d patches? " + (length patch-names))) + (stgit-capture-output nil + (apply 'stgit-run "delete" patch-names)) + (stgit-refresh)))) + +(defun stgit-coalesce (patch-names) + "Run stg coalesce on the named patches" + (interactive (list (stgit-marked-patches))) + (let ((edit-buf (get-buffer-create "*StGit edit*")) + (dir default-directory)) + (log-edit 'stgit-confirm-coalesce t nil edit-buf) + (set (make-local-variable 'stgit-patches) patch-names) + (setq default-directory dir) + (let ((standard-output edit-buf)) + (apply 'stgit-run "coalesce" "--save-template=-" patch-names)))) + +(defun stgit-confirm-coalesce () + (interactive) + (let ((file (make-temp-file "stgit-edit-"))) + (write-region (point-min) (point-max) file) + (stgit-capture-output nil + (apply 'stgit-run "coalesce" "-f" file stgit-patches)) + (with-current-buffer log-edit-parent-buffer + (stgit-refresh)))) + +(defun stgit-help () + "Display help for the StGit mode." + (interactive) + (describe-function 'stgit-mode)) + +(provide 'stgit) diff --git a/debian/rules b/debian/rules index 5688680..795c77b 100755 --- a/debian/rules +++ b/debian/rules @@ -33,9 +33,7 @@ build: build-stamp build-stamp: configure-stamp dh_testdir - # Add here commands to compile the package. - $(MAKE) - #docbook-to-man debian/stgit.sgml > stgit.1 + $(MAKE) all doc touch build-stamp @@ -56,7 +54,7 @@ install: build dh_installdirs # Add here commands to install the package into debian/stgit. - $(MAKE) DESTDIR=$(CURDIR)/debian/stgit PREFIX=/usr install + $(MAKE) DESTDIR=$(CURDIR)/debian/stgit prefix=/usr install install-doc install-html # Build architecture-independent files here. binary-indep: build install diff --git a/examples/gitconfig b/examples/gitconfig index b7a6629..9efc089 100644 --- a/examples/gitconfig +++ b/examples/gitconfig @@ -14,11 +14,15 @@ # Automatically Bcc the address below #autobcc = your.name@yourcompany.com + # Automatically sign newly created patches + #autosign = Signed-off-by + # Set to 'yes' if you don't want to use the 'resolved' command. # 'refresh' will automatically mark the conflicts as resolved #autoresolved = no # SMTP server for sending patches + #smtpserver = /usr/sbin/sendmail -t -i #smtpserver = localhost:25 # Set to 'yes' to use SMTP over TLS @@ -60,13 +64,6 @@ # To support local parent branches: #pull-policy = rebase - # The three-way merge tool. Note that the 'output' file contains the - # same data as 'branch1'. This is useful for tools that do not take an - # output parameter - #merger = diff3 -L current -L ancestor -L patched -m -E \ - # \"%(branch1)s\" \"%(ancestor)s\" \"%(branch2)s\" \ - # > \"%(output)s\" - # Interactive two/three-way merge tool. It is executed by the # 'resolved --interactive' command #i3merge = xxdiff --title1 current --title2 ancestor --title3 patched \ @@ -102,6 +99,10 @@ # The maximum length of an automatically generated patch name #namelenth = 30 + # Extra options to pass to "git diff" (extend/override with + # -O/--diff-opts). For example, -M turns on rename detection. + #diff-opts = -M + [mail "alias"] # E-mail aliases used with the 'mail' command git = git@vger.kernel.org diff --git a/perf/.gitignore b/perf/.gitignore new file mode 100644 index 0000000..dfae110 --- /dev/null +++ b/perf/.gitignore @@ -0,0 +1,2 @@ +/*.orig +/*.trash diff --git a/perf/create_synthetic_repo.py b/perf/create_synthetic_repo.py new file mode 100644 index 0000000..4d6ef6b --- /dev/null +++ b/perf/create_synthetic_repo.py @@ -0,0 +1,61 @@ +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 != None: + print 'from :%d' % parent + for fn, fm in sorted(files.iteritems()): + 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 xrange(10)) + +def iter_paths(): + for i in xrange(32): + for j in xrange(32): + for k in xrange(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() diff --git a/perf/find_patchbomb.py b/perf/find_patchbomb.py new file mode 100644 index 0000000..69a78c7 --- /dev/null +++ b/perf/find_patchbomb.py @@ -0,0 +1,31 @@ +# Feed this with git rev-list HEAD --parents + +import sys + +parents = {} +for line in sys.stdin.readlines(): + commits = line.split() + parents[commits[0]] = commits[1:] + +sequence_num = {} +stack = [] +for commit in parents.keys(): + 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.iteritems()) +print '%s is a sequence of %d patches' % (commit, num) diff --git a/perf/perftest.py b/perf/perftest.py new file mode 100644 index 0000000..e5ed04b --- /dev/null +++ b/perf/perftest.py @@ -0,0 +1,96 @@ +import datetime, os, os.path, subprocess, 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.iteritems()): + print '%s: %s' % (fun, desc) +else: + for test in args: + perftests[test]() diff --git a/perf/setup.sh b/perf/setup.sh new file mode 100644 index 0000000..b92ddfc --- /dev/null +++ b/perf/setup.sh @@ -0,0 +1,52 @@ +krepo='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 diff --git a/setup.py b/setup.py index 10b3715..fb67958 100755 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ import sys, glob, os from distutils.core import setup -from stgit.version import version, git_min_ver, python_min_ver +from stgit import version def __version_to_list(version): """Convert a version string to a list of numbers or strings @@ -28,9 +28,9 @@ def __check_python_version(): """Check the minimum Python version """ pyver = '.'.join(map(lambda x: str(x), sys.version_info)) - if not __check_min_version(python_min_ver, pyver): + if not __check_min_version(version.python_min_ver, pyver): print >> sys.stderr, 'Python version %s or newer required. Found %s' \ - % (python_min_ver, pyver) + % (version.python_min_ver, pyver) sys.exit(1) def __check_git_version(): @@ -38,11 +38,31 @@ def __check_git_version(): """ from stgit.run import Run gitver = Run('git', '--version').output_one_line().split()[2] - if not __check_min_version(git_min_ver, gitver): + if not __check_min_version(version.git_min_ver, gitver): print >> sys.stderr, 'GIT version %s or newer required. Found %s' \ - % (git_min_ver, gitver) + % (version.git_min_ver, gitver) sys.exit(1) +def __run_setup(): + setup(name = 'stgit', + version = version.version, + license = 'GPLv2', + author = 'Catalin Marinas', + author_email = 'catalin.marinas@gmail.com', + url = 'http://www.procode.org/stgit/', + description = 'Stacked GIT', + long_description = 'Push/pop utility on top of GIT', + scripts = ['stg'], + packages = ['stgit', 'stgit.commands', 'stgit.lib'], + data_files = [ + ('share/stgit/templates', glob.glob('templates/*.tmpl')), + ('share/stgit/examples', glob.glob('examples/*.tmpl')), + ('share/stgit/examples', ['examples/gitconfig']), + ('share/stgit/contrib', ['contrib/diffcol.sh', + 'contrib/stgbashprompt.sh']), + ('share/stgit/completion', ['stgit-completion.bash']) + ]) + # Check the minimum versions required if sys.argv[1] in ['install', 'build']: __check_python_version() @@ -51,24 +71,11 @@ if sys.argv[1] in ['install', 'build']: # ensure readable template files old_mask = os.umask(0022) -setup(name = 'stgit', - version = version, - license = 'GPLv2', - author = 'Catalin Marinas', - author_email = 'catalin.marinas@gmail.com', - url = 'http://www.procode.org/stgit/', - description = 'Stacked GIT', - long_description = 'Push/pop utility on top of GIT', - scripts = ['stg'], - packages = ['stgit', 'stgit.commands'], - data_files = [('share/stgit/templates', glob.glob('templates/*.tmpl')), - ('share/stgit/examples', glob.glob('examples/*.tmpl')), - ('share/stgit/examples', ['examples/gitconfig']), - ('share/stgit/contrib', ['contrib/diffcol.sh', - 'contrib/stgbashprompt.sh', - 'contrib/stgit-completion.bash']), - ('share/doc/stgit', glob.glob('doc/*.txt'))] - ) +try: + version.write_builtin_version() + __run_setup() +finally: + version.delete_builtin_version() # restore the old mask os.umask(old_mask) diff --git a/stg-build b/stg-build new file mode 100755 index 0000000..2af6523 --- /dev/null +++ b/stg-build @@ -0,0 +1,41 @@ +#!/usr/bin/env python +# -*- python -*- +import optparse, 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).iterkeys()): + 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() diff --git a/stgit/argparse.py b/stgit/argparse.py new file mode 100644 index 0000000..406ada3 --- /dev/null +++ b/stgit/argparse.py @@ -0,0 +1,284 @@ +"""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).""" + +import optparse, sys, textwrap +from stgit import utils +from stgit.config import config + +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.nargs: + 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 link: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( + '--ack and --sign were both specified') + 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.""")] + +def message_options(save_template): + def no_dup(parser): + if parser.values.message != None: + raise optparse.OptionValueError( + 'Cannot give more than one --message or --file') + def no_combine(parser): + if (save_template and parser.values.message != None + and parser.values.save_template != 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: + f = file(value) + parser.values.message = f.read() + f.close() + no_combine(parser) + def templ_callback(option, opt_str, value, parser): + if value == '-': + def w(s): + sys.stdout.write(s) + else: + def w(s): + f = file(value, 'w+') + f.write(s) + f.close() + 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], + 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) + 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 author_committer_options(): + return _person_opts('author', 'auth') + _person_opts('committer', 'comm') + +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']) +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)]) diff --git a/stgit/commands/.gitignore b/stgit/commands/.gitignore new file mode 100644 index 0000000..eff10ee --- /dev/null +++ b/stgit/commands/.gitignore @@ -0,0 +1 @@ +/cmdlist.py diff --git a/stgit/commands/__init__.py b/stgit/commands/__init__.py index 4b03e3a..54a9326 100644 --- a/stgit/commands/__init__.py +++ b/stgit/commands/__init__.py @@ -1,5 +1,8 @@ +# -*- coding: utf-8 -*- + __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 @@ -14,3 +17,78 @@ 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ + +import os +from stgit import utils + +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')] +_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 = utils.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((getattr(m, 'name', mod), (mod, _kinds[m.kind], m.help)) + for mod, m in _find_commands()) + +def py_commands(commands, f): + f.write('command_list = {\n') + for key, val in sorted(commands.iteritems()): + f.write(' %r: %r,\n' % (key, val)) + f.write(' }\n') + +def _command_list(commands): + kinds = {} + for cmd, (mod, kind, help) in commands.iteritems(): + kinds.setdefault(kind, {})[cmd] = help + for kind in _kind_order: + kind = _kinds[kind] + yield kind, sorted(kinds[kind].iteritems()) + +def pretty_command_list(commands, f): + cmd_len = max(len(cmd) for cmd in commands.iterkeys()) + 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('stgsublink:%s[]::\n' % cmd) + f.write(' %s\n' % help) + f.write('\n') diff --git a/stgit/commands/add.py b/stgit/commands/add.py deleted file mode 100644 index ceea188..0000000 --- a/stgit/commands/add.py +++ /dev/null @@ -1,44 +0,0 @@ - -__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, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -""" - -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit import stack, git - - -help = 'add files or directories to the repository' -usage = """%prog [options] - -Add the files or directories passed as arguments to the -repository. When a directory name is given, all the files and -subdirectories are recursively added.""" - -directory = DirectoryHasRepository(needs_current_series = False) -options = [] - - -def func(parser, options, args): - """Add files or directories to the repository - """ - if len(args) < 1: - parser.error('incorrect number of arguments') - - git.add(args) diff --git a/stgit/commands/applied.py b/stgit/commands/applied.py deleted file mode 100644 index 45d0926..0000000 --- a/stgit/commands/applied.py +++ /dev/null @@ -1,55 +0,0 @@ - -__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, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -""" - -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit.out import * -from stgit import stack, git - - -help = 'print the applied patches' -usage = """%prog [options] - -List the patches from the series which were already pushed onto the -stack. They are listed in the order in which they were pushed, the -last one being the current (topmost) patch.""" - -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one'), - make_option('-c', '--count', - help = 'print the number of applied patches', - action = 'store_true')] - - -def func(parser, options, args): - """Show the applied patches - """ - if len(args) != 0: - parser.error('incorrect number of arguments') - - applied = crt_series.get_applied() - - if options.count: - out.stdout(len(applied)) - else: - for p in applied: - out.stdout(p) diff --git a/stgit/commands/branch.py b/stgit/commands/branch.py index 50684bb..3d912fc 100644 --- a/stgit/commands/branch.py +++ b/stgit/commands/branch.py @@ -1,6 +1,3 @@ -"""Branch command -""" - __copyright__ = """ Copyright (C) 2005, Chuck Lever @@ -19,55 +16,95 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os, time, re -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git, basedir - - -help = 'manage patch stacks' -usage = """%prog [options] branch-name [commit-id] - +from stgit import argparse, stack, git, basedir +from stgit.lib import log + +help = 'Branch operations: switch, list, create, rename, delete, ...' +kind = 'stack' +usage = ['', + '', + '--list', + '--create []', + '--clone []', + '--rename ', + '--protect []', + '--unprotect []', + '--delete [--force] ', + '--description= []'] +description = """ Create, clone, switch between, rename, or delete development branches -within a git repository. By default, a single branch called 'master' -is always created in a new repository. This subcommand allows you to -manage several patch series in the same repository via GIT branches. - -When displaying the branches, the names can be prefixed with -'s' (StGIT managed) or 'p' (protected). - -If not given any options, switch to the named branch.""" - -directory = DirectoryGotoToplevel() -options = [make_option('-c', '--create', - help = 'create a new development branch', - action = 'store_true'), - make_option('--clone', - help = 'clone the contents of the current branch', - action = 'store_true'), - make_option('--delete', - help = 'delete an existing development branch', - action = 'store_true'), - make_option('-d', '--description', - help = 'set the branch description'), - make_option('--force', - help = 'force a delete when the series is not empty', - action = 'store_true'), - make_option('-l', '--list', - help = 'list branches contained in this repository', - action = 'store_true'), - make_option('-p', '--protect', - help = 'prevent StGIT from modifying this branch', - action = 'store_true'), - make_option('-r', '--rename', - help = 'rename an existing development branch', - action = 'store_true'), - make_option('-u', '--unprotect', - help = 'allow StGIT to modify this branch', - action = 'store_true')] - +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 + stglink: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 + stglink: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 + stglink: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('-d', '--description', short = 'Set the branch description'), + opt('--force', action = 'store_true', + short = 'Force a delete when the series is not empty')] + +directory = DirectoryGotoToplevel(log = False) def __is_current_branch(branch_name): return crt_series.get_name() == branch_name @@ -161,6 +198,7 @@ def func(parser, options, args): parent_branch = parentbranch) out.info('Branch "%s" created' % args[0]) + log.compat_log_entry('branch --create') return elif options.clone: @@ -181,6 +219,8 @@ def func(parser, options, args): crt_series.clone(clone) out.done() + log.copy_log(log.default_repo(), crt_series.get_name(), clone, + 'branch --clone') return elif options.delete: @@ -188,6 +228,7 @@ def func(parser, options, args): 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.list: @@ -195,13 +236,16 @@ def func(parser, options, args): if len(args) != 0: parser.error('incorrect number of arguments') - branches = git.get_heads() - branches.sort() + 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 branches: + for i in sorted(branches): __print_branch(i, max_len) else: out.info('No branches') @@ -238,7 +282,7 @@ def func(parser, options, args): 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: diff --git a/stgit/commands/clean.py b/stgit/commands/clean.py index c703418..9b48e7b 100644 --- a/stgit/commands/clean.py +++ b/stgit/commands/clean.py @@ -15,43 +15,45 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * +from stgit.argparse import opt from stgit.out import * -from stgit import stack, git - - -help = 'delete the empty patches in the series' -usage = """%prog [options] +from stgit.commands import common +from stgit.lib import transaction +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.""" -directory = DirectoryGotoToplevel() -options = [make_option('-a', '--applied', - help = 'delete the empty applied patches', - action = 'store_true'), - make_option('-u', '--unapplied', - help = 'delete the empty unapplied patches', - action = 'store_true')] - - -def __delete_empty(patches, applied): - """Delete the empty patches - """ - for p in patches: - if crt_series.empty_patch(p): - out.start('Deleting patch "%s"' % p) - if applied and crt_series.patch_applied(p): - crt_series.pop_patch(p) - crt_series.delete_patch(p) - out.done() - elif applied and crt_series.patch_unapplied(p): - crt_series.push_patch(p) +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 @@ -59,19 +61,8 @@ def func(parser, options, args): if len(args) != 0: parser.error('incorrect number of arguments') - check_local_changes() - check_conflicts() - check_head_top_equal(crt_series) - if not (options.applied or options.unapplied): options.applied = options.unapplied = True - if options.applied: - applied = crt_series.get_applied() - __delete_empty(applied, True) - - if options.unapplied: - unapplied = crt_series.get_unapplied() - __delete_empty(unapplied, False) - - print_crt_patch(crt_series) + _clean(directory.repository.current_stack, + options.applied, options.unapplied) diff --git a/stgit/commands/clone.py b/stgit/commands/clone.py index c3b0bbe..efb7198 100644 --- a/stgit/commands/clone.py +++ b/stgit/commands/clone.py @@ -16,22 +16,29 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - from stgit.commands.common import * from stgit.utils import * -from stgit import stack, git +from stgit import argparse, stack, git +help = 'Make a local clone of a remote repository' +kind = 'repo' +usage = [' '] +description = """ +Clone a git repository into the local directory (using +stglink:clone[]) and initialise the local branch "master". -help = 'make a local clone of a remote repository' -usage = """%prog [options] +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 stglink:init[] and the '--create' and '--clone' +commands of stglink:branch[]. -Clone a GIT into the local and initialise the -patch stack.""" +The target directory will be created by this command, and must +not already exist.""" -directory = DirectoryAnywhere(needs_current_series = False) +args = [argparse.repo, argparse.dir] options = [] +directory = DirectoryAnywhere(needs_current_series = False, log = False) def func(parser, options, args): """Clone the into the local and initialises the diff --git a/stgit/commands/coalesce.py b/stgit/commands/coalesce.py new file mode 100644 index 0000000..4b5c00a --- /dev/null +++ b/stgit/commands/coalesce.py @@ -0,0 +1,126 @@ +# -*- coding: utf-8 -*- + +__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, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +""" + +from stgit.argparse import opt +from stgit.out import * +from stgit import argparse, utils +from stgit.commands import common +from stgit.lib import git, transaction + +help = 'Coalesce two or more patches into one' +kind = 'stack' +usage = ['[options] '] +description = """ +Coalesce two or more patches, creating one big patch that contains all +their changes. + +If there are conflicts when reordering the patches to match the order +you specify, you will have to resolve them manually just as if you had +done a sequence of pushes and pops yourself.""" + +args = [argparse.patch_range(argparse.applied_patches, + argparse.unapplied_patches)] +options = [opt('-n', '--name', short = 'Name of coalesced patch') + ] + argparse.message_options(save_template = True) + +directory = common.DirectoryHasRepositoryLib() + +class SaveTemplateDone(Exception): + pass + +def _coalesce_patches(trans, patches, msg, save_template): + 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 == None: + msg = '\n\n'.join('%s\n\n%s' % (pn.ljust(70, '-'), + trans.patches[pn].data.message) + for pn in patches) + if save_template: + save_template(msg) + raise SaveTemplateDone() + else: + msg = utils.edit_string(msg, '.stgit-coalesce.txt').strip() + cd = cd.set_message(msg) + + return cd + +def _coalesce(stack, iw, name, msg, save_template, patches): + + # 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') + + def make_coalesced_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, 'coalesce', + allow_conflicts = True) + push_new_patch = bool(set(patches) & set(trans.applied)) + try: + new_commit_data = _coalesce_patches(trans, patches, msg, save_template) + if new_commit_data: + # We were able to construct the coalesced 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 = _coalesce_patches(trans, patches, msg, + save_template) + assert not trans.delete_patches(lambda pn: pn in patches) + make_coalesced_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 _coalesce(stack, stack.repository.default_iw, options.name, + options.message, options.save_template, patches) diff --git a/stgit/commands/commit.py b/stgit/commands/commit.py index e56f5a0..dd8d6e6 100644 --- a/stgit/commands/commit.py +++ b/stgit/commands/commit.py @@ -15,53 +15,94 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * +from stgit.argparse import opt +from stgit.commands import common +from stgit.lib import transaction from stgit.out import * -from stgit import stack, git - -help = 'permanently store the applied patches into stack base' -usage = """%prog [options] - -Merge the applied patches into the base of the current stack and -remove them from the series while advancing the base. - -Use this command only if you want to permanently store the applied -patches and no longer manage them with StGIT.""" - -directory = DirectoryGotoToplevel() -options = [] - +from stgit import argparse + +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): - """Merge the applied patches into the base of the current stack - and remove them from the series while advancing the base - """ - if len(args) != 0: - parser.error('incorrect number of arguments') - - check_local_changes() - check_conflicts() - check_head_top_equal(crt_series) - - applied = crt_series.get_applied() - if not applied: - raise CmdException, 'No patches applied' - - if crt_series.get_protected(): - raise CmdException, 'This branch is protected. Commit is not permitted' - - crt_head = git.get_head() - - out.start('Committing %d patches' % len(applied)) - - crt_series.pop_patch(applied[0]) - git.switch(crt_head) - - for patch in applied: - crt_series.delete_patch(patch) - - out.done() + """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 != 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 != 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 xrange(min(len(stack.patchorder.applied), len(patches))): + if stack.patchorder.applied[i] == patches[i]: + common_prefix += 1 + if common_prefix < len(patches): + to_push = trans.pop_patches( + lambda pn: pn in stack.patchorder.applied[common_prefix:]) + 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) diff --git a/stgit/commands/common.py b/stgit/commands/common.py index 3840387..15fdde2 100644 --- a/stgit/commands/common.py +++ b/stgit/commands/common.py @@ -19,120 +19,85 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os, os.path, re -from optparse import OptionParser, make_option - from stgit.exception import * from stgit.utils import * from stgit.out import * from stgit.run import * from stgit import stack, git, basedir from stgit.config import config, file_extensions - +from stgit.lib import stack as libstack +from stgit.lib import git as libgit +from stgit.lib import log # Command exception class class CmdException(StgException): pass # Utility functions -class RevParseException(StgException): - """Revision spec parse error.""" - pass - def parse_rev(rev): - """Parse a revision specification into its - patchname@branchname//patch_id parts. If no branch name has a slash - in it, also accept / instead of //.""" - if '/' in ''.join(git.get_heads()): - # We have branch names with / in them. - branch_chars = r'[^@]' - patch_id_mark = r'//' - else: - # No / in branch names. - branch_chars = r'[^@/]' - patch_id_mark = r'(/|//)' - patch_re = r'(?P[^@/]+)' - branch_re = r'@(?P%s+)' % branch_chars - patch_id_re = r'%s(?P[a-z.]*)' % patch_id_mark - - # Try //patch_id. - m = re.match(r'^%s$' % patch_id_re, rev) - if m: - return None, None, m.group('patch_id') - - # Try path[@branch]//patch_id. - m = re.match(r'^%s(%s)?%s$' % (patch_re, branch_re, patch_id_re), rev) - if m: - return m.group('patch'), m.group('branch'), m.group('patch_id') - - # Try patch[@branch]. - m = re.match(r'^%s(%s)?$' % (patch_re, branch_re), rev) - if m: - return m.group('patch'), m.group('branch'), None - - # No, we can't parse that. - raise RevParseException + """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 """ - if not rev: - return None + # 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 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. + """ + # Try a [branch:]patch name first + branch, patch = parse_rev(name) + if not branch: + branch = branch_name or repository.current_branch_name - # try a GIT revision first - try: - return git.rev_parse(rev + '^{commit}') - except git.GitException: - pass + # 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)) - # try an StGIT patch name + # Other combination of branch and patch try: - patch, branch, patch_id = parse_rev(rev) - if branch == None: - series = crt_series - else: - series = stack.Series(branch) - if patch == None: - patch = series.get_current() - if not patch: - raise CmdException, 'No patches applied' - if patch in series.get_applied() or patch in series.get_unapplied() or \ - patch in series.get_hidden(): - if patch_id in ['top', '', None]: - return series.get_patch(patch).get_top() - elif patch_id == 'bottom': - return series.get_patch(patch).get_bottom() - elif patch_id == 'top.old': - return series.get_patch(patch).get_old_top() - elif patch_id == 'bottom.old': - return series.get_patch(patch).get_old_bottom() - elif patch_id == 'log': - return series.get_patch(patch).get_log() - if patch == 'base' and patch_id == None: - return series.get_base() - except RevParseException: - pass - except stack.StackException: + return repository.rev_parse('patches/%s/%s' % (branch, patch), + discard_stderr = True) + except libgit.RepositoryException: pass - raise CmdException, 'Unknown patch or revision: %s' % rev + # 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 check_local_changes(): if git.local_changes(): - raise CmdException, \ - 'local changes in the tree. Use "refresh" or "status --reset"' + raise CmdException('local changes in the tree. Use "refresh" or' + ' "status --reset"') 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.""") + 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 os.path.exists(os.path.join(basedir.get(), 'conflicts')): - raise CmdException, \ - 'Unsolved conflicts. Please resolve them first or\n' \ - ' revert the changes with "status --reset"' + if git.get_conflicts(): + raise CmdException('Unsolved conflicts. Please resolve them first' + ' or revert the changes with "status --reset"') def print_crt_patch(crt_series, branch = None): if not branch: @@ -145,29 +110,9 @@ def print_crt_patch(crt_series, branch = None): else: out.info('No patches applied') -def resolved(filename, reset = None): - if reset: - reset_file = filename + file_extensions()[reset] - if os.path.isfile(reset_file): - if os.path.isfile(filename): - os.remove(filename) - os.rename(reset_file, filename) - # update the access and modificatied times - os.utime(filename, None) - - git.update_cache([filename], force = True) - - for ext in file_extensions().values(): - fn = filename + ext - if os.path.isfile(fn): - os.remove(fn) - def resolved_all(reset = None): conflicts = git.get_conflicts() - if conflicts: - for filename in conflicts: - resolved(filename, reset) - os.remove(os.path.join(basedir.get(), 'conflicts')) + git.resolved(conflicts, reset) def push_patches(crt_series, patches, check_merged = False): """Push multiple patches onto the stack. This function is shared @@ -228,6 +173,8 @@ def parse_patches(patch_args, patch_list, boundary = 0, ordered = False): 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: @@ -286,29 +233,19 @@ def parse_patches(patch_args, patch_list, boundary = 0, ordered = False): return patches def name_email(address): - """Return a tuple consisting of the name and email parsed from a - standard 'name ' or 'email (name)' string - """ - address = re.sub('[\\\\"]', '\\\\\g<0>', address) - str_list = re.findall('^(.*)\s*<(.*)>\s*$', address) - if not str_list: - str_list = re.findall('^(.*)\s*\((.*)\)\s*$', address) - if not str_list: - raise CmdException, 'Incorrect "name "/"email (name)" string: %s' % address - return ( str_list[0][1], str_list[0][0] ) - - return str_list[0] + p = parse_name_email(address) + if p: + return p + else: + raise CmdException('Incorrect "name "/"email (name)" string: %s' + % address) def name_email_date(address): - """Return a tuple consisting of the name, email and date parsed - from a 'name date' string - """ - address = re.sub('[\\\\"]', '\\\\\g<0>', address) - str_list = re.findall('^(.*)\s*<(.*)>\s*(.*)\s*$', address) - if not str_list: - raise CmdException, 'Incorrect "name date" string: %s' % address - - return str_list[0] + p = parse_name_email_date(address) + if p: + return p + else: + raise CmdException('Incorrect "name date" string: %s' % address) def address_or_alias(addr_str): """Return the address if it contains an e-mail address or look up @@ -482,12 +419,15 @@ def parse_mail(msg): return (descr, authname, authemail, authdate, diff) -def parse_patch(fobj): - """Parse the input file and return (description, authname, +def parse_patch(text, contains_diff): + """Parse the input text and return (description, authname, authemail, authdate, diff) """ - descr, diff = __split_descr_diff(fobj.read()) - descr, authname, authemail, authdate = __parse_description(descr) + if contains_diff: + (text, diff) = __split_descr_diff(text) + else: + diff = None + (descr, authname, authemail, authdate) = __parse_description(text) # we don't yet have an agreed place for the creation date. # Just return None @@ -508,8 +448,9 @@ class DirectoryException(StgException): pass class _Directory(object): - def __init__(self, needs_current_series = True): + 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: @@ -542,6 +483,9 @@ class _Directory(object): ).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): @@ -550,6 +494,7 @@ class DirectoryAnywhere(_Directory): class DirectoryHasRepository(_Directory): def setup(self): self.git_dir # might throw an exception + log.compat_log_external_mods() class DirectoryInWorktree(DirectoryHasRepository): def setup(self): @@ -561,3 +506,12 @@ 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() diff --git a/stgit/commands/copy.py b/stgit/commands/copy.py deleted file mode 100644 index e94dd66..0000000 --- a/stgit/commands/copy.py +++ /dev/null @@ -1,45 +0,0 @@ - -__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, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -""" - -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit import stack, git - - -help = 'copy files inside the repository' -usage = """%prog [options] [ | ] - -Copy of the files and dirs passed as arguments under another name or -location inside the same repository.""" - -directory = DirectoryHasRepository() -options = [] - -def func(parser, options, args): - """Copy files inside the repository - """ - if len(args) < 1: - parser.error('incorrect number of arguments') - - if not crt_series.get_current(): - raise CmdException, 'No patches applied' - - git.copy(args[0:-1], args[-1]) diff --git a/stgit/commands/delete.py b/stgit/commands/delete.py index 1696cb9..015fb49 100644 --- a/stgit/commands/delete.py +++ b/stgit/commands/delete.py @@ -16,67 +16,62 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit.out import * -from stgit import stack, git - - -help = 'delete patches' -usage = """%prog [options] [] [..] - -Delete the patches passed as arguments. If an applied patch is to be -deleted, all other patches applied on top of it must be deleted too, -and they must be explicitly specified, since this command will not try -to delete a patch unless you explicitly ask it to. If any applied -patches are deleted, they are popped from the stack. - -Note that the 'delete' operation is irreversible.""" - -directory = DirectoryGotoToplevel() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one')] +from stgit.argparse import opt +from stgit.commands import common +from stgit.lib import transaction +from stgit import argparse + +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')] + +directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): - """Deletes one or more patches. - """ - applied_patches = crt_series.get_applied() - unapplied_patches = crt_series.get_unapplied() - all_patches = applied_patches + unapplied_patches - + """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: - patches = parse_patches(args, all_patches, len(applied_patches)) + patches = set(common.parse_patches(args, list(stack.patchorder.all))) else: parser.error('No patches specified') - applied = [] + 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 - # find the applied patches to be deleted. We can only delete - # consecutive patches in the applied range - for patch in applied_patches[::-1]: - if patch in patches: - applied.append(patch) - patches.remove(patch) + 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: - break - - # any applied patches to be deleted but not in consecutive order? - for patch in patches: - if patch in applied_patches: - raise CmdException, 'Cannot delete the applied patch "%s"' % patch - - if applied and not options.branch: - check_local_changes() - check_conflicts() - check_head_top_equal(crt_series) - - # delete the patches - for patch in applied + patches: - crt_series.delete_patch(patch) - out.info('Patch "%s" successfully deleted' % patch) - - if not options.branch: - print_crt_patch(crt_series) + 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) diff --git a/stgit/commands/diff.py b/stgit/commands/diff.py index 791b1ce..7d2f719 100644 --- a/stgit/commands/diff.py +++ b/stgit/commands/diff.py @@ -17,41 +17,39 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option from pydoc import pager - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'show the tree diff' -usage = """%prog [options] [] +from stgit import argparse, stack, git +from stgit.lib import git as gitlib +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. File names can also -be given to restrict the diff output. The tree-ish object can be a -standard git commit, tag or tree. In addition to these, the command -also supports 'base', representing the bottom of the current stack, -and '[patch][//[bottom | top]]' for the patch boundaries (defaulting to -the current one): - -rev = '([patch][//[bottom | top]]) | | base' - -If neither bottom nor top are given but a '//' is present, the command -shows the specified patch (defaulting to the current one).""" - -directory = DirectoryHasRepository() -options = [make_option('-r', '--range', - metavar = 'rev1[..[rev2]]', dest = 'revs', - help = 'show the diff between revisions'), - make_option('-O', '--diff-opts', - help = 'options to pass to git diff'), - make_option('-s', '--stat', - help = 'show the stat instead of the diff', - action = 'store_true')] - +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 can be an StGIT patch, a standard git commit, tag or +tree. In addition to these, the command also supports '{base}', +representing the bottom of the current stack. + +rev = '[branch:](|{base}) | '""" + +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) def func(parser, options, args): """Show the tree diff @@ -63,17 +61,8 @@ def func(parser, options, args): rev_list = options.revs.split('..') rev_list_len = len(rev_list) if rev_list_len == 1: - rev = rev_list[0] - if rev.endswith('/'): - # the whole patch - rev = strip_suffix('/', rev) - if rev.endswith('/'): - rev = strip_suffix('/', rev) - rev1 = rev + '//bottom' - rev2 = rev + '//top' - else: - rev1 = rev_list[0] - rev2 = None + rev1 = rev_list[0] + rev2 = None elif rev_list_len == 2: rev1 = rev_list[0] rev2 = rev_list[1] @@ -83,16 +72,11 @@ def func(parser, options, args): rev1 = 'HEAD' rev2 = None - if options.diff_opts: - diff_flags = options.diff_opts.split() - else: - diff_flags = [] - + diff_str = git.diff(args, git_id(crt_series, rev1), + rev2 and git_id(crt_series, rev2), + diff_flags = options.diff_flags) if options.stat: - out.stdout_raw(git.diffstat(args, git_id(crt_series, rev1), - git_id(crt_series, rev2)) + '\n') + out.stdout_raw(gitlib.diffstat(diff_str) + '\n') else: - diff_str = git.diff(args, git_id(crt_series, rev1), - git_id(crt_series, rev2), diff_flags = diff_flags ) if diff_str: pager(diff_str) diff --git a/stgit/commands/edit.py b/stgit/commands/edit.py index 36d2e01..4904f68 100644 --- a/stgit/commands/edit.py +++ b/stgit/commands/edit.py @@ -18,18 +18,16 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -from optparse import OptionParser, make_option -from email.Utils import formatdate - -from stgit.commands.common import * -from stgit.utils import * +from stgit.argparse import opt +from stgit import argparse, git, utils +from stgit.commands import common +from stgit.lib import git as gitlib, transaction, edit from stgit.out import * -from stgit import stack, git - help = 'edit a patch description or diff' -usage = """%prog [options] [] - +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. @@ -49,196 +47,96 @@ separator: Diff text Command-line options can be used to modify specific information -without invoking the editor. - -If the patch diff is edited but the patch application fails, the -rejected patch is stored in the .stgit-failed.patch file (and also in -.stgit-edit.{diff,txt}). The edited patch can be replaced with one of -these files using the '--file' and '--diff' options. -""" - -directory = DirectoryGotoToplevel() -options = [make_option('-d', '--diff', - help = 'edit the patch diff', - action = 'store_true'), - make_option('-f', '--file', - help = 'use FILE instead of invoking the editor'), - make_option('-O', '--diff-opts', - help = 'options to pass to git diff'), - make_option('--undo', - help = 'revert the commit generated by the last edit', - action = 'store_true'), - make_option('-a', '--annotate', metavar = 'NOTE', - help = 'annotate the patch log entry'), - make_option('-m', '--message', - help = 'replace the patch description with MESSAGE'), - make_option('--author', metavar = '"NAME "', - help = 'replae the author details with "NAME "'), - make_option('--authname', - help = 'replace the author name with AUTHNAME'), - make_option('--authemail', - help = 'replace the author e-mail with AUTHEMAIL'), - make_option('--authdate', - help = 'replace the author date with AUTHDATE'), - make_option('--commname', - help = 'replace the committer name with COMMNAME'), - make_option('--commemail', - help = 'replace the committer e-mail with COMMEMAIL') - ] + make_sign_options() - -def __update_patch(pname, fname, options): - """Update the current patch from the given file. - """ - patch = crt_series.get_patch(pname) - - bottom = patch.get_bottom() - top = patch.get_top() - - f = open(fname) - message, author_name, author_email, author_date, diff = parse_patch(f) - f.close() - - out.start('Updating patch "%s"' % pname) - - if options.diff: - git.switch(bottom) - try: - git.apply_patch(fname) - except: - # avoid inconsistent repository state - git.switch(top) - raise - - crt_series.refresh_patch(message = message, - author_name = author_name, - author_email = author_email, - author_date = author_date, - backup = True, log = 'edit') - - if crt_series.empty_patch(pname): - out.done('empty patch') - else: - out.done() - -def __edit_update_patch(pname, options): - """Edit the given patch interactively. - """ - patch = crt_series.get_patch(pname) - - if options.diff_opts: - if not options.diff: - raise CmdException, '--diff-opts only available with --diff' - diff_flags = options.diff_opts.split() - else: - diff_flags = [] - - # generate the file to be edited - descr = patch.get_description().strip() - authdate = patch.get_authdate() - - tmpl = 'From: %(authname)s <%(authemail)s>\n' - if authdate: - tmpl += 'Date: %(authdate)s\n' - tmpl += '\n%(descr)s\n' - - tmpl_dict = { - 'descr': descr, - 'authname': patch.get_authname(), - 'authemail': patch.get_authemail(), - 'authdate': patch.get_authdate() - } - - if options.diff: - # add the patch diff to the edited file - bottom = patch.get_bottom() - top = patch.get_top() - - tmpl += '---\n\n' \ - '%(diffstat)s\n' \ - '%(diff)s' - - tmpl_dict['diffstat'] = git.diffstat(rev1 = bottom, rev2 = top) - tmpl_dict['diff'] = git.diff(rev1 = bottom, rev2 = top, - diff_flags = diff_flags) - - for key in tmpl_dict: - # make empty strings if key is not available - if tmpl_dict[key] is None: - tmpl_dict[key] = '' - - text = tmpl % tmpl_dict - - if options.diff: - fname = '.stgit-edit.diff' - else: - fname = '.stgit-edit.txt' - - # write the file to be edited - f = open(fname, 'w+') - f.write(text) - f.close() - - # invoke the editor - call_editor(fname) - - __update_patch(pname, fname, options) +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.""" + +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.author_committer_options() + argparse.diff_opts_option()) + +directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): """Edit the given patch or the current one. """ - crt_pname = crt_series.get_current() + stack = directory.repository.current_stack - if not args: - pname = crt_pname - if not pname: - raise CmdException, 'No patches applied' + 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: - pname = args[0] - if crt_series.patch_unapplied(pname) or crt_series.patch_hidden(pname): - raise CmdException, 'Cannot edit unapplied or hidden patches' - elif not crt_series.patch_applied(pname): - raise CmdException, 'Unknown patch "%s"' % pname + [patchname] = args + if not stack.patches.exists(patchname): + raise common.CmdException('%s: no such patch' % patchname) else: - parser.error('incorrect number of arguments') - - check_local_changes() - check_conflicts() - check_head_top_equal(crt_series) - - if pname != crt_pname: - # Go to the patch to be edited - applied = crt_series.get_applied() - between = applied[:applied.index(pname):-1] - pop_patches(crt_series, between) - - if options.author: - options.authname, options.authemail = name_email(options.author) - - if options.undo: - out.start('Undoing the editing of "%s"' % pname) - crt_series.undo_refresh() - out.done() - elif options.message or options.authname or options.authemail \ - or options.authdate or options.commname or options.commemail \ - or options.sign_str: - # just refresh the patch with the given information - out.start('Updating patch "%s"' % pname) - crt_series.refresh_patch(message = options.message, - author_name = options.authname, - author_email = options.authemail, - author_date = options.authdate, - committer_name = options.commname, - committer_email = options.commemail, - backup = True, sign_str = options.sign_str, - log = 'edit', - notes = options.annotate) - out.done() - elif options.file: - __update_patch(pname, options.file, options) + parser.error('Cannot edit more than one patch') + + cd = orig_cd = stack.patches.get(patchname).commit.data + + cd, failed_diff = edit.auto_edit_patch( + stack.repository, cd, msg = options.message, contains_diff = True, + author = options.author, committer = options.committer, + 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 + + if cd == orig_cd or options.edit: + cd, failed_diff = edit.interactive_edit_patch( + stack.repository, cd, options.diff, options.diff_flags, failed_diff) + + def failed(): + fn = '.stgit-failed.patch' + f = file(fn, 'w') + f.write(edit.patch_desc(stack.repository, cd, + options.diff, options.diff_flags, failed_diff)) + f.close() + out.error('Edited patch did not apply.', + 'It 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() + + # 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: - __edit_update_patch(pname, options) - - if pname != crt_pname: - # Push the patches back - between.reverse() - push_patches(crt_series, between) + popped = [] + trans.patches[patchname] = stack.repository.commit(cd) + try: + for pn in popped: + trans.push_patch(pn, iw) + 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() diff --git a/stgit/commands/export.py b/stgit/commands/export.py index c4fb7e3..dfdcea1 100644 --- a/stgit/commands/export.py +++ b/stgit/commands/export.py @@ -18,18 +18,17 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit.out import * -from stgit import stack, git, templates - - -help = 'exports patches to a directory' -usage = """%prog [options] [] [] [..] - +import os +from stgit.argparse import opt +from stgit.commands import common +from stgit import argparse, git, templates +from stgit.out import out +from stgit.lib import git as gitlib + +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 @@ -46,38 +45,39 @@ file: %(authemail)s - author's e-mail %(authdate)s - patch creation date %(commname)s - committer's name - %(commemail)s - committer's e-mail -""" - -directory = DirectoryHasRepository() -options = [make_option('-d', '--dir', - help = 'export patches to DIR instead of the default'), - make_option('-p', '--patch', - help = 'append .patch to the patch names', - action = 'store_true'), - make_option('-e', '--extension', - help = 'append .EXTENSION to the patch names'), - make_option('-n', '--numbered', - help = 'prefix the patch names with order numbers', - action = 'store_true'), - make_option('-t', '--template', metavar = 'FILE', - help = 'Use FILE as a template'), - make_option('-b', '--branch', - help = 'use BRANCH instead of the default one'), - make_option('-O', '--diff-opts', - help = 'options to pass to git diff'), - make_option('-s', '--stdout', - help = 'dump the patches to the standard output', - action = 'store_true')] - + %(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' % crt_series.get_name() + dirname = 'patches-%s' % stack.name directory.cd_to_topdir() if not options.branch and git.local_changes(): @@ -89,21 +89,16 @@ def func(parser, options, args): os.makedirs(dirname) series = file(os.path.join(dirname, 'series'), 'w+') - if options.diff_opts: - diff_flags = options.diff_opts.split() - else: - diff_flags = [] - - applied = crt_series.get_applied() - unapplied = crt_series.get_unapplied() + applied = stack.patchorder.applied + unapplied = stack.patchorder.unapplied if len(args) != 0: - patches = parse_patches(args, applied + unapplied, len(applied)) + patches = common.parse_patches(args, applied + unapplied, len(applied)) else: patches = applied num = len(patches) if num == 0: - raise CmdException, 'No patches applied' + raise common.CmdException, 'No patches applied' zpadding = len(str(num)) if zpadding < 2: @@ -119,7 +114,7 @@ def func(parser, options, args): # note the base commit for this series if not options.stdout: - base_commit = crt_series.get_patch(patches[0]).get_bottom() + base_commit = stack.patches.get(patches[0]).commit.sha1 print >> series, '# This series applies on GIT commit %s' % base_commit patch_no = 1; @@ -136,25 +131,27 @@ def func(parser, options, args): print >> series, pname # get the patch description - patch = crt_series.get_patch(p) + patch = stack.patches.get(p) + cd = patch.commit.data - descr = patch.get_description().strip() + descr = cd.message.strip() descr_lines = descr.split('\n') short_descr = descr_lines[0].rstrip() long_descr = reduce(lambda x, y: x + '\n' + y, descr_lines[1:], '').strip() - tmpl_dict = {'description': patch.get_description().rstrip(), + 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': git.diffstat(rev1 = patch.get_bottom(), - rev2 = patch.get_top()), - 'authname': patch.get_authname(), - 'authemail': patch.get_authemail(), - 'authdate': patch.get_authdate(), - 'commname': patch.get_commname(), - 'commemail': patch.get_commemail()} + '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} for key in tmpl_dict: if not tmpl_dict[key]: tmpl_dict[key] = '' @@ -162,10 +159,10 @@ def func(parser, options, args): try: descr = tmpl % tmpl_dict except KeyError, err: - raise CmdException, 'Unknown patch template variable: %s' \ + raise common.CmdException, 'Unknown patch template variable: %s' \ % err except TypeError: - raise CmdException, 'Only "%(name)s" variables are ' \ + raise common.CmdException, 'Only "%(name)s" variables are ' \ 'supported in the patch template' if options.stdout: @@ -175,13 +172,11 @@ def func(parser, options, args): if options.stdout and num > 1: print '-'*79 - print patch.get_name() + print patch.name print '-'*79 f.write(descr) - f.write(git.diff(rev1 = patch.get_bottom(), - rev2 = patch.get_top(), - diff_flags = diff_flags)) + f.write(diff) if not options.stdout: f.close() patch_no += 1 diff --git a/stgit/commands/files.py b/stgit/commands/files.py index cc9ed30..46d43c1 100644 --- a/stgit/commands/files.py +++ b/stgit/commands/files.py @@ -17,57 +17,51 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'show the files modified by a patch (or the current patch)' -usage = """%prog [options] [] +from stgit import argparse, stack, git +from stgit.lib import git as gitlib +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.""" -directory = DirectoryHasRepository() -options = [make_option('-s', '--stat', - help = 'show the diff stat', - action = 'store_true'), - make_option('-b', '--branch', - help = 'use BRANCH instead of the default one'), - make_option('-O', '--diff-opts', - help = 'options to pass to git diff'), - make_option('--bare', - help = 'bare file names (useful for scripting)', - action = 'store_true')] +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) def func(parser, options, args): """Show the files modified by a patch (or the current patch) """ if len(args) == 0: - patch = '' + patch = 'HEAD' elif len(args) == 1: patch = args[0] else: parser.error('incorrect number of arguments') - rev1 = git_id(crt_series, '%s//bottom' % patch) - rev2 = git_id(crt_series, '%s//top' % patch) + rev1 = git_id(crt_series, '%s^' % patch) + rev2 = git_id(crt_series, '%s' % patch) if options.stat: - out.stdout_raw(git.diffstat(rev1 = rev1, rev2 = rev2) + '\n') + out.stdout_raw(gitlib.diffstat(git.diff(rev1 = rev1, rev2 = rev2)) + '\n') elif options.bare: out.stdout_raw(git.barefiles(rev1, rev2) + '\n') else: - if options.diff_opts: - diff_flags = options.diff_opts.split() - else: - diff_flags = [] - - out.stdout_raw(git.files(rev1, rev2, diff_flags = diff_flags) + '\n') + out.stdout_raw(git.files(rev1, rev2, diff_flags = options.diff_flags) + + '\n') diff --git a/stgit/commands/float.py b/stgit/commands/float.py index 5af7e85..7c3dcdf 100644 --- a/stgit/commands/float.py +++ b/stgit/commands/float.py @@ -17,24 +17,28 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * -from stgit import stack, git - -help = 'push patches to the top, even if applied' -usage = """%prog [ | -s [] ] +from stgit import argparse, stack, git +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).""" -directory = DirectoryGotoToplevel() -options = [make_option('-s', '--series', - help = 'rearrange according to a series file', - action = 'store_true')] +args = [argparse.patch_range(argparse.applied_patches, + argparse.unapplied_patches)] +options = [ + opt('-s', '--series', action = 'store_true', + short = 'Rearrange according to a series file')] + +directory = DirectoryGotoToplevel(log = True) def func(parser, options, args): """Pops and pushed to make the named patch the topmost patch diff --git a/stgit/commands/fold.py b/stgit/commands/fold.py index 3930a1f..66a2dd9 100644 --- a/stgit/commands/fold.py +++ b/stgit/commands/fold.py @@ -16,17 +16,16 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'integrate a GNU diff patch into the current patch' -usage = """%prog [options] [] +from stgit import argparse, stack, git +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 @@ -34,13 +33,14 @@ 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.""" -directory = DirectoryHasRepository() -options = [make_option('-t', '--threeway', - help = 'perform a three-way merge with the current patch', - action = 'store_true'), - make_option('-b', '--base', - help = 'use BASE instead of HEAD applying the patch')] +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 applying the patch')] +directory = DirectoryHasRepository(log = True) def func(parser, options, args): """Integrate a GNU diff patch into the current patch diff --git a/stgit/commands/goto.py b/stgit/commands/goto.py index 84b840b..60a917e 100644 --- a/stgit/commands/goto.py +++ b/stgit/commands/goto.py @@ -15,53 +15,41 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit import stack, git - - -help = 'push or pop patches to the given one' -usage = """%prog [options] - +from stgit.commands import common +from stgit.lib import transaction +from stgit import argparse + +help = 'Push or pop patches to the given one' +kind = 'stack' +usage = [''] +description = """ Push/pop patches to/from the stack until the one given on the command -line becomes current. There is no '--undo' option for 'goto'. Use the -'push --undo' command for this.""" +line becomes current.""" -directory = DirectoryGotoToplevel() -options = [make_option('-k', '--keep', - help = 'keep the local changes when popping patches', - action = 'store_true')] +args = [argparse.other_applied_patches, argparse.unapplied_patches] +options = [] +directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): - """Pushes the given patch or all onto the series - """ if len(args) != 1: parser.error('incorrect number of arguments') - - check_conflicts() - check_head_top_equal(crt_series) - - if not options.keep: - check_local_changes() - - applied = crt_series.get_applied() - unapplied = crt_series.get_unapplied() patch = args[0] - if patch in applied: - applied.reverse() - patches = applied[:applied.index(patch)] - pop_patches(crt_series, patches, options.keep) - elif patch in unapplied: - if options.keep: - raise CmdException, 'Cannot use --keep with patch pushing' - patches = unapplied[:unapplied.index(patch)+1] - push_patches(crt_series, patches) + stack = directory.repository.current_stack + iw = stack.repository.default_iw + trans = transaction.StackTransaction(stack, 'goto') + 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: + for pn in trans.unapplied[:trans.unapplied.index(patch)+1]: + trans.push_patch(pn, iw) + except transaction.TransactionHalted: + pass + elif patch in trans.hidden: + raise common.CmdException('Cannot goto a hidden patch') else: - raise CmdException, 'Patch "%s" does not exist' % patch - - print_crt_patch(crt_series) + raise common.CmdException('Patch "%s" does not exist' % patch) + return trans.run(iw) diff --git a/stgit/commands/hide.py b/stgit/commands/hide.py index 1a38907..014febb 100644 --- a/stgit/commands/hide.py +++ b/stgit/commands/hide.py @@ -16,23 +16,26 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'hide a patch in the series' -usage = """%prog [options] +from stgit import argparse, stack, git +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.""" -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one')] +args = [argparse.patch_range(argparse.applied_patches, + argparse.unapplied_patches)] +options = [ + opt('-b', '--branch', args = [argparse.stg_branches], + short = 'Use BRANCH instead of the default branch')] + +directory = DirectoryHasRepository(log = True) def func(parser, options, args): """Hide a range of patch in the series diff --git a/stgit/commands/id.py b/stgit/commands/id.py index 94b0229..566edcc 100644 --- a/stgit/commands/id.py +++ b/stgit/commands/id.py @@ -15,28 +15,27 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit.out import * -from stgit import stack, git - - -help = 'print the GIT hash value of a StGIT reference' -usage = """%prog [options] [id] - -Print the hash value of a GIT id (defaulting to HEAD). In addition to -the standard GIT id's like heads and tags, this command also accepts -'base[@]' and '[[@]][//[bottom | top]]'. If no -'top' or 'bottom' are passed and is a valid patch name, 'top' -will be used by default.""" - -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one')] - +from stgit.out import out +from stgit.commands import common +from stgit.lib import stack +from stgit import argparse + +help = 'Print the git hash value of a StGit reference' +kind = 'repo' +usage = ['[options] [id]'] +description = """ +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 +'[:]' and '[:]{base}' showing the id of a patch +or the base of the stack. 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 @@ -48,4 +47,4 @@ def func(parser, options, args): else: parser.error('incorrect number of arguments') - out.stdout(git_id(crt_series, id_str)) + out.stdout(common.git_commit(id_str, directory.repository).sha1) diff --git a/stgit/commands/imprt.py b/stgit/commands/imprt.py index cd44d3f..de5e9a5 100644 --- a/stgit/commands/imprt.py +++ b/stgit/commands/imprt.py @@ -18,17 +18,17 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import sys, os, re, email from mailbox import UnixMailbox from StringIO import StringIO -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'import a GNU diff file as a new patch' -usage = """%prog [options] [|] +from stgit import argparse, stack, git +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 @@ -44,52 +44,45 @@ stack. The patch description has to be separated from the data with a '---' line.""" -directory = DirectoryHasRepository() -options = [make_option('-m', '--mail', - help = 'import the patch from a standard e-mail file', - action = 'store_true'), - make_option('-M', '--mbox', - help = 'import a series of patches from an mbox file', - action = 'store_true'), - make_option('-s', '--series', - help = 'import a series of patches', - action = 'store_true'), - make_option('-u', '--url', - help = 'import a patch from a URL', - action = 'store_true'), - make_option('-n', '--name', - help = 'use NAME as the patch name'), - make_option('-t', '--strip', - help = 'strip numbering and extension from patch name', - action = 'store_true'), - make_option('-i', '--ignore', - help = 'ignore the applied patches in the series', - action = 'store_true'), - make_option('--replace', - help = 'replace the unapplied patches in the series', - action = 'store_true'), - make_option('-b', '--base', - help = 'use BASE instead of HEAD for file importing'), - make_option('-e', '--edit', - help = 'invoke an editor for the patch description', - action = 'store_true'), - make_option('-p', '--showpatch', - help = 'show the patch content in the editor buffer', - action = 'store_true'), - make_option('-a', '--author', metavar = '"NAME "', - help = 'use "NAME " as the author details'), - make_option('--authname', - help = 'use AUTHNAME as the author name'), - make_option('--authemail', - help = 'use AUTHEMAIL as the author e-mail'), - make_option('--authdate', - help = 'use AUTHDATE as the author date'), - make_option('--commname', - help = 'use COMMNAME as the committer name'), - make_option('--commemail', - help = 'use COMMEMAIL as the committer e-mail') - ] + make_sign_options() - +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'), + opt('-u', '--url', action = 'store_true', + short = 'Import a patch from a URL'), + opt('-n', '--name', + short = 'Use NAME as the patch name'), + opt('-t', '--strip', 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('-e', '--edit', action = 'store_true', + short = 'Invoke an editor for the patch description'), + opt('-p', '--showpatch', action = 'store_true', + short = 'Show the patch content in the editor buffer'), + opt('-a', '--author', metavar = '"NAME "', + short = 'Use "NAME " as the author details'), + opt('--authname', + short = 'Use AUTHNAME as the author name'), + opt('--authemail', + short = 'Use AUTHEMAIL as the author e-mail'), + opt('--authdate', + short = 'Use AUTHDATE as the author date'), + opt('--commname', + short = 'Use COMMNAME as the committer name'), + opt('--commemail', + short = 'Use COMMEMAIL as the committer e-mail'), + ] + argparse.sign_options() + +directory = DirectoryHasRepository(log = True) def __strip_patch_name(name): stripped = re.sub('^[0-9]+-(.*)$', '\g<1>', name) @@ -175,14 +168,42 @@ def __create_patch(filename, message, author_name, author_email, 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 + import bz2, gzip + 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, e: + pass + + # plain old file... + return (open(filename), filename) + def __import_file(filename, options, patch = None): """Import a patch from a file or standard input """ + pname = None if filename: - f = file(filename) + (f, pname) = __get_handle_and_name(filename) else: f = sys.stdin + if patch: + pname = patch + elif not pname: + pname = filename + if options.mail: try: msg = email.message_from_file(f) @@ -192,16 +213,11 @@ def __import_file(filename, options, patch = None): parse_mail(msg) else: message, author_name, author_email, author_date, diff = \ - parse_patch(f) + parse_patch(f.read(), contains_diff = True) if filename: f.close() - if patch: - pname = patch - else: - pname = filename - __create_patch(pname, message, author_name, author_email, author_date, diff, options) diff --git a/stgit/commands/init.py b/stgit/commands/init.py index 475a4ce..6ffb93e 100644 --- a/stgit/commands/init.py +++ b/stgit/commands/init.py @@ -16,24 +16,21 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit import stack, git - - -help = 'initialise the current branch for use with StGIT' -usage = """%prog [options] - -Initialise the current GIT branch to be used as an StGIT stack. Note -that you must already be in a GIT repository and .git/HEAD must point -to a valid file in refs/heads/.""" - -directory = DirectoryHasRepository() +from stgit.commands import common +from stgit.lib import stack + +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 @@ -41,4 +38,4 @@ def func(parser, options, args): if len(args) != 0: parser.error('incorrect number of arguments') - crt_series.init() + stack.Stack.initialise(directory.repository) diff --git a/stgit/commands/log.py b/stgit/commands/log.py index 52d55a5..39cdfe7 100644 --- a/stgit/commands/log.py +++ b/stgit/commands/log.py @@ -1,5 +1,8 @@ +# -*- coding: utf-8 -*- + __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 @@ -15,133 +18,74 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os, time -from optparse import OptionParser, make_option -from pydoc import pager -from stgit.commands.common import * -from stgit import stack, git -from stgit.out import * -from stgit.run import Run - -help = 'display the patch changelog' -usage = """%prog [options] [patch] - -List all the current and past commit ids of the given patch. The ---graphical option invokes gitk instead of printing. The changelog -commit messages have the form ' '. The -can be one of the following: - - new - new patch created - refresh - local changes were added to the patch - push - the patch was cleanly pushed onto the stack - push(m) - the patch was pushed onto the stack with a three-way merge - push(f) - the patch was fast-forwarded - undo - the patch boundaries were restored to the old values - -Note that only the diffs shown in the 'refresh', 'undo' and 'sync' -actions are meaningful for the patch changes. The 'push' actions -represent the changes to the entire base of the current -patch. Conflicts reset the patch content and a subsequent 'refresh' -will show the entire patch.""" - -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one'), - make_option('-p', '--patch', - help = 'show the refresh diffs', - action = 'store_true'), - make_option('-n', '--number', type = 'int', - help = 'limit the output to NUMBER commits'), - make_option('-f', '--full', - help = 'show the full commit ids', - action = 'store_true'), - make_option('-g', '--graphical', - help = 'run gitk instead of printing', - action = 'store_true')] - -def show_log(log, options): - """List the patch changelog - """ - commit = git.get_commit(log) - if options.number != None: - n = options.number - else: - n = -1 - diff_list = [] - while commit: - if n == 0: - # limit the output - break - - log = commit.get_log().split('\n') - - cmd_rev = log[0].split() - if len(cmd_rev) >= 2: - cmd = cmd_rev[0] - rev = cmd_rev[1] - elif len(cmd_rev) == 1: - cmd = cmd_rev[0] - rev = '' - else: - cmd = rev = '' - - if options.patch: - if cmd in ['refresh', 'undo', 'sync', 'edit']: - diff_list.append(git.pretty_commit(commit.get_id_hash())) - - # limiter decrement - n -= 1 - else: - if len(log) >= 3: - notes = log[2] - else: - notes = '' - author_name, author_email, author_date = \ - name_email_date(commit.get_author()) - secs, tz = author_date.split() - date = '%s %s' % (time.ctime(int(secs)), tz) - - if options.full: - out.stdout('%-7s %-40s %s' % (cmd[:7], rev[:40], date)) - else: - out.stdout('%-8s [%-7s] %-28s %s' % \ - (rev[:8], cmd[:7], notes[:28], date)) - - # limiter decrement - n -= 1 - - parent = commit.get_parent() - if parent: - commit = git.get_commit(parent) - else: - commit = None - - if options.patch and diff_list: - pager('\n'.join(diff_list).rstrip()) +import os.path +from optparse import make_option +from stgit import argparse, run +from stgit.argparse import opt +from stgit.commands import common +from stgit.lib import log +from stgit.out import out + +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('-p', '--patch', 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')] + +directory = common.DirectoryHasRepositoryLib() + +def show_log(stacklog, pathlim, num, full, show_diff): + cmd = ['git', 'log'] + if num != None and num > 0: + cmd.append('-%d' % num) + if show_diff: + cmd.append('-p') + elif not full: + cmd.append('--pretty=format:%h %aD %s') + run.Run(*(cmd + [stacklog.sha1, '--'] + pathlim)).run() def func(parser, options, args): - """Show the patch changelog - """ - if len(args) == 0: - name = crt_series.get_current() - if not name: - raise CmdException, 'No patches applied' - elif len(args) == 1: - name = args[0] - if not name in crt_series.get_applied() + crt_series.get_unapplied() + \ - crt_series.get_hidden(): - raise CmdException, 'Unknown patch "%s"' % name + if options.branch: + stack = directory.repository.get_stack(options.branch) else: - parser.error('incorrect number of arguments') - - patch = crt_series.get_patch(name) - - log = patch.get_log() - if not log: - raise CmdException, 'No changelog for patch "%s"' % name + 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 + stacklog = log.get_log_entry(stack.repository, logref, logcommit) + pathlim = [os.path.join('patches', pn) for pn in patches] if options.graphical: - # discard the exit codes generated by SIGINT, SIGKILL, SIGTERM - Run('gitk', log).returns([0, -2, -9, -15]).run() + for o in ['diff', 'number', 'full']: + if getattr(options, o): + parser.error('cannot combine --graphical and --%s' % o) + # Discard the exit codes generated by SIGINT, SIGKILL, and SIGTERM. + run.Run(*(['gitk', stacklog.simplified.sha1, '--'] + pathlim) + ).returns([0, -2, -9, -15]).run() else: - show_log(log, options) + show_log(stacklog.simplified, pathlim, + options.number, options.full, options.diff) diff --git a/stgit/commands/mail.py b/stgit/commands/mail.py index 05c905b..0b3157e 100644 --- a/stgit/commands/mail.py +++ b/stgit/commands/mail.py @@ -17,27 +17,30 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import sys, os, re, time, datetime, socket, smtplib, getpass import email, email.Utils, email.Header -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git, version, templates +from stgit import argparse, stack, git, version, templates from stgit.config import config +from stgit.run import Run +from stgit.lib import git as gitlib - -help = 'send a patch or series of patches by e-mail' -usage = """%prog [options] [] [] [..] - +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. 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 +'--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'. +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 @@ -84,72 +87,63 @@ the following: %(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 + %(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 %(shortdescr)s - the first line of the patch description""" -directory = DirectoryHasRepository() -options = [make_option('-a', '--all', - help = 'e-mail all the applied patches', - action = 'store_true'), - make_option('--to', - help = 'add TO to the To: list', - action = 'append'), - make_option('--cc', - help = 'add CC to the Cc: list', - action = 'append'), - make_option('--bcc', - help = 'add BCC to the Bcc: list', - action = 'append'), - make_option('--auto', - help = 'automatically cc the patch signers', - action = 'store_true'), - make_option('--noreply', - help = 'do not send subsequent messages as replies', - action = 'store_true'), - make_option('--unrelated', - help = 'send patches without sequence numbering', - action = 'store_true'), - make_option('--attach', - help = 'send a patch as attachment', - action = 'store_true'), - make_option('-v', '--version', metavar = 'VERSION', - help = 'add VERSION to the [PATCH ...] prefix'), - make_option('--prefix', metavar = 'PREFIX', - help = 'add PREFIX to the [... PATCH ...] prefix'), - make_option('-t', '--template', metavar = 'FILE', - help = 'use FILE as the message template'), - make_option('-c', '--cover', metavar = 'FILE', - help = 'send FILE as the cover message'), - make_option('-e', '--edit-cover', - help = 'edit the cover message before sending', - action = 'store_true'), - make_option('-E', '--edit-patches', - help = 'edit each patch before sending', - action = 'store_true'), - make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS', - help = 'sleep for SECONDS between e-mails sending'), - make_option('--refid', - help = 'use REFID as the reference id'), - make_option('--smtp-server', metavar = 'HOST[:PORT]', - help = 'SMTP server to use for sending mail'), - make_option('-u', '--smtp-user', metavar = 'USER', - help = 'username for SMTP authentication'), - make_option('-p', '--smtp-password', metavar = 'PASSWORD', - help = 'username for SMTP authentication'), - make_option('-T', '--smtp-tls', - help = 'use SMTP with TLS encryption', - action = 'store_true'), - make_option('-b', '--branch', - help = 'use BRANCH instead of the default one'), - make_option('-O', '--diff-opts', - help = 'options to pass to git diff'), - make_option('-m', '--mbox', - help = 'generate an mbox file instead of sending', - action = 'store_true')] - +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', + short = 'Add TO to the To: list'), + opt('--cc', action = 'append', + short = 'Add CC to the Cc: list'), + opt('--bcc', action = 'append', + short = 'Add BCC to the Bcc: list'), + opt('--auto', action = 'store_true', + short = 'Automatically cc the patch signers'), + opt('--noreply', 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('-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('--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') + ] + argparse.diff_opts_option() + +directory = DirectoryHasRepository(log = False) def __get_sender(): """Return the 'authname ' string as read from the @@ -185,8 +179,14 @@ def __parse_addresses(msg): return (from_addr_list[0], to_addr_list) -def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep, - smtpuser, smtppassword, use_tls): +def __send_message_sendmail(sendmail, msg): + """Send the message using the sendmail command. + """ + cmd = sendmail.split() + Run(*cmd).raw_input(msg).discard_output() + +def __send_message_smtp(smtpserver, from_addr, to_addr_list, msg, + smtpuser, smtppassword, use_tls): """Send the message using the given SMTP server """ try: @@ -208,13 +208,25 @@ def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep, result = s.sendmail(from_addr, to_addr_list, msg) if len(result): print "mail server refused delivery for the following recipients: %s" % result - # give recipients a chance of receiving patches in the correct order - time.sleep(sleep) except Exception, err: raise CmdException, str(err) s.quit() +def __send_message(smtpserver, from_addr, to_addr_list, msg, + sleep, smtpuser, smtppassword, use_tls): + """Message sending dispatcher. + """ + if smtpserver.startswith('/'): + # Use the sendmail tool + __send_message_sendmail(smtpserver, msg) + else: + # Use the SMTP server (we have host and port information) + __send_message_smtp(smtpserver, from_addr, to_addr_list, msg, + smtpuser, smtppassword, use_tls) + # give recipients a chance of receiving patches in the correct order + time.sleep(sleep) + def __build_address_headers(msg, options, extra_cc = []): """Build the address headers and check existing headers in the template. @@ -361,9 +373,9 @@ def __build_cover(tmpl, patches, msg_id, options): 'number': number_str, 'shortlog': stack.shortlog(crt_series.get_patch(p) for p in patches), - 'diffstat': git.diffstat( - rev1 = git_id(crt_series, '%s//bottom' % patches[0]), - rev2 = git_id(crt_series, '%s//top' % patches[-1]))} + 'diffstat': gitlib.diffstat(git.diff( + rev1 = git_id(crt_series, '%s^' % patches[0]), + rev2 = git_id(crt_series, '%s' % patches[-1])))} try: msg_string = tmpl % tmpl_dict @@ -402,8 +414,8 @@ def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options): options.edit_patches = True descr_lines = descr.split('\n') - short_descr = descr_lines[0].rstrip() - long_descr = '\n'.join(descr_lines[1:]).lstrip() + 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(); @@ -431,11 +443,6 @@ def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options): prefix_str = confprefix + ' ' else: prefix_str = '' - - if options.diff_opts: - diff_flags = options.diff_opts.split() - else: - diff_flags = [] total_nr_str = str(total_nr) patch_nr_str = str(patch_nr).zfill(len(total_nr_str)) @@ -444,6 +451,9 @@ def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options): else: number_str = '' + 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 @@ -452,13 +462,8 @@ def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options): 'longdescr': long_descr, # for backward template compatibility 'endofheaders': '', - 'diff': git.diff( - rev1 = git_id(crt_series, '%s//bottom' % patch), - rev2 = git_id(crt_series, '%s//top' % patch), - diff_flags = diff_flags), - 'diffstat': git.diffstat( - rev1 = git_id(crt_series, '%s//bottom'%patch), - rev2 = git_id(crt_series, '%s//top' % patch)), + 'diff': diff, + 'diffstat': gitlib.diffstat(diff), # for backward template compatibility 'date': '', 'version': version_str, diff --git a/stgit/commands/new.py b/stgit/commands/new.py index 6a8f086..067882a 100644 --- a/stgit/commands/new.py +++ b/stgit/commands/new.py @@ -16,70 +16,91 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit import stack, git - - -help = 'create a new patch and make it the topmost one' -usage = """%prog [options] [name] - -Create a new, empty patch and make it the topmost one. If the -'--message' option is not passed, an editor is invoked with the -.git/patchdescr.tmpl, ~/.stgit/templates/patchdescr.tmpl or -/usr/share/stgit/templates/patchdescr.tmpl file used a as template, -together with generated lines. The local changes in the working tree -are not included in the patch; an "stg refresh" command is needed for -this. - -If no name is given for the new patch, one is generated from the first -line of the commit message.""" - -directory = DirectoryGotoToplevel() -options = [make_option('-m', '--message', - help = 'use MESSAGE as the patch description'), - make_option('-s', '--showpatch', - help = 'show the patch content in the editor buffer', - action = 'store_true'), - make_option('-a', '--author', metavar = '"NAME "', - help = 'use "NAME " as the author details'), - make_option('--authname', - help = 'use AUTHNAME as the author name'), - make_option('--authemail', - help = 'use AUTHEMAIL as the author e-mail'), - make_option('--authdate', - help = 'use AUTHDATE as the author date'), - make_option('--commname', - help = 'use COMMNAME as the committer name'), - make_option('--commemail', - help = 'use COMMEMAIL as the committer e-mail') - ] + make_sign_options() - +from stgit import argparse, utils +from stgit.commands import common +from stgit.lib import git as gitlib, transaction +from stgit.config import config + +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 stglink: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_committer_options() + + argparse.message_options(save_template = True) + + argparse.sign_options()) + +directory = common.DirectoryHasRepositoryLib() def func(parser, options, args): - """Creates a new patch - """ + """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 # autogenerate a name + 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') - check_conflicts() - check_head_top_equal(crt_series) + cd = gitlib.CommitData( + tree = stack.head.data.tree, parents = [stack.head], message = '', + author = gitlib.Person.author(), committer = gitlib.Person.committer()) + + # Set patch commit message from commandline. + if options.message != None: + cd = cd.set_message(options.message) - if options.author: - options.authname, options.authemail = name_email(options.author) + # Modify author and committer data. + cd = (cd.set_author(options.author(cd.author)) + .set_committer(options.committer(cd.committer))) - crt_series.new_patch(name, message = options.message, - show_patch = options.showpatch, - author_name = options.authname, - author_email = options.authemail, - author_date = options.authdate, - committer_name = options.commname, - committer_email = options.commemail, - sign_str = options.sign_str) + # Add Signed-off-by: or similar. + if options.sign_str != None: + sign_str = options.sign_str + else: + sign_str = config.get("stgit.autosign") + + if sign_str != None: + cd = cd.set_message( + utils.add_sign_line(cd.message, sign_str, + cd.committer.name, cd.committer.email)) + + if options.save_template: + options.save_template(cd.message) + return utils.STGIT_SUCCESS + + # Let user edit the commit message manually. + if not options.message: + cd = cd.set_message(utils.edit_string(cd.message, '.stgit-new.txt')) + if name == None: + name = utils.make_patch_name(cd.message, + lambda name: stack.patches.exists(name)) + + # Write the new patch. + iw = stack.repository.default_iw + trans = transaction.StackTransaction(stack, 'new') + trans.patches[name] = stack.repository.commit(cd) + trans.applied.append(name) + return trans.run() diff --git a/stgit/commands/patches.py b/stgit/commands/patches.py index 140699d..54fac21 100644 --- a/stgit/commands/patches.py +++ b/stgit/commands/patches.py @@ -16,29 +16,30 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option from pydoc import pager - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'show the applied patches modifying a file' -usage = """%prog [options] [] +from stgit import argparse, stack, git +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.""" -directory = DirectoryHasRepository() -options = [make_option('-d', '--diff', - help = 'show the diff for the given files', - action = 'store_true'), - make_option('-b', '--branch', - help = 'use BRANCH instead of the default one')] +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) diff_tmpl = \ '-------------------------------------------------------------------------------\n' \ diff --git a/stgit/commands/pick.py b/stgit/commands/pick.py index add2a33..760918b 100644 --- a/stgit/commands/pick.py +++ b/stgit/commands/pick.py @@ -16,18 +16,17 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git +from stgit import argparse, stack, git from stgit.stack import Series - -help = 'import a patch from a different branch or a commit object' -usage = """%prog [options] ([] [] [..])| - +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 @@ -35,28 +34,28 @@ used as the name of the current patch. It can be overridden with the option. The log and author information are those of the commit object.""" -directory = DirectoryGotoToplevel() -options = [make_option('-n', '--name', - help = 'use NAME as the patch name'), - make_option('-B', '--ref-branch', - help = 'pick patches from BRANCH'), - make_option('-r', '--reverse', - help = 'reverse the commit object before importing', - action = 'store_true'), - make_option('-p', '--parent', metavar = 'COMMITID', - help = 'use COMMITID as parent'), - make_option('-x', '--expose', - help = 'append the imported commit id to the patch log', - action = 'store_true'), - make_option('--fold', - help = 'fold the commit object into the current patch', - action = 'store_true'), - make_option('--update', - help = 'like fold but only update the current patch files', - action = 'store_true'), - make_option('--unapplied', - help = 'keep the patch unapplied', - action = 'store_true')] +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', '--reverse', action = 'store_true', + short = 'Reverse the commit object before importing'), + 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('--unapplied', action = 'store_true', + short = 'Keep the patch unapplied')] + +directory = DirectoryGotoToplevel(log = True) def __pick_commit(commit_id, patchname, options): """Pick a commit id. @@ -83,12 +82,12 @@ def __pick_commit(commit_id, patchname, options): # try a direct git apply first if not git.apply_diff(bottom, top): - git.merge(bottom, git.get_head(), top, recursive = True) + git.merge_recursive(bottom, git.get_head(), top) out.done() elif options.update: - rev1 = git_id(crt_series, '//bottom') - rev2 = git_id(crt_series, '//top') + 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) @@ -115,10 +114,8 @@ def __pick_commit(commit_id, patchname, options): patchname = newpatch.get_name() # find a patchlog to fork from - (refpatchname, refbranchname, refpatchid) = parse_rev(patchname) - if refpatchname and not refpatchid and \ - (not refpatchid or refpatchid == 'top'): - # FIXME: should also support picking //top.old + refbranchname, refpatchname = parse_rev(patchname) + if refpatchname: if refbranchname: # assume the refseries is OK, since we already resolved # commit_str to a git_id diff --git a/stgit/commands/pop.py b/stgit/commands/pop.py index dedf41b..2c78ac2 100644 --- a/stgit/commands/pop.py +++ b/stgit/commands/pop.py @@ -17,35 +17,34 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * -from stgit import stack, git - - -help = 'pop one or more patches from the stack' -usage = """%prog [options] [] [] [..] +from stgit import argparse, stack, git +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 (push --undo would +the push operations may fail because of conflicts ("stg undo" would revert the last push operation).""" -directory = DirectoryGotoToplevel() -options = [make_option('-a', '--all', - help = 'pop all the applied patches', - action = 'store_true'), - make_option('-n', '--number', type = 'int', - help = 'pop the specified number of patches'), - make_option('-k', '--keep', - help = 'keep the local changes', - action = 'store_true')] +args = [argparse.patch_range(argparse.applied_patches)] +options = [ + opt('-a', '--all', action = 'store_true', + short = 'Pop all the applied patches'), + opt('-n', '--number', type = 'int', + short = 'Pop the specified number of patches'), + opt('-k', '--keep', action = 'store_true', + short = 'Keep the local changes')] +directory = DirectoryGotoToplevel(log = True) def func(parser, options, args): """Pop the topmost patch from the stack diff --git a/stgit/commands/pull.py b/stgit/commands/pull.py index bec7fd7..f6d1398 100644 --- a/stgit/commands/pull.py +++ b/stgit/commands/pull.py @@ -16,18 +16,17 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * from stgit.config import GitConfigException -from stgit import stack, git - - -help = 'pull the changes from the remote repository' -usage = """%prog [options] [] +from stgit import argparse, stack, git +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 @@ -38,13 +37,14 @@ resolved and the patch pushed again. Check the 'git fetch' documentation for the format.""" -directory = DirectoryGotoToplevel() -options = [make_option('-n', '--nopush', - help = 'do not push the patches back after pulling', - action = 'store_true'), - make_option('-m', '--merged', - help = 'check for patches merged upstream', - action = 'store_true')] +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) def func(parser, options, args): """Pull the changes from a remote repository diff --git a/stgit/commands/push.py b/stgit/commands/push.py index 979835b..818e02d 100644 --- a/stgit/commands/push.py +++ b/stgit/commands/push.py @@ -17,65 +17,44 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'push one or more patches onto of the stack' -usage = """%prog [options] [] [] [..] +from stgit import argparse, stack, git +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 the result of the 'push' -operation is not acceptable or if there are too many conflicts, the -'--undo' option can be used to revert the last pushed patch. Conflicts -raised during the push operation have to be fixed and the 'resolved' -command run. +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 'resolved' 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.""" -directory = DirectoryGotoToplevel() -options = [make_option('-a', '--all', - help = 'push all the unapplied patches', - action = 'store_true'), - make_option('-n', '--number', type = 'int', - help = 'push the specified number of patches'), - make_option('--reverse', - help = 'push the patches in reverse order', - action = 'store_true'), - make_option('-m', '--merged', - help = 'check for patches merged upstream', - action = 'store_true'), - make_option('--undo', - help = 'undo the last patch pushing', - action = 'store_true')] +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'), + opt('--reverse', action = 'store_true', + short = 'Push the patches in reverse order'), + opt('-m', '--merged', action = 'store_true', + short = 'Check for patches merged upstream')] +directory = DirectoryGotoToplevel(log = True) def func(parser, options, args): """Pushes the given patch or all onto the series """ - # If --undo is passed, do the work and exit - if options.undo: - patch = crt_series.get_current() - if not patch: - raise CmdException, 'No patch to undo' - - out.start('Undoing push of "%s"' % patch) - resolved_all() - if crt_series.undo_push(): - out.done() - else: - out.done('patch unchanged') - print_crt_patch(crt_series) - - return - check_local_changes() check_conflicts() check_head_top_equal(crt_series) diff --git a/stgit/commands/rebase.py b/stgit/commands/rebase.py index ec2e04c..a4bc6e7 100644 --- a/stgit/commands/rebase.py +++ b/stgit/commands/rebase.py @@ -16,16 +16,15 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * -from stgit import stack, git - - -help = 'move the stack base to another point in history' -usage = """%prog [options] +from stgit import argparse, stack, git +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. @@ -38,16 +37,17 @@ the rebase by executing the following sequence: Or if you want to skip that patch: - $ stg push --undo + $ stg undo --hard $ stg push next-patch..top-patch""" -directory = DirectoryGotoToplevel() -options = [make_option('-n', '--nopush', - help = 'do not push the patches back after rebasing', - action = 'store_true'), - make_option('-m', '--merged', - help = 'check for patches merged upstream', - action = 'store_true')] +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) def func(parser, options, args): """Rebase the current stack diff --git a/stgit/commands/redo.py b/stgit/commands/redo.py new file mode 100644 index 0000000..eb8b20f --- /dev/null +++ b/stgit/commands/redo.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +__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, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +""" + +from stgit.argparse import opt +from stgit.commands import common +from stgit.lib import log, transaction + +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) diff --git a/stgit/commands/refresh.py b/stgit/commands/refresh.py index 6e8ed0c..27cccc5 100644 --- a/stgit/commands/refresh.py +++ b/stgit/commands/refresh.py @@ -1,6 +1,8 @@ +# -*- coding: utf-8 -*- __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 @@ -16,110 +18,238 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit.out import * -from stgit import stack, git -from stgit.config import config - - -help = 'generate a new commit for the current patch' -usage = """%prog [options] [] - -Include the latest tree changes in the current patch. This command -generates a new GIT commit object with the patch details, the previous -one no longer being visible. The patch attributes like author, -committer and description can be changed with the command line -options. The '--force' option is useful when a commit object was -created with a different tool but the changes need to be included in -the current patch.""" - -directory = DirectoryHasRepository() -options = [make_option('-f', '--force', - help = 'force the refresh even if HEAD and '\ - 'top differ', - action = 'store_true'), - make_option('--update', - help = 'only update the current patch files', - action = 'store_true'), - make_option('--undo', - help = 'revert the commit generated by the last refresh', - action = 'store_true'), - make_option('-a', '--annotate', metavar = 'NOTE', - help = 'annotate the patch log entry'), - make_option('-p', '--patch', - help = 'refresh (applied) PATCH instead of the top one') - ] - -def func(parser, options, args): - """Generate a new commit for the current or given patch. - """ - args = git.ls_files(args) - directory.cd_to_topdir() - - autoresolved = config.get('stgit.autoresolved') - if autoresolved != 'yes': - check_conflicts() - - if options.patch: - if args or options.update: - raise CmdException, \ - 'Only full refresh is available with the --patch option' - patch = options.patch - if not crt_series.patch_applied(patch): - raise CmdException, 'Patches "%s" not applied' % patch +from stgit.argparse import opt +from stgit.commands import common +from stgit.lib import git, transaction, edit +from stgit.out import out +from stgit import argparse, utils + +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. + +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 +coalesce. + +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('-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'), + ] + (argparse.message_options(save_template = False) + + 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): + """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() + 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: - patch = crt_series.get_current() - if not patch: - raise CmdException, 'No patches applied' - - if not options.force: - check_head_top_equal(crt_series) - - if options.undo: - out.start('Undoing the refresh of "%s"' % patch) - crt_series.undo_refresh() - out.done() - return - - files = [path for (stat, path) in git.tree_status(files = args, verbose = True)] - - if files or not crt_series.head_top_equal(): - if options.patch: - applied = crt_series.get_applied() - between = applied[:applied.index(patch):-1] - pop_patches(crt_series, between, keep = True) - elif options.update: - rev1 = git_id(crt_series, '//bottom') - rev2 = git_id(crt_series, '//top') - patch_files = git.barefiles(rev1, rev2).split('\n') - files = [f for f in files if f in patch_files] - if not files: - out.info('No modified files for updating patch "%s"' % patch) - return - - out.start('Refreshing patch "%s"' % patch) - - if autoresolved == 'yes': - resolved_all() - crt_series.refresh_patch(files = files, - backup = True, notes = options.annotate) - - if crt_series.empty_patch(patch): - out.done('empty patch') - else: - out.done() - - if options.patch: - between.reverse() - push_patches(crt_series, between) - elif options.annotate: - # only annotate the top log entry as there is no need to - # refresh the patch and generate a full commit - crt_series.log_patch(crt_series.get_patch(patch), None, - notes = options.annotate) + 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: - out.info('Patch "%s" is already up to date' % patch) + # 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): + """Absorb the temp patch into the target patch.""" + trans = transaction.StackTransaction(stack, 'refresh') + 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') + + stack = directory.repository.current_stack + patch_name = get_patch(stack, options.patch) + paths = list_files(stack, patch_name, args, options.index, options.update) + + # 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') + + # 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): + cd, failed_diff = edit.auto_edit_patch( + stack.repository, cd, msg = options.message, 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 + return cd + return absorb(stack, patch_name, temp_name, edit_fun) diff --git a/stgit/commands/rename.py b/stgit/commands/rename.py index 1d7c43b..8a593ac 100644 --- a/stgit/commands/rename.py +++ b/stgit/commands/rename.py @@ -16,24 +16,26 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'rename a patch in the series' -usage = """%prog [options] [oldpatch] - -Rename into in a series. If is not given, the -top-most patch will be renamed. """ - -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one')] - +from stgit import argparse, stack, git + +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) def func(parser, options, args): """Rename a patch in the series diff --git a/stgit/commands/repair.py b/stgit/commands/repair.py index aa34792..37c4bab 100644 --- a/stgit/commands/repair.py +++ b/stgit/commands/repair.py @@ -18,8 +18,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * @@ -27,15 +26,17 @@ from stgit.run import * from stgit import stack, git help = 'Fix StGit metadata if branch was modified with git commands' -usage = """%prog [options] - +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 "git reset" or similar to undo the effect of the git - command(s). + 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 accomodate the modifications to the branch. Specifically, it will @@ -48,8 +49,8 @@ options: * 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 "git - reset" to get rid of the merge and run "stg repair" again. + 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. @@ -68,9 +69,11 @@ 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.""" -directory = DirectoryGotoToplevel() +args = [] options = [] +directory = DirectoryGotoToplevel(log = True) + class Commit(object): def __init__(self, id): self.id = id diff --git a/stgit/commands/reset.py b/stgit/commands/reset.py new file mode 100644 index 0000000..7dfd4a0 --- /dev/null +++ b/stgit/commands/reset.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- + +__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, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +""" + +from stgit.argparse import opt +from stgit.commands import common +from stgit.lib import git, log, transaction +from stgit.out import out +from stgit import argparse + +help = 'Reset the patch stack to an earlier state' +kind = 'stack' +usage = ['[options] []'] +description = """ +Reset the patch stack to an earlier state. 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 + if len(args) >= 1: + ref, patches = args[0], args[1:] + state = log.get_log_entry(stack.repository, ref, + stack.repository.rev_parse(ref)) + else: + raise common.CmdException('Wrong number of arguments') + trans = transaction.StackTransaction(stack, 'reset', + discard_changes = options.hard, + allow_bad_head = True) + try: + if patches: + log.reset_stack_partially(trans, stack.repository.default_iw, + state, patches) + else: + log.reset_stack(trans, stack.repository.default_iw, state) + except transaction.TransactionHalted: + pass + return trans.run(stack.repository.default_iw, allow_bad_head = not patches) diff --git a/stgit/commands/resolved.py b/stgit/commands/resolved.py index 011db91..2ce7ec3 100644 --- a/stgit/commands/resolved.py +++ b/stgit/commands/resolved.py @@ -17,32 +17,32 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * -from stgit import stack, git, basedir +from stgit import argparse, stack, git, basedir from stgit.config import config, file_extensions from stgit.gitmergeonefile import interactive_merge - -help = 'mark a file conflict as solved' -usage = """%prog [options] [] - +help = 'Mark a file conflict as solved' +kind = 'wc' +usage = ['[options] []'] +description = """ Mark a merge conflict as resolved. The conflicts can be seen with the 'status' command, the corresponding files being prefixed with a -'C'. This command also removes any .{ancestor,current,patched} -files.""" - -directory = DirectoryHasRepository(needs_current_series = False) -options = [make_option('-a', '--all', - help = 'mark all conflicts as solved', - action = 'store_true'), - make_option('-r', '--reset', metavar = '(ancestor|current|patched)', - help = 'reset the file(s) to the given state'), - make_option('-i', '--interactive', - help = 'run the interactive merging tool', - action = 'store_true')] +'C'.""" + +args = [argparse.conflicting_files] +options = [ + opt('-a', '--all', action = 'store_true', + short = 'Mark all conflicts as solved'), + opt('-r', '--reset', metavar = '(ancestor|current|patched)', + args = [argparse.strings('ancestor', 'current', 'patched')], + short = 'Reset the file(s) to the given state'), + opt('-i', '--interactive', action = 'store_true', + short = 'Run the interactive merging tool')] + +directory = DirectoryHasRepository(needs_current_series = False, log = False) def func(parser, options, args): """Mark the conflict as resolved @@ -77,18 +77,9 @@ def func(parser, options, args): raise CmdException, 'No conflicts for "%s"' % filename # resolved - try: + if options.interactive: for filename in files: - if options.interactive: - interactive_merge(filename) - resolved(filename, options.reset) - del conflicts[conflicts.index(filename)] - finally: - # save or remove the conflicts file. Needs a finally clause to - # ensure that already solved conflicts are marked - if conflicts == []: - os.remove(os.path.join(basedir.get(), 'conflicts')) - else: - f = file(os.path.join(basedir.get(), 'conflicts'), 'w+') - f.writelines([line + '\n' for line in conflicts]) - f.close() + interactive_merge(filename) + git.resolved([filename]) + else: + git.resolved(files, options.reset) diff --git a/stgit/commands/rm.py b/stgit/commands/rm.py deleted file mode 100644 index 59d098b..0000000 --- a/stgit/commands/rm.py +++ /dev/null @@ -1,48 +0,0 @@ - -__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, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -""" - -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit import stack, git - - -help = 'remove files from the repository' -usage = """%prog [options] - -Remove given files from the repository. The command doesn't remove the -working copy of the file.""" - -directory = DirectoryHasRepository() -options = [make_option('-f', '--force', - help = 'force removing even if the file exists', - action = 'store_true')] - - -def func(parser, options, args): - """Remove files from the repository - """ - if len(args) < 1: - parser.error('incorrect number of arguments') - - if not crt_series.get_current(): - raise CmdException, 'No patches applied' - - git.rm(args, options.force) diff --git a/stgit/commands/series.py b/stgit/commands/series.py index e3467cc..95196d3 100644 --- a/stgit/commands/series.py +++ b/stgit/commands/series.py @@ -16,140 +16,124 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -import stgit.commands.common -from stgit.commands.common import * -from stgit.utils import * -from stgit.out import * -from stgit import stack, git - - -help = 'print the patch series' -usage = """%prog [options] [] - +from stgit.argparse import opt +from stgit.commands import common +from stgit.commands.common import parse_patches +from stgit.out import out +from stgit.config import config +from stgit import argparse + +help = 'Print the patch series' +kind = 'stack' +usage = ['[options] []'] +description = """ Show all the patches in the series or just those in the given range. The applied patches are prefixed with a '+', the unapplied ones with a '-' and the hidden ones with a '!'. The current patch is prefixed with a '>'. Empty patches are prefixed with a '0'.""" -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one'), - make_option('-a', '--all', - help = 'show all patches, including the hidden ones', - action = 'store_true'), - make_option('-i', '--invisible', - help = 'show the hidden patches only', - action = 'store_true'), - make_option('-m', '--missing', metavar = 'BRANCH', - help = 'show patches in BRANCH missing in current'), - make_option('-c', '--count', - help = 'print the number of patches in the series', - action = 'store_true'), - make_option('-d', '--description', - help = 'show a short description for each patch', - action = 'store_true'), - make_option('--author', - help = 'show the author name for each patch', - action = 'store_true'), - make_option('-e', '--empty', - help = 'check whether patches are empty ' - '(much slower)', - action = 'store_true'), - make_option('--showbranch', - help = 'append the branch name to the listed patches', - action = 'store_true'), - make_option('--noprefix', - help = 'do not show the patch status prefix', - action = 'store_true'), - make_option('-s', '--short', - help = 'list just the patches around the topmost patch', - action = 'store_true'), - make_option('-g', '--graphical', - help = 'run gitk instead of printing', - action = 'store_true')] - - -def __get_description(patch): +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'), + 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 """ - p = crt_series.get_patch(patch) - descr = (p.get_description() or '').strip() + cd = stack.patches.get(patch).commit.data + descr = cd.message.strip() descr_lines = descr.split('\n') return descr_lines[0].rstrip() -def __get_author(patch): +def __get_author(stack, patch): """Extract and return a patch's short description """ - p = crt_series.get_patch(patch) - return p.get_authname(); + cd = stack.patches.get(patch).commit.data + return cd.author.name -def __print_patch(patch, branch_str, prefix, empty_prefix, length, options): +def __print_patch(stack, patch, branch_str, prefix, empty_prefix, length, options): """Print a patch name, description and various markers. """ if options.noprefix: prefix = '' - elif options.empty and crt_series.empty_patch(patch): + elif options.empty and stack.patches.get(patch).is_empty(): prefix = empty_prefix - patch_str = patch + branch_str + patch_str = branch_str + patch if options.description or options.author: patch_str = patch_str.ljust(length) if options.description: - out.stdout(prefix + patch_str + ' # ' + __get_description(patch)) + out.stdout(prefix + patch_str + ' # ' + __get_description(stack, patch)) elif options.author: - out.stdout(prefix + patch_str + ' # ' + __get_author(patch)) + out.stdout(prefix + patch_str + ' # ' + __get_author(stack, patch)) else: out.stdout(prefix + patch_str) def func(parser, options, args): """Show the patch series """ - global crt_series - if options.all and options.short: - raise CmdException, 'combining --all and --short is meaningless' - + 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 - if options.invisible: - applied = unapplied = [] - hidden = crt_series.get_hidden() + 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 = crt_series.get_applied() - unapplied = crt_series.get_unapplied() - hidden = crt_series.get_hidden() + applied = stack.patchorder.applied + unapplied = stack.patchorder.unapplied + hidden = stack.patchorder.hidden else: - applied = crt_series.get_applied() - unapplied = crt_series.get_unapplied() - hidden = [] + applied = stack.patchorder.applied + unapplied = stack.patchorder.unapplied if options.missing: - # switch the series, the one specified with --missing should - # become the current - cmp_series = crt_series - crt_series = stack.Series(options.missing) - stgit.commands.common.crt_series = crt_series - - cmp_patches = applied + unapplied + hidden - - # new current series patches - if options.invisible: - applied = unapplied = [] - hidden = crt_series.get_hidden() - elif options.all: - applied = crt_series.get_applied() - unapplied = crt_series.get_unapplied() - hidden = crt_series.get_hidden() - else: - applied = crt_series.get_applied() - unapplied = crt_series.get_unapplied() - hidden = [] + cmp_patches = cmp_stack.patchorder.all else: - cmp_patches = [] + cmp_patches = () # the filtering range covers the whole series if args: @@ -186,38 +170,22 @@ def func(parser, options, args): return if options.showbranch: - branch_str = '@' + crt_series.get_name() + branch_str = stack.name + ':' else: branch_str = '' - if options.graphical: - if options.missing: - raise CmdException, '--graphical not supported with --missing' - - gitk_args = [] - if applied: - gitk_args.append('%s^..%s' - % (git_id(crt_series, applied[0]), - git_id(crt_series, applied[-1]))) - for p in unapplied: - patch_id = git_id(crt_series, p) - gitk_args.append('%s^..%s' % (patch_id, patch_id)) - - # discard the exit codes generated by SIGINT, SIGKILL, SIGTERM - Run('gitk', *gitk_args).returns([0, -2, -9, -15]).run() - else: - max_len = 0 - if len(patches) > 0: - max_len = max([len(i + branch_str) for i in patches]) + 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(p, branch_str, '+ ', '0 ', max_len, options) - __print_patch(applied[-1], branch_str, '> ', '0>', max_len, - options) + if applied: + for p in applied[:-1]: + __print_patch(stack, p, branch_str, '+ ', '0 ', max_len, options) + __print_patch(stack, applied[-1], branch_str, '> ', '0>', max_len, + options) - for p in unapplied: - __print_patch(p, branch_str, '- ', '0 ', max_len, options) + for p in unapplied: + __print_patch(stack, p, branch_str, '- ', '0 ', max_len, options) - for p in hidden: - __print_patch(p, branch_str, '! ', '! ', max_len, options) + for p in hidden: + __print_patch(stack, p, branch_str, '! ', '! ', max_len, options) diff --git a/stgit/commands/show.py b/stgit/commands/show.py index 72d1be3..9a1f48b 100644 --- a/stgit/commands/show.py +++ b/stgit/commands/show.py @@ -16,32 +16,31 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option from pydoc import pager - +from stgit.argparse import opt from stgit.commands.common import * -from stgit import git - - -help = 'show the commit corresponding to a patch (or the current patch)' -usage = """%prog [options] [] [] [..] +from stgit import argparse, git -Show the commit log and the diff corresponding to the given -patches. The output is similar to that generated by the 'git show' -command.""" +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'.""" -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one'), - make_option('-a', '--applied', - help = 'show the applied patches', - action = 'store_true'), - make_option('-u', '--unapplied', - help = 'show the unapplied patches', - action = 'store_true'), - make_option('-O', '--show-opts', - help = 'options to pass to "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'), + ] + argparse.diff_opts_option() +directory = DirectoryHasRepository(log = False) def func(parser, options, args): """Show commit log and diff @@ -62,13 +61,9 @@ def func(parser, options, args): patches = parse_patches(args, applied + unapplied + \ crt_series.get_hidden(), len(applied)) - if options.show_opts: - show_flags = options.show_opts.split() - else: - show_flags = [] - commit_ids = [git_id(crt_series, patch) for patch in patches] - commit_str = '\n'.join([git.pretty_commit(commit_id, flags = show_flags) + commit_str = '\n'.join([git.pretty_commit(commit_id, + flags = options.diff_flags) for commit_id in commit_ids]) if commit_str: pager(commit_str) diff --git a/stgit/commands/sink.py b/stgit/commands/sink.py index 7e5c955..d4561ed 100644 --- a/stgit/commands/sink.py +++ b/stgit/commands/sink.py @@ -17,27 +17,43 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * -from stgit import stack, git - - -help = 'send patches deeper down the stack' -usage = """%prog [-t ] [-n] [] - -Pop all patches (or all patches including ), then -push the specified (the current patch by default), and -then push back into place the formerly-applied patches (unless -n -is also given).""" - -directory = DirectoryGotoToplevel() -options = [make_option('-n', '--nopush', - help = 'do not push the patches back after sinking', - action = 'store_true'), - make_option('-t', '--to', metavar = 'TARGET', - help = 'sink patches below TARGET patch')] +from stgit import argparse, stack, git + +help = 'Send patches deeper down the stack' +kind = 'stack' +usage = ['[-t ] [-n] []'] +description = """ +This is the opposite operation of stglink: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 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.""")] + +directory = DirectoryGotoToplevel(log = True) def func(parser, options, args): """Sink patches down the stack. diff --git a/stgit/commands/status.py b/stgit/commands/status.py index 94d0b57..730b47c 100644 --- a/stgit/commands/status.py +++ b/stgit/commands/status.py @@ -17,16 +17,15 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * -from stgit import stack, git - - -help = 'show the tree status' -usage = """%prog [options] [] +from stgit import argparse, stack, git +help = 'Show the tree status' +kind = 'wc' +usage = ['[options] []'] +description = """ Show the status of the whole working copy or the given files. The command also shows the files in the current directory which are not under revision control. The files are prefixed as follows: @@ -37,35 +36,29 @@ under revision control. The files are prefixed as follows: C - conflict ? - unknown -A 'refresh' command clears the status of the modified, new and deleted -files.""" - -directory = DirectoryHasRepository(needs_current_series = False) -options = [make_option('-m', '--modified', - help = 'show modified files only', - action = 'store_true'), - make_option('-n', '--new', - help = 'show new files only', - action = 'store_true'), - make_option('-d', '--deleted', - help = 'show deleted files only', - action = 'store_true'), - make_option('-c', '--conflict', - help = 'show conflict files only', - action = 'store_true'), - make_option('-u', '--unknown', - help = 'show unknown files only', - action = 'store_true'), - make_option('-x', '--noexclude', - help = 'do not exclude any files from listing', - action = 'store_true'), - make_option('--reset', - help = 'reset the current tree changes', - action = 'store_true')] - - -def status(files = None, modified = False, new = False, deleted = False, - conflict = False, unknown = False, noexclude = False): +An 'stg refresh' command clears the status of the modified, new and +deleted files.""" + +args = [argparse.files] +options = [ + opt('-m', '--modified', action = 'store_true', + short = 'Show modified files only'), + opt('-n', '--new', action = 'store_true', + short = 'Show new files only'), + opt('-d', '--deleted', action = 'store_true', + short = 'Show deleted files only'), + opt('-c', '--conflict', action = 'store_true', + short = 'Show conflict files only'), + opt('-u', '--unknown', action = 'store_true', + short = 'Show unknown files only'), + opt('-x', '--noexclude', action = 'store_true', + short = 'Do not exclude any files from listing'), + opt('--reset', action = 'store_true', + short = 'Reset the current tree changes')] + +directory = DirectoryHasRepository(needs_current_series = False, log = False) + +def status(files, modified, new, deleted, conflict, unknown, noexclude): """Show the tree status """ cache_files = git.tree_status(files, @@ -104,9 +97,10 @@ def func(parser, options, args): directory.cd_to_topdir() if options.reset: + directory.log = True if args: - for f in args: - resolved(f) + conflicts = git.get_conflicts() + git.resolved([fn for fn in args if fn in conflicts]) git.reset(args) else: resolved_all() diff --git a/stgit/commands/sync.py b/stgit/commands/sync.py index a04ff82..ea949d6 100644 --- a/stgit/commands/sync.py +++ b/stgit/commands/sync.py @@ -16,37 +16,34 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - import stgit.commands.common +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'synchronise patches with a branch or a series' -usage = """%prog [options] [] [] [..] +from stgit import argparse, stack, git +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. - -The sync operation can be reverted for individual patches with --undo.""" - -directory = DirectoryGotoToplevel() -options = [make_option('-a', '--all', - help = 'synchronise all the applied patches', - action = 'store_true'), - make_option('-B', '--ref-branch', - help = 'syncronise patches with BRANCH'), - make_option('-s', '--series', - help = 'syncronise patches with SERIES'), - make_option('--undo', - help = 'undo the synchronisation of the current patch', - action = 'store_true')] +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) def __check_all(): check_local_changes() @@ -57,7 +54,7 @@ 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(patch.get_bottom(), git.get_head(), patch.get_top()) + 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. @@ -68,18 +65,6 @@ def __series_merge_patch(base, patchdir, pname): def func(parser, options, args): """Synchronise a range of patches """ - if options.undo: - if options.ref_branch or options.series: - raise CmdException, \ - '--undo cannot be specified with --ref-branch or --series' - __check_all() - - out.start('Undoing the sync of "%s"' % crt_series.get_current()) - crt_series.undo_refresh() - git.reset() - out.done() - return - if options.ref_branch: remote_series = stack.Series(options.ref_branch) if options.ref_branch == crt_series.get_name(): @@ -157,9 +142,7 @@ def func(parser, options, args): bottom = patch.get_bottom() top = patch.get_top() - # reset the patch backup information. That's needed in case we - # undo the sync but there were no changes made - patch.set_bottom(bottom, backup = True) + # reset the patch backup information. patch.set_top(top, backup = True) # the actual merging (either from a branch or an external file) diff --git a/stgit/commands/top.py b/stgit/commands/top.py index e7cb275..4ec37b4 100644 --- a/stgit/commands/top.py +++ b/stgit/commands/top.py @@ -16,24 +16,23 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit.out import * -from stgit import stack, git - - -help = 'print the name of the top patch' -usage = """%prog [options] - +from stgit.argparse import opt +from stgit.commands import common +from stgit.out import out +from stgit import argparse + +help = 'Print the name of the top patch' +kind = 'stack' +usage = [''] +description = """ Print the name of the current (topmost) patch.""" -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one')] +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 @@ -41,8 +40,10 @@ def func(parser, options, args): if len(args) != 0: parser.error('incorrect number of arguments') - name = crt_series.get_current() - if name: - out.stdout(name) + stack = directory.repository.get_stack(options.branch) + applied = stack.patchorder.applied + + if applied: + out.stdout(applied[-1]) else: - raise CmdException, 'No patches applied' + raise common.CmdException, 'No patches applied' diff --git a/stgit/commands/unapplied.py b/stgit/commands/unapplied.py deleted file mode 100644 index d5bb43e..0000000 --- a/stgit/commands/unapplied.py +++ /dev/null @@ -1,54 +0,0 @@ - -__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, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -""" - -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * -from stgit.out import * -from stgit import stack, git - - -help = 'print the unapplied patches' -usage = """%prog [options] - -List the patches from the series which are not pushed onto the stack. -They are listed in the reverse order in which they were popped.""" - -directory = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one'), - make_option('-c', '--count', - help = 'print the number of unapplied patches', - action = 'store_true')] - - -def func(parser, options, args): - """Show the unapplied patches - """ - if len(args) != 0: - parser.error('incorrect number of arguments') - - unapplied = crt_series.get_unapplied() - - if options.count: - out.stdout(len(unapplied)) - else: - for p in unapplied: - out.stdout(p) diff --git a/stgit/commands/uncommit.py b/stgit/commands/uncommit.py index ba3448f..bcc8bac 100644 --- a/stgit/commands/uncommit.py +++ b/stgit/commands/uncommit.py @@ -17,20 +17,21 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser, make_option - -from stgit.commands.common import * -from stgit.utils import * +from stgit.argparse import opt +from stgit.commands import common +from stgit.lib import transaction from stgit.out import * -from stgit import stack, git - -help = 'turn regular GIT commits into StGIT patches' -usage = """%prog [] | -n NUM []] | -t [-x] - +from stgit import argparse, utils + +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 exact opposite of 'stg commit'. +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 @@ -48,31 +49,32 @@ given commit should be uncommitted. Only commits with exactly one parent can be uncommitted; in other words, you can't uncommit a merge.""" -directory = DirectoryGotoToplevel() -options = [make_option('-n', '--number', type = 'int', - help = 'uncommit the specified number of commits'), - make_option('-t', '--to', - help = 'uncommit to the specified commit'), - make_option('-x', '--exclusive', - help = 'exclude the commit specified by the --to option', - action = 'store_true')] +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 = git_id(crt_series, options.to) + to_commit = stack.repository.rev_parse(options.to) 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: @@ -88,53 +90,57 @@ def func(parser, options, args): patchnames = args patch_nr = len(patchnames) - if crt_series.get_protected(): - raise CmdException, \ - 'This branch is protected. Uncommit is not permitted' - - def get_commit(commit_id): - commit = git.Commit(commit_id) + def get_parent(c): + next = c.data.parents try: - parent, = commit.get_parents() + [next] = next except ValueError: - raise CmdException('Commit %s does not have exactly one parent' - % commit_id) - return (commit, commit_id, parent) + raise common.CmdException( + 'Trying to uncommit %s, which does not have exactly one parent' + % c.sha1) + return next commits = [] - next_commit = crt_series.get_base() + next_commit = stack.base if patch_nr: out.start('Uncommitting %d patches' % patch_nr) for i in xrange(patch_nr): - commit, commit_id, parent = get_commit(next_commit) - commits.append((commit, commit_id, parent)) - next_commit = parent + commits.append(next_commit) + next_commit = get_parent(next_commit) else: if options.exclusive: - out.start('Uncommitting to %s (exclusive)' % to_commit) + out.start('Uncommitting to %s (exclusive)' % to_commit.sha1) else: - out.start('Uncommitting to %s' % to_commit) + out.start('Uncommitting to %s' % to_commit.sha1) while True: - commit, commit_id, parent = get_commit(next_commit) - if commit_id == to_commit: + if next_commit == to_commit: if not options.exclusive: - commits.append((commit, commit_id, parent)) + commits.append(next_commit) break - commits.append((commit, commit_id, parent)) - next_commit = parent + commits.append(next_commit) + next_commit = get_parent(next_commit) patch_nr = len(commits) - for (commit, commit_id, parent), patchname in \ - zip(commits, patchnames or [None for i in xrange(len(commits))]): - author_name, author_email, author_date = \ - name_email_date(commit.get_author()) - crt_series.new_patch(patchname, - can_edit = False, before_existing = True, - commit = False, - top = commit_id, bottom = parent, - message = commit.get_log(), - author_name = author_name, - author_email = author_email, - author_date = author_date) - + 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() diff --git a/stgit/commands/undo.py b/stgit/commands/undo.py new file mode 100644 index 0000000..6a04363 --- /dev/null +++ b/stgit/commands/undo.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +__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, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +""" + +from stgit.argparse import opt +from stgit.commands import common +from stgit.lib import git, log, transaction +from stgit.out import out + +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) diff --git a/stgit/commands/unhide.py b/stgit/commands/unhide.py index 665d664..0c0832a 100644 --- a/stgit/commands/unhide.py +++ b/stgit/commands/unhide.py @@ -16,23 +16,25 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ import sys, os -from optparse import OptionParser, make_option - +from stgit.argparse import opt from stgit.commands.common import * from stgit.utils import * from stgit.out import * -from stgit import stack, git - - -help = 'unhide a hidden patch in the series' -usage = """%prog [options] +from stgit import argparse, stack, git +help = 'Unhide a hidden patch' +kind = 'stack' +usage = ['[options] '] +description = """ Unhide a hidden range of patches so that they are shown in the plain -'series' command output.""" +'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 = DirectoryHasRepository() -options = [make_option('-b', '--branch', - help = 'use BRANCH instead of the default one')] +directory = DirectoryHasRepository(log = True) def func(parser, options, args): """Unhide a range of patches in the series diff --git a/stgit/completion.py b/stgit/completion.py new file mode 100644 index 0000000..e461e3b --- /dev/null +++ b/stgit/completion.py @@ -0,0 +1,140 @@ +import textwrap +import stgit.commands +from stgit import argparse + +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, str): + 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 *)'), + 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.iterkeys()))] + +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( + 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 "$_stg_commands" --' + ' "${COMP_WORDS[COMP_CWORD]}"))'), + 'return'], + 'fi', + '', + '# Complete arguments to subcommands.', + 'case "$command" in', [ + '%s) _stg_%s ;;' % (cmd, cmd) + for cmd in sorted(commands.iterkeys())], + 'esac') + +def install(): + return ['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.iteritems()): + r.append(command_fun(cmd, modname)) + r += [main_switch(commands), install()] + write(f, flatten(r, '')) diff --git a/stgit/config.py b/stgit/config.py index 8934445..9bfdd52 100644 --- a/stgit/config.py +++ b/stgit/config.py @@ -34,8 +34,6 @@ class GitConfig: 'stgit.pullcmd': 'git pull', 'stgit.fetchcmd': 'git fetch', 'stgit.pull-policy': 'pull', - 'stgit.merger': 'diff3 -L current -L ancestor -L patched -m -E ' \ - '"%(branch1)s" "%(ancestor)s" "%(branch2)s" > "%(output)s"', 'stgit.autoimerge': 'no', 'stgit.keeporig': 'yes', 'stgit.keepoptimized': 'no', diff --git a/stgit/git.py b/stgit/git.py index 35579d4..4d01fc2 100644 --- a/stgit/git.py +++ b/stgit/git.py @@ -43,7 +43,6 @@ class GRun(Run): """ Run.__init__(self, 'git', *cmd) - # # Classes # @@ -154,14 +153,12 @@ def get_commit(id_hash): def get_conflicts(): """Return the list of file conflicts """ - conflicts_file = os.path.join(basedir.get(), 'conflicts') - if os.path.isfile(conflicts_file): - f = file(conflicts_file) - names = [line.strip() for line in f.readlines()] - f.close() - return names - else: - return None + names = set() + for line in GRun('ls-files', '-z', '--unmerged' + ).raw_output().split('\0')[:-1]: + stat, path = line.split('\t', 1) + names.add(path) + return list(names) def exclude_files(): files = [os.path.join(basedir.get(), 'info', 'exclude')] @@ -185,11 +182,13 @@ def ls_files(files, tree = 'HEAD', full_name = True): args.append('--') args.extend(files) try: - return GRun('ls-files', '--error-unmatch', *args).output_lines() + # 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(output): """Parse the output of git diff-index, diff-files, etc. Doesn't handle @@ -244,8 +243,6 @@ def tree_status(files = None, tree_id = 'HEAD', unknown = False, # conflicted files conflicts = get_conflicts() - if not conflicts: - conflicts = [] cache_files += [('C', filename) for filename in conflicts if not files or filename in files] reported_files = set(conflicts) @@ -475,109 +472,6 @@ def rename_branch(from_name, to_name): and os.path.exists(os.path.join(reflog_dir, from_name)): rename(reflog_dir, from_name, to_name) -def add(names): - """Add the files or recursively add the directory contents - """ - # generate the file list - files = [] - for i in names: - if not os.path.exists(i): - raise GitException, 'Unknown file or directory: %s' % i - - if os.path.isdir(i): - # recursive search. We only add files - for root, dirs, local_files in os.walk(i): - for name in [os.path.join(root, f) for f in local_files]: - if os.path.isfile(name): - files.append(os.path.normpath(name)) - elif os.path.isfile(i): - files.append(os.path.normpath(i)) - else: - raise GitException, '%s is not a file or directory' % i - - if files: - try: - GRun('update-index', '--add', '--').xargs(files) - except GitRunException: - raise GitException, 'Unable to add file' - -def __copy_single(source, target, target2=''): - """Copy file or dir named 'source' to name target+target2""" - - # "source" (file or dir) must match one or more git-controlled file - realfiles = GRun('ls-files', source).output_lines() - if len(realfiles) == 0: - raise GitException, '"%s" matches no git-controled files' % source - - if os.path.isdir(source): - # physically copy the files, and record them to add them in one run - newfiles = [] - re_string='^'+source+'/(.*)$' - prefix_regexp = re.compile(re_string) - for f in [f.strip() for f in realfiles]: - m = prefix_regexp.match(f) - if not m: - raise Exception, '"%s" does not match "%s"' % (f, re_string) - newname = target+target2+'/'+m.group(1) - if not os.path.exists(os.path.dirname(newname)): - os.makedirs(os.path.dirname(newname)) - copyfile(f, newname) - newfiles.append(newname) - - add(newfiles) - else: # files, symlinks, ... - newname = target+target2 - copyfile(source, newname) - add([newname]) - - -def copy(filespecs, target): - if os.path.isdir(target): - # target is a directory: copy each entry on the command line, - # with the same name, into the target - target = target.rstrip('/') - - # first, check that none of the children of the target - # matching the command line aleady exist - for filespec in filespecs: - entry = target+ '/' + os.path.basename(filespec.rstrip('/')) - if os.path.exists(entry): - raise GitException, 'Target "%s" already exists' % entry - - for filespec in filespecs: - filespec = filespec.rstrip('/') - basename = '/' + os.path.basename(filespec) - __copy_single(filespec, target, basename) - - elif os.path.exists(target): - raise GitException, 'Target "%s" exists but is not a directory' % target - elif len(filespecs) != 1: - raise GitException, 'Cannot copy more than one file to non-directory' - - else: - # at this point: len(filespecs)==1 and target does not exist - - # check target directory - targetdir = os.path.dirname(target) - if targetdir != '' and not os.path.isdir(targetdir): - raise GitException, 'Target directory "%s" does not exist' % targetdir - - __copy_single(filespecs[0].rstrip('/'), target) - - -def rm(files, force = False): - """Remove a file from the repository - """ - if not force: - for f in files: - if os.path.exists(f): - raise GitException, '%s exists. Remove it first' %f - if files: - GRun('update-index', '--remove', '--').xargs(files) - else: - if files: - GRun('update-index', '--force-remove', '--').xargs(files) - # Persons caching __user = None __author = None @@ -724,77 +618,33 @@ def apply_diff(rev1, rev2, check_index = True, files = None): return True -def merge(base, head1, head2, recursive = False): +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() - - err_output = None - if recursive: - # this operation tracks renames but it is slower (used in - # general when pushing or picking patches) - try: - # discard output to mask the verbose prints of the tool - GRun('merge-recursive', base, '--', head1, head2 - ).discard_output() - except GitRunException, ex: - err_output = str(ex) - pass - else: - # the fast case where we don't track renames (used when the - # distance between base and heads is small, i.e. folding or - # synchronising patches) - try: - GRun('read-tree', '-u', '-m', '--aggressive', - base, head1, head2).run() - except GitRunException: - raise GitException, 'read-tree failed (local changes maybe?)' - - # check the index for unmerged entries - files = {} - stages_re = re.compile('^([0-7]+) ([0-9a-f]{40}) ([1-3])\t(.*)$', re.S) - - for line in GRun('ls-files', '--unmerged', '--stage', '-z' - ).raw_output().split('\0'): - if not line: - continue - - mode, hash, stage, path = stages_re.findall(line)[0] - - if not path in files: - files[path] = {} - files[path]['1'] = ('', '') - files[path]['2'] = ('', '') - files[path]['3'] = ('', '') - - files[path][stage] = (mode, hash) - - if err_output and not files: - # if no unmerged files, there was probably a different type of - # error and we have to abort the merge - raise GitException, err_output - - # merge the unmerged files - errors = False - for path in files: - # remove additional files that might be generated for some - # newer versions of GIT - for suffix in [base, head1, head2]: - if not suffix: - continue - fname = path + '~' + suffix - if os.path.exists(fname): - os.remove(fname) - - stages = files[path] - if gitmergeonefile.merge(stages['1'][1], stages['2'][1], - stages['3'][1], path, stages['1'][0], - stages['2'][0], stages['3'][0]) != 0: - errors = True - - if errors: - raise GitException, 'GIT index merging failed (possible conflicts)' + 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 + conflicts = [l.strip() for l in output if l.startswith('CONFLICT')] + out.info(*conflicts) + + # try the interactive merge or stage checkout (if enabled) + for filename in get_conflicts(): + if (gitmergeonefile.merge(filename)): + # interactive merge succeeded + resolved([filename]) + + # any conflicts left unsolved? + cn = len(get_conflicts()) + if cn: + raise GitException, "%d conflict(s)" % cn def diff(files = None, rev1 = 'HEAD', rev2 = None, diff_flags = [], binary = True): @@ -819,13 +669,6 @@ def diff(files = None, rev1 = 'HEAD', rev2 = None, diff_flags = [], else: return '' -# TODO: take another parameter representing a diff string as we -# usually invoke git.diff() form the calling functions -def diffstat(files = None, rev1 = 'HEAD', rev2 = None): - """Return the diffstat between rev1 and rev2.""" - return GRun('apply', '--stat', '--summary' - ).raw_input(diff(files, rev1, rev2)).raw_output() - def files(rev1, rev2, diff_flags = []): """Return the files modified between rev1 and rev2 """ @@ -904,6 +747,17 @@ def reset(files = None, tree_id = None, check_out = True): if not files: __set_head(tree_id) +def resolved(filenames, reset = None): + if reset: + stage = {'ancestor': 1, 'current': 2, 'patched': 3}[reset] + GRun('checkout-index', '--no-create', '--stage=%d' % stage, + '--stdin', '-z').input_nulterm(filenames).no_output() + GRun('update-index', '--add', '--').xargs(filenames) + for filename in filenames: + gitmergeonefile.clean_up(filename) + # update the access and modificatied times + os.utime(filename, None) + def fetch(repository = 'origin', refspec = None): """Fetches changes from the remote repository, using 'git fetch' by default. @@ -998,7 +852,7 @@ def apply_patch(filename = None, diff = None, base = None, top = commit(message = 'temporary commit used for applying a patch', parents = [base]) switch(orig_head) - merge(base, orig_head, top) + merge_recursive(base, orig_head, top) def clone(repository, local_dir): """Clone a remote repository. At the moment, just use the diff --git a/stgit/gitmergeonefile.py b/stgit/gitmergeonefile.py index 55b62db..1fe226e 100644 --- a/stgit/gitmergeonefile.py +++ b/stgit/gitmergeonefile.py @@ -33,7 +33,7 @@ class GitMergeException(StgException): # # Options # -merger = ConfigOption('stgit', 'merger') +autoimerge = ConfigOption('stgit', 'autoimerge') keeporig = ConfigOption('stgit', 'keeporig') # @@ -48,274 +48,103 @@ def __str2none(x): class MRun(Run): exc = GitMergeException # use a custom exception class on errors -def __checkout_files(orig_hash, file1_hash, file2_hash, - path, - orig_mode, file1_mode, file2_mode): - """Check out the files passed as arguments +def __checkout_stages(filename): + """Check-out the merge stages in the index for the give file """ - global orig, src1, src2 - extensions = file_extensions() + line = MRun('git', 'checkout-index', '--stage=all', '--', filename + ).output_one_line() + stages, path = line.split('\t') + stages = dict(zip(['ancestor', 'current', 'patched'], + stages.split(' '))) + + for stage, fn in stages.iteritems(): + if stages[stage] == '.': + stages[stage] = None + else: + newname = filename + extensions[stage] + if os.path.exists(newname): + # remove the stage if it is already checked out + os.remove(newname) + os.rename(stages[stage], newname) + stages[stage] = newname - if orig_hash: - orig = path + extensions['ancestor'] - tmp = MRun('git', 'unpack-file', orig_hash).output_one_line() - os.chmod(tmp, int(orig_mode, 8)) - os.renames(tmp, orig) - if file1_hash: - src1 = path + extensions['current'] - tmp = MRun('git', 'unpack-file', file1_hash).output_one_line() - os.chmod(tmp, int(file1_mode, 8)) - os.renames(tmp, src1) - if file2_hash: - src2 = path + extensions['patched'] - tmp = MRun('git', 'unpack-file', file2_hash).output_one_line() - os.chmod(tmp, int(file2_mode, 8)) - os.renames(tmp, src2) - - if file1_hash and not os.path.exists(path): - # the current file might be removed by GIT when it is a new - # file added in both branches. Just re-generate it - tmp = MRun('git', 'unpack-file', file1_hash).output_one_line() - os.chmod(tmp, int(file1_mode, 8)) - os.renames(tmp, path) - -def __remove_files(orig_hash, file1_hash, file2_hash): - """Remove any temporary files - """ - if orig_hash: - os.remove(orig) - if file1_hash: - os.remove(src1) - if file2_hash: - os.remove(src2) - -def __conflict(path): - """Write the conflict file for the 'path' variable and exit - """ - append_string(os.path.join(basedir.get(), 'conflicts'), path) - + return stages -def interactive_merge(filename): - """Run the interactive merger on the given file. Note that the - index should not have any conflicts. +def __remove_stages(filename): + """Remove the merge stages from the working directory """ extensions = file_extensions() + for ext in extensions.itervalues(): + fn = filename + ext + if os.path.isfile(fn): + os.remove(fn) - ancestor = filename + extensions['ancestor'] - current = filename + extensions['current'] - patched = filename + extensions['patched'] - - if os.path.isfile(ancestor): - three_way = True - files_dict = {'branch1': current, - 'ancestor': ancestor, - 'branch2': patched, - 'output': filename} - imerger = config.get('stgit.i3merge') - else: - three_way = False - files_dict = {'branch1': current, - 'branch2': patched, - 'output': filename} - imerger = config.get('stgit.i2merge') - - if not imerger: - raise GitMergeException, 'No interactive merge command configured' - - # check whether we have all the files for the merge - for fn in [filename, current, patched]: - if not os.path.isfile(fn): - raise GitMergeException, \ - 'Cannot run the interactive merge: "%s" missing' % fn - - mtime = os.path.getmtime(filename) - - out.info('Trying the interactive %s merge' - % (three_way and 'three-way' or 'two-way')) - - err = os.system(imerger % files_dict) - if err != 0: - raise GitMergeException, 'The interactive merge failed: %d' % err - if not os.path.isfile(filename): - raise GitMergeException, 'The "%s" file is missing' % filename - if mtime == os.path.getmtime(filename): - raise GitMergeException, 'The "%s" file was not modified' % filename - - -# -# Main algorithm -# -def merge(orig_hash, file1_hash, file2_hash, - path, - orig_mode, file1_mode, file2_mode): - """Three-way merge for one file algorithm +def interactive_merge(filename): + """Run the interactive merger on the given file. Stages will be + removed according to stgit.keeporig. If successful and stages + kept, they will be removed via git.resolved(). """ - __checkout_files(orig_hash, file1_hash, file2_hash, - path, - orig_mode, file1_mode, file2_mode) - - # file exists in origin - if orig_hash: - # modified in both - if file1_hash and file2_hash: - # if modes are the same (git read-tree probably dealt with it) - if file1_hash == file2_hash: - if os.system('git update-index --cacheinfo %s %s %s' - % (file1_mode, file1_hash, path)) != 0: - out.error('git update-index failed') - __conflict(path) - return 1 - if os.system('git checkout-index -u -f -- %s' % path): - out.error('git checkout-index failed') - __conflict(path) - return 1 - if file1_mode != file2_mode: - out.error('File added in both, permissions conflict') - __conflict(path) - return 1 - # 3-way merge - else: - merge_ok = os.system(str(merger) % {'branch1': src1, - 'ancestor': orig, - 'branch2': src2, - 'output': path }) == 0 - - if merge_ok: - os.system('git update-index -- %s' % path) - __remove_files(orig_hash, file1_hash, file2_hash) - return 0 - else: - out.error('Three-way merge tool failed for file "%s"' - % path) - # reset the cache to the first branch - os.system('git update-index --cacheinfo %s %s %s' - % (file1_mode, file1_hash, path)) - - if config.get('stgit.autoimerge') == 'yes': - try: - interactive_merge(path) - except GitMergeException, ex: - # interactive merge failed - out.error(str(ex)) - if str(keeporig) != 'yes': - __remove_files(orig_hash, file1_hash, - file2_hash) - __conflict(path) - return 1 - # successful interactive merge - os.system('git update-index -- %s' % path) - __remove_files(orig_hash, file1_hash, file2_hash) - return 0 - else: - # no interactive merge, just mark it as conflict - if str(keeporig) != 'yes': - __remove_files(orig_hash, file1_hash, file2_hash) - __conflict(path) - return 1 - - # file deleted in both or deleted in one and unchanged in the other - elif not (file1_hash or file2_hash) \ - or file1_hash == orig_hash or file2_hash == orig_hash: - if os.path.exists(path): - os.remove(path) - __remove_files(orig_hash, file1_hash, file2_hash) - return os.system('git update-index --remove -- %s' % path) - # file deleted in one and changed in the other + stages = __checkout_stages(filename) + + try: + # Check whether we have all the files for the merge. + if not (stages['current'] and stages['patched']): + raise GitMergeException('Cannot run the interactive merge') + + if stages['ancestor']: + three_way = True + files_dict = {'branch1': stages['current'], + 'ancestor': stages['ancestor'], + 'branch2': stages['patched'], + 'output': filename} + imerger = config.get('stgit.i3merge') else: - # Do something here - we must at least merge the entry in - # the cache, instead of leaving it in U(nmerged) state. In - # fact, stg resolved does not handle that. - - # Do the same thing cogito does - remove the file in any case. - os.system('git update-index --remove -- %s' % path) - - #if file1_hash: - ## file deleted upstream and changed in the patch. The - ## patch is probably going to move the changes - ## elsewhere. - - #os.system('git update-index --remove -- %s' % path) - #else: - ## file deleted in the patch and changed upstream. We - ## could re-delete it, but for now leave it there - - ## and let the user check if he still wants to remove - ## the file. - - ## reset the cache to the first branch - #os.system('git update-index --cacheinfo %s %s %s' - # % (file1_mode, file1_hash, path)) - __conflict(path) - return 1 - - # file does not exist in origin - else: - # file added in both - if file1_hash and file2_hash: - # files are the same - if file1_hash == file2_hash: - if os.system('git update-index --add --cacheinfo %s %s %s' - % (file1_mode, file1_hash, path)) != 0: - out.error('git update-index failed') - __conflict(path) - return 1 - if os.system('git checkout-index -u -f -- %s' % path): - out.error('git checkout-index failed') - __conflict(path) - return 1 - if file1_mode != file2_mode: - out.error('File "%s" added in both, permissions conflict' - % path) - __conflict(path) - return 1 - # files added in both but different - else: - out.error('File "%s" added in branches but different' % path) - # reset the cache to the first branch - os.system('git update-index --cacheinfo %s %s %s' - % (file1_mode, file1_hash, path)) - - if config.get('stgit.autoimerge') == 'yes': - try: - interactive_merge(path) - except GitMergeException, ex: - # interactive merge failed - out.error(str(ex)) - if str(keeporig) != 'yes': - __remove_files(orig_hash, file1_hash, - file2_hash) - __conflict(path) - return 1 - # successful interactive merge - os.system('git update-index -- %s' % path) - __remove_files(orig_hash, file1_hash, file2_hash) - return 0 - else: - # no interactive merge, just mark it as conflict - if str(keeporig) != 'yes': - __remove_files(orig_hash, file1_hash, file2_hash) - __conflict(path) - return 1 - # file added in one - elif file1_hash or file2_hash: - if file1_hash: - mode = file1_mode - obj = file1_hash - else: - mode = file2_mode - obj = file2_hash - if os.system('git update-index --add --cacheinfo %s %s %s' - % (mode, obj, path)) != 0: - out.error('git update-index failed') - __conflict(path) - return 1 - __remove_files(orig_hash, file1_hash, file2_hash) - return os.system('git checkout-index -u -f -- %s' % path) + three_way = False + files_dict = {'branch1': stages['current'], + 'branch2': stages['patched'], + 'output': filename} + imerger = config.get('stgit.i2merge') + + if not imerger: + raise GitMergeException, 'No interactive merge command configured' + + mtime = os.path.getmtime(filename) + + out.start('Trying the interactive %s merge' + % (three_way and 'three-way' or 'two-way')) + err = os.system(imerger % files_dict) + out.done() + if err != 0: + raise GitMergeException, 'The interactive merge failed' + if not os.path.isfile(filename): + raise GitMergeException, 'The "%s" file is missing' % filename + if mtime == os.path.getmtime(filename): + raise GitMergeException, 'The "%s" file was not modified' % filename + finally: + # keep the merge stages? + if str(keeporig) != 'yes': + __remove_stages(filename) + +def clean_up(filename): + """Remove merge conflict stages if they were generated. + """ + if str(keeporig) == 'yes': + __remove_stages(filename) - # Unhandled case - out.error('Unhandled merge conflict: "%s" "%s" "%s" "%s" "%s" "%s" "%s"' - % (orig_hash, file1_hash, file2_hash, - path, - orig_mode, file1_mode, file2_mode)) - __conflict(path) - return 1 +def merge(filename): + """Merge one file if interactive is allowed or check out the stages + if keeporig is set. + """ + if str(autoimerge) == 'yes': + try: + interactive_merge(filename) + except GitMergeException, ex: + out.error(str(ex)) + return False + return True + + if str(keeporig) == 'yes': + __checkout_stages(filename) + + return False diff --git a/stgit/lib/__init__.py b/stgit/lib/__init__.py new file mode 100644 index 0000000..45eb307 --- /dev/null +++ b/stgit/lib/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- + +__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, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +""" diff --git a/stgit/lib/edit.py b/stgit/lib/edit.py new file mode 100644 index 0000000..c8d29f6 --- /dev/null +++ b/stgit/lib/edit.py @@ -0,0 +1,99 @@ +"""This module contains utility functions for patch editing.""" + +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 != 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 == 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 = ['From: %s <%s>' % (cd.author.name, cd.author.email), + 'Date: %s' % cd.author.date.isoformat(), + '', + cd.message] + if append_diff: + if replacement_diff: + diff = replacement_diff + else: + just_diff = repo.diff_tree(cd.parent.data.tree, cd.tree, diff_flags) + diff = '\n'.join([git.diffstat(just_diff), just_diff]) + desc += ['---', '', diff] + return '\n'.join(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_string( + 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 == 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 != 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 diff --git a/stgit/lib/git.py b/stgit/lib/git.py new file mode 100644 index 0000000..0a208ef --- /dev/null +++ b/stgit/lib/git.py @@ -0,0 +1,907 @@ +"""A Python class hierarchy wrapping a git repository and its +contents.""" + +import os, os.path, re +from datetime import datetime, timedelta, tzinfo + +from stgit import exception, run, utils +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 + +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 xrange(6)], + **{'tzinfo': TimeZone(m.group(7))}) + except ValueError: + raise DateException(datestring, 'date') + 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(' '), + 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] + name = property(lambda self: self.__name) + email = property(lambda self: self.__email) + name_email = property(lambda self: '%s <%s>' % (self.name, self.email)) + date = property(lambda self: 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 = os.environ.get('GIT_AUTHOR_NAME', NoValue), + email = os.environ.get('GIT_AUTHOR_EMAIL', NoValue), + date = Date.maybe(os.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 = os.environ.get('GIT_COMMITTER_NAME', NoValue), + email = os.environ.get('GIT_COMMITTER_EMAIL', NoValue), + date = Date.maybe( + os.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, string): + self.__string = str(string) + str = property(lambda self: self.__string) + def commit(self, repository): + """Commit the blob. + @return: The committed blob + @rtype: L{Blob}""" + sha1 = repository.run(['git', 'hash-object', '-w', '--stdin'] + ).raw_input(self.str).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 + sha1 = property(lambda self: self.__sha1) + def __str__(self): + return 'Blob<%s>' % self.sha1 + @property + def data(self): + return BlobData(self.__repository.cat_object(self.sha1)) + +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.iteritems()) + entries = property(lambda self: self.__entries) + """Map from name to (I{permission}, I{object}) tuple.""" + def set_entry(self, name, po): + """Create a new L{TreeData} object identical to this one, except that + it maps C{name} to C{po}. + + @param name: Name of the changed mapping + @type name: C{str} + @param po: Value of the changed mapping + @type po: L{Blob} or L{Tree} or (C{str}, L{Blob} or L{Tree}) + @return: The new L{TreeData} object + @rtype: L{TreeData}""" + e = dict(self.entries) + e[name] = self.__x(po) + return type(self)(e) + def del_entry(self, name): + """Create a new L{TreeData} object identical to this one, except that + it doesn't map C{name} to anything. + + @param name: Name of the deleted mapping + @type name: C{str} + @return: The new L{TreeData} object + @rtype: L{TreeData}""" + e = dict(self.entries) + del e[name] + return type(self)(e) + def commit(self, repository): + """Commit the tree. + @return: The committed tree + @rtype: L{Tree}""" + listing = ''.join( + '%s %s %s\t%s\0' % (mode, obj.typename, obj.sha1, name) + for (name, (mode, obj)) in self.entries.iteritems()) + sha1 = repository.run(['git', 'mktree', '-z'] + ).raw_input(listing).output_one_line() + return repository.get_tree(sha1) + @classmethod + def parse(cls, repository, s): + """Parse a raw git tree description. + + @return: A new L{TreeData} object + @rtype: L{TreeData}""" + entries = {} + for line in s.split('\0')[:-1]: + 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 + sha1 = property(lambda self: self.__sha1) + @property + def data(self): + if self.__data == None: + self.__data = TreeData.parse( + self.__repository, + self.__repository.run(['git', 'ls-tree', '-z', self.sha1] + ).raw_output()) + 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') + tree = property(lambda self: self.__tree) + parents = property(lambda self: self.__parents) + @property + def parent(self): + assert len(self.__parents) == 1 + return self.__parents[0] + author = property(lambda self: self.__author) + committer = property(lambda self: self.__committer) + message = property(lambda self: 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 == None: + tree = None + else: + tree = self.tree.sha1 + if self.parents == 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) + env = {} + for p, v1 in ((self.author, 'AUTHOR'), + (self.committer, 'COMMITTER')): + if p != None: + for attr, v2 in (('name', 'NAME'), ('email', 'EMAIL'), + ('date', 'DATE')): + if getattr(p, attr) != None: + env['GIT_%s_%s' % (v1, v2)] = str(getattr(p, attr)) + sha1 = repository.run(c, env = 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 = list(s.splitlines(True)) + for i in xrange(len(lines)): + line = lines[i].strip() + if not line: + return cd.set_message(''.join(lines[i+1:])) + key, value = line.split(None, 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)) + else: + assert False + assert False + +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 + sha1 = property(lambda self: self.__sha1) + @property + def data(self): + if self.__data == 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 = {} + for line in self.__repository.run(['git', 'show-ref']).output_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 == 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 == 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 == 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 not name 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 not name 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.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 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 + env = property(lambda self: { 'GIT_DIR': self.__git_dir }) + @classmethod + def default(cls): + """Return the default repository.""" + try: + return cls(run.Run('git', 'rev-parse', '--git-dir' + ).output_one_line()) + except run.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 == None: + self.__default_index = Index( + self, (os.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 == None: + path = os.environ.get('GIT_WORK_TREE', None) + if not path: + o = run.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 == None: + self.__default_iw = IndexAndWorktree(self.default_index, + self.default_worktree) + return self.__default_iw + directory = property(lambda self: self.__git_dir) + refs = property(lambda self: self.__refs) + def cat_object(self, sha1): + return self.run(['git', 'cat-file', '-p', sha1]).raw_output() + def rev_parse(self, rev, discard_stderr = False): + try: + return self.get_commit(self.run( + ['git', 'rev-parse', '%s^{commit}' % rev] + ).discard_stderr(discard_stderr).output_one_line()) + except run.RunException: + raise RepositoryException('%s: No such revision' % rev) + 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 run.RunException: + raise DetachedHeadException() + def set_head_ref(self, ref, msg): + self.run(['git', 'symbolic-ref', '-m', msg, 'HEAD', ref]).no_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_text, 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_text: + return tree + index = self.temp_index() + try: + index.read_tree(tree) + try: + index.apply(patch_text, quiet) + return index.write_tree() + except MergeException: + return None + finally: + index.delete() + def diff_tree(self, t1, t2, diff_opts): + """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) + return self.run(['git', 'diff-tree', '-p'] + list(diff_opts) + + [t1.sha1, t2.sha1]).raw_output() + 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) + i = iter(self.run(['git', 'diff-tree', '-r', '-z'] + [t1.sha1, t2.sha1] + ).raw_output().split('\0')) + try: + while True: + x = i.next() + if not x: + continue + omode, nmode, osha1, nsha1, status = x[1:].split(' ') + fn1 = i.next() + if status[0] in ['C', 'R']: + fn2 = i.next() + 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.""" + +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 + env = property(lambda self: 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 run.RunException: + raise MergeException('Conflicting merge') + def is_clean(self): + try: + self.run(['git', 'update-index', '--refresh']).discard_output() + except run.RunException: + return False + else: + return True + def apply(self, patch_text, quiet): + """In-index patch application, no worktree involved.""" + try: + r = self.run(['git', 'apply', '--cached']).raw_input(patch_text) + if quiet: + r = r.discard_stderr() + r.no_output() + except run.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 == 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'] + ).raw_output().split('\0')[:-1]: + 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 + env = property(lambda self: { 'GIT_WORK_TREE': '.' }) + env_in_cwd = property(lambda self: { 'GIT_WORK_TREE': self.directory }) + directory = property(lambda self: 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 + index = property(lambda self: self.__index) + env = property(lambda self: utils.add_dict(self.__index.env, + self.__worktree.env)) + env_in_cwd = property(lambda self: self.__worktree.env_in_cwd) + cwd = property(lambda self: 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 run.RunException: + raise CheckoutException('Index/workdir dirty') + def merge(self, base, ours, theirs): + 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.discard_output() + except run.RunException, e: + if r.exitcode == 1: + raise MergeConflictException() + else: + raise MergeException('Index/worktree dirty') + 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)).raw_output().split('\0')[:-1]) + 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() + +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) + + name = property(lambda self: self.__name) + repository = property(lambda self: 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): + value = 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.Run('git', 'apply', '--stat', '--summary' + ).raw_input(diff).raw_output() diff --git a/stgit/lib/log.py b/stgit/lib/log.py new file mode 100644 index 0000000..dfadd51 --- /dev/null +++ b/stgit/lib/log.py @@ -0,0 +1,524 @@ +r"""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.""" + +import re +from stgit.lib import git, stack as libstack +from stgit import exception, utils +from stgit.out import out +import StringIO + +class LogException(exception.StgException): + pass + +class LogParseException(LogException): + pass + +def patch_file(repo, cd): + return repo.commit(git.BlobData(''.join(s + '\n' for s in [ + '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, + '', + '---', + '', + repo.diff_tree(cd.parent.data.tree, cd.tree, ['-M'] + ).strip()]))) + +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 != 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 + all_patches = property(lambda self: (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 = {} + for line in metadata: + if line.startswith(' '): + 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.keys(): + 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.str) + lg = cls(repo, prev, head, applied, unapplied, hidden, patches, message) + lg.commit = commit + return lg + def __metadata_string(self): + e = StringIO.StringIO() + e.write('Version: 1\n') + if self.prev == 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 != None: + xp.add(self.prev.commit) + xp -= set(self.prev.patches.values()) + return xp + def __tree(self, metadata): + if self.prev == 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.iteritems()) + 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.iteritems()) + return self.__repo.commit(git.TreeData({ + 'meta': self.__repo.commit(git.BlobData(metadata)), + '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 != 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, 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, 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.)""" + repo = default_repo() + try: + stack = repo.get_stack(repo.current_branch_name) + except libstack.StackException, 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 not pn 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 exception.StgException: + # Stack doesn't exist, so we can't log. + return + log_external_mods(stack) diff --git a/stgit/lib/stack.py b/stgit/lib/stack.py new file mode 100644 index 0000000..47679b6 --- /dev/null +++ b/stgit/lib/stack.py @@ -0,0 +1,265 @@ +"""A Python class hierarchy wrapping the StGit on-disk metadata.""" + +import os.path +from stgit import exception, utils +from stgit.lib import git, stackupgrade +from stgit.config import config + +class StackException(exception.StgException): + """Exception raised by L{stack} objects.""" + +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 + name = property(lambda self: 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) + 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 not name 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) + applied = property(lambda self: self.__get_list('applied'), + lambda self, val: self.__set_list('applied', val)) + unapplied = property(lambda self: self.__get_list('unapplied'), + lambda self, val: self.__set_list('unapplied', val)) + hidden = property(lambda self: self.__get_list('hidden'), + lambda self, val: self.__set_list('hidden', val)) + all = property(lambda self: self.applied + self.unapplied + self.hidden) + all_visible = property(lambda self: 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 not name 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) + patchorder = property(lambda self: self.__patchorder) + patches = property(lambda self: 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), + str(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 not name in self.__stacks: + self.__stacks[name] = Stack(self, name) + return self.__stacks[name] diff --git a/stgit/lib/stackupgrade.py b/stgit/lib/stackupgrade.py new file mode 100644 index 0000000..4b437dc --- /dev/null +++ b/stgit/lib/stackupgrade.py @@ -0,0 +1,105 @@ +import os.path +from stgit import utils +from stgit.out import out +from stgit.config import config + +# 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 + for patch in (file(os.path.join(branch_dir, 'unapplied')).readlines() + + file(os.path.join(branch_dir, 'applied')).readlines()): + 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 not fv in [None, FORMAT_VERSION]: + raise StackException('Branch %s is at format version %d, expected %d' + % (branch, fv, FORMAT_VERSION)) + return fv != None # true if branch is initialized diff --git a/stgit/lib/transaction.py b/stgit/lib/transaction.py new file mode 100644 index 0000000..de62a8c --- /dev/null +++ b/stgit/lib/transaction.py @@ -0,0 +1,360 @@ +"""The L{StackTransaction} class makes it possible to make complex +updates to an StGit stack in a safe and convenient way.""" + +import atexit +import itertools as it + +from stgit import exception, utils +from stgit.utils import any, all +from stgit.out import * +from stgit.lib import git, log + +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 sha1 strings.""" + 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): + """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.__conflicting_push = None + 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 + 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() + stack = property(lambda self: self.__stack) + patches = property(lambda self: self.__patches) + def __set_applied(self, val): + self.__applied = list(val) + applied = property(lambda self: self.__applied, __set_applied) + def __set_unapplied(self, val): + self.__unapplied = list(val) + unapplied = property(lambda self: self.__unapplied, __set_unapplied) + def __set_hidden(self, val): + self.__hidden = list(val) + hidden = property(lambda self: self.__hidden, __set_hidden) + all_patches = property(lambda self: (self.__applied + self.__unapplied + + self.__hidden)) + def __set_base(self, val): + assert (not self.__applied + or self.patches[self.applied[0]].data.parent == val) + self.__base = val + base = property(lambda self: self.__base, __set_base) + @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 + def __get_head(self): + if self.__bad_head: + return self.__bad_head + else: + return self.top + def __set_head(self, val): + self.__bad_head = val + head = property(__get_head, __set_head) + 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 __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 == None + or not iw.index.conflicts()): + return + out.error('Need to resolve conflicts first') + self.__abort() + assert iw != 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.iteritems(): + if commit == 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: + out.error(self.__error) + + # Write patches. + def write(msg): + for pn, commit in self.__patches.iteritems(): + if self.__stack.patches.exists(pn): + p = self.__stack.patches.get(pn) + if commit == 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 + write(self.__msg) + if self.__conflicting_push != None: + self.__patches = _TransPatchMap(self.__stack) + self.__conflicting_push() + 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 xrange(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 xrange(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): + """Attempt to push the named patch. If this results in conflicts, + halts the transaction. If index+worktree are given, spill any + conflicts to them.""" + orig_cd = self.patches[pn].data + cd = orig_cd.set_committer(None) + s = ['', ' (empty)'][cd.is_nochange()] + oldparent = cd.parent + cd = cd.set_parent(self.top) + 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) + merge_conflict = False + if not tree: + if iw == 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: + iw.merge(base, ours, theirs) + tree = iw.index.write_tree() + self.__current_tree = tree + s = ' (modified)' + except git.MergeConflictException: + tree = ours + merge_conflict = True + s = ' (conflict)' + except git.MergeException, 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) + else: + comm = None + s = ' (unmodified)' + out.info('Pushed %s%s' % (pn, s)) + def update(): + 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: + # We've just caused conflicts, so we must allow them in + # the final checkout. + self.__allow_conflicts = lambda trans: True + + # Save this update so that we can run it a little later. + self.__conflicting_push = update + self.__halt('Merge conflict') + else: + # Update immediately. + update() + + def reorder_patches(self, applied, unapplied, hidden, iw = None): + """Push and pop patches to attain the given ordering.""" + common = len(list(it.takewhile(lambda (a, b): a == b, + 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) + assert self.applied == applied + assert set(self.unapplied + self.hidden) == set(unapplied + hidden) + self.unapplied = unapplied + self.hidden = hidden diff --git a/stgit/main.py b/stgit/main.py index a03447f..e324179 100644 --- a/stgit/main.py +++ b/stgit/main.py @@ -18,11 +18,11 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys, os -from optparse import OptionParser +import sys, os, traceback import stgit.commands from stgit.out import * +from stgit import argparse, run, utils # # The commands map @@ -39,124 +39,22 @@ class Commands(dict): if not candidates: out.error('Unknown command: %s' % key, 'Try "%s help" for a list of supported commands' % prog) - sys.exit(1) + sys.exit(utils.STGIT_GENERAL_ERROR) elif len(candidates) > 1: out.error('Ambiguous command: %s' % key, 'Candidates are: %s' % ', '.join(candidates)) - sys.exit(1) + sys.exit(utils.STGIT_GENERAL_ERROR) return candidates[0] def __getitem__(self, key): - """Return the command python module name based. - """ - global prog - cmd_mod = self.get(key) or self.get(self.canonical_cmd(key)) - - __import__('stgit.commands.' + cmd_mod) - return getattr(stgit.commands, cmd_mod) + return stgit.commands.get_command(cmd_mod) -commands = Commands({ - 'add': 'add', - 'applied': 'applied', - 'branch': 'branch', - 'delete': 'delete', - 'diff': 'diff', - 'clean': 'clean', - 'clone': 'clone', - 'commit': 'commit', - 'cp': 'copy', - 'edit': 'edit', - 'export': 'export', - 'files': 'files', - 'float': 'float', - 'fold': 'fold', - 'goto': 'goto', - 'hide': 'hide', - 'id': 'id', - 'import': 'imprt', - 'init': 'init', - 'log': 'log', - 'mail': 'mail', - 'new': 'new', - 'patches': 'patches', - 'pick': 'pick', - 'pop': 'pop', - 'pull': 'pull', - 'push': 'push', - 'rebase': 'rebase', - 'refresh': 'refresh', - 'rename': 'rename', - 'repair': 'repair', - 'resolved': 'resolved', - 'rm': 'rm', - 'series': 'series', - 'show': 'show', - 'sink': 'sink', - 'status': 'status', - 'sync': 'sync', - 'top': 'top', - 'unapplied': 'unapplied', - 'uncommit': 'uncommit', - 'unhide': 'unhide' - }) +cmd_list = stgit.commands.get_commands() +commands = Commands((cmd, mod) for cmd, (mod, kind, help) + in cmd_list.iteritems()) -# classification: repository, stack, patch, working copy -repocommands = ( - 'clone', - 'id', - ) -stackcommands = ( - 'applied', - 'branch', - 'clean', - 'commit', - 'float', - 'goto', - 'hide', - 'init', - 'patches', - 'pop', - 'pull', - 'push', - 'rebase', - 'repair', - 'series', - 'sink', - 'top', - 'unapplied', - 'uncommit', - 'unhide', - ) -patchcommands = ( - 'delete', - 'edit', - 'export', - 'files', - 'fold', - 'import', - 'log', - 'mail', - 'new', - 'pick', - 'refresh', - 'rename', - 'show', - 'sync', - ) -wccommands = ( - 'add', - 'cp', - 'diff', - 'resolved', - 'rm', - 'status', - ) - -def _print_helpstring(cmd): - print ' ' + cmd + ' ' * (12 - len(cmd)) + commands[cmd].help - def print_help(): print 'usage: %s [options]' % os.path.basename(sys.argv[0]) print @@ -164,38 +62,13 @@ def print_help(): print ' help print the detailed command usage' print ' version display version information' print ' copyright display copyright information' - # unclassified commands if any - cmds = commands.keys() - cmds.sort() - for cmd in cmds: - if not cmd in repocommands and not cmd in stackcommands \ - and not cmd in patchcommands and not cmd in wccommands: - _print_helpstring(cmd) - print - - print 'Repository commands:' - for cmd in repocommands: - _print_helpstring(cmd) - print - - print 'Stack commands:' - for cmd in stackcommands: - _print_helpstring(cmd) - print - - print 'Patch commands:' - for cmd in patchcommands: - _print_helpstring(cmd) print - - print 'Working-copy commands:' - for cmd in wccommands: - _print_helpstring(cmd) + stgit.commands.pretty_command_list(cmd_list, sys.stdout) # # The main function (command dispatcher) # -def main(): +def _main(): """The main function """ global prog @@ -206,7 +79,7 @@ def main(): print >> sys.stderr, 'usage: %s ' % prog print >> sys.stderr, \ ' Try "%s --help" for a list of supported commands' % prog - sys.exit(1) + sys.exit(utils.STGIT_GENERAL_ERROR) cmd = sys.argv[1] @@ -216,32 +89,31 @@ def main(): sys.argv[2] = '--help' else: print_help() - sys.exit(0) + 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]) if not cmd in commands: out.error('%s help: "%s" command unknown' % (prog, cmd)) - sys.exit(1) + sys.exit(utils.STGIT_GENERAL_ERROR) sys.argv[0] += ' %s' % cmd command = commands[cmd] - parser = OptionParser(usage = command.usage, - option_list = command.options) + parser = argparse.make_option_parser(command) from pydoc import pager pager(parser.format_help()) else: print_help() - sys.exit(0) + sys.exit(utils.STGIT_SUCCESS) if cmd in ['-v', '--version', 'version']: from stgit.version import version print 'Stacked GIT %s' % version os.system('git --version') print 'Python version %s' % sys.version - sys.exit(0) + sys.exit(utils.STGIT_SUCCESS) if cmd in ['copyright']: print __copyright__ - sys.exit(0) + sys.exit(utils.STGIT_SUCCESS) # re-build the command line arguments cmd = commands.canonical_cmd(cmd) @@ -249,8 +121,7 @@ def main(): del(sys.argv[1]) command = commands[cmd] - usage = command.usage.split('\n')[0].strip() - parser = OptionParser(usage = usage, option_list = command.options) + parser = argparse.make_option_parser(command) options, args = parser.parse_args() directory = command.directory @@ -265,7 +136,7 @@ def main(): debug_level = int(os.environ.get('STGIT_DEBUG_LEVEL', 0)) except ValueError: out.error('Invalid STGIT_DEBUG_LEVEL environment variable') - sys.exit(1) + sys.exit(utils.STGIT_GENERAL_ERROR) try: directory.setup() @@ -278,14 +149,29 @@ def main(): else: command.crt_series = Series() - command.func(parser, options, args) + ret = command.func(parser, options, args) except (StgException, IOError, ParsingError, NoSectionError), err: + directory.write_log(cmd) out.error(str(err), title = '%s %s' % (prog, cmd)) if debug_level > 0: - raise - else: - sys.exit(2) + traceback.print_exc() + 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(1) + sys.exit(utils.STGIT_GENERAL_ERROR) + except: + out.error('Unhandled exception:') + traceback.print_exc() + sys.exit(utils.STGIT_BUG_ERROR) - sys.exit(0) + directory.write_log(cmd) + sys.exit(ret or utils.STGIT_SUCCESS) + +def main(): + try: + _main() + finally: + run.finish_logging() diff --git a/stgit/out.py b/stgit/out.py index d3c86b4..753c176 100644 --- a/stgit/out.py +++ b/stgit/out.py @@ -17,10 +17,10 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ -import sys +import sys, textwrap class MessagePrinter(object): - def __init__(self): + def __init__(self, file = None): class Output(object): def __init__(self, write, flush): self.write = write @@ -49,6 +49,10 @@ class MessagePrinter(object): 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) @@ -64,9 +68,12 @@ class MessagePrinter(object): self.new_line() self.write(string) self.at_start_of_line = string.endswith('\n') - self.__stderr = Output(sys.stderr.write, sys.stderr.flush) - self.__stdout = Output(sys.stdout.write, sys.stdout.flush) - if sys.stdout.isatty(): + if file: + self.__stdout = self.__stderr = Output(file.write, file.flush) + else: + self.__stdout = Output(sys.stdout.write, sys.stdout.flush) + self.__stderr = Output(sys.stdout.write, sys.stdout.flush) + if file or sys.stdout.isatty(): self.__out = self.__stdout self.__err = self.__stdout else: diff --git a/stgit/run.py b/stgit/run.py index fa304d0..7493ed3 100644 --- a/stgit/run.py +++ b/stgit/run.py @@ -27,12 +27,40 @@ class RunException(StgException): subprocess.""" pass -_all_log_modes = ['debug', 'profile'] -_log_mode = os.environ.get('STGIT_SUBPROCESS_LOG', '') -if _log_mode and not _log_mode 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)) +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 not log_mode 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(open(outfile, 'a')) + else: + f = out + return (log_mode, f) + +(_log_mode, _logfile) = get_log_mode(os.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: exc = RunException @@ -42,21 +70,32 @@ class Run: if type(c) != str: raise Exception, 'Bad command: %r' % (cmd,) self.__good_retvals = [0] - self.__env = None + self.__env = self.__cwd = None self.__indata = None self.__discard_stderr = False def __log_start(self): if _log_mode == 'debug': - out.start('Running subprocess %s' % self.__cmd) + _logfile.start('Running subprocess %s' % self.__cmd) + if self.__cwd != None: + _logfile.info('cwd: %s' % self.__cwd) + if self.__env != None: + for k in sorted(self.__env.iterkeys()): + if k not in os.environ or os.environ[k] != self.__env[k]: + _logfile.info('%s: %s' % (k, self.__env[k])) elif _log_mode == 'profile': - out.start('Running subprocess %s' % self.__cmd[0]) + _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': - out.done('return code: %d' % retcode) + _logfile.done('return code: %d' % retcode) elif _log_mode == 'profile': - duration = datetime.datetime.now() - self.__starttime - out.done('%1.3f s' % (duration.microseconds/1e6 + duration.seconds)) + 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 == None: return @@ -67,7 +106,7 @@ class Run: """Run with captured IO.""" self.__log_start() try: - p = subprocess.Popen(self.__cmd, env = self.__env, + p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) @@ -85,7 +124,7 @@ class Run: assert self.__indata == None self.__log_start() try: - p = subprocess.Popen(self.__cmd, env = self.__env) + p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd) self.exitcode = p.wait() except OSError, e: raise self.exc('%s failed: %s' % (self.__cmd[0], e)) @@ -104,12 +143,18 @@ class Run: self.__env = dict(os.environ) self.__env.update(env) return self + def cwd(self, cwd): + self.__cwd = cwd + return self def raw_input(self, indata): self.__indata = indata return self def input_lines(self, lines): self.__indata = ''.join(['%s\n' % line for line in lines]) return self + def input_nulterm(self, lines): + self.__indata = ''.join('%s\0' % line for line in lines) + return self def no_output(self): outdata = self.__run_io() if outdata: diff --git a/stgit/stack.py b/stgit/stack.py index 802a382..9958e7a 100644 --- a/stgit/stack.py +++ b/stgit/stack.py @@ -28,7 +28,7 @@ from stgit.run import * from stgit import git, basedir, templates from stgit.config import config from shutil import copyfile - +from stgit.lib import git as libgit, stackupgrade # stack exception class class StackException(StgException): @@ -162,8 +162,6 @@ class Patch(StgitObject): def create(self): os.mkdir(self._dir()) - self.create_empty_field('bottom') - self.create_empty_field('top') def delete(self, keep_log = False): if os.path.isdir(self._dir()): @@ -198,47 +196,35 @@ class Patch(StgitObject): 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 update_top_ref(self): - top = self.get_top() - if top: - self.__update_top_ref(top) - def get_old_bottom(self): - return self._get_field('bottom.old') + return git.get_commit(self.get_old_top()).get_parent() def get_bottom(self): - return self._get_field('bottom') - - def set_bottom(self, value, backup = False): - if backup: - curr = self._get_field('bottom') - self._set_field('bottom.old', curr) - self._set_field('bottom', value) + return git.get_commit(self.get_top()).get_parent() def get_old_top(self): return self._get_field('top.old') def get_top(self): - return self._get_field('top') + return git.rev_parse(self.__top_ref) def set_top(self, value, backup = False): if backup: - curr = self._get_field('top') - self._set_field('top.old', curr) - self._set_field('top', value) + 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 restore_old_boundaries(self): - bottom = self._get_field('bottom.old') top = self._get_field('top.old') - if top and bottom: - self._set_field('bottom', bottom) - self._set_field('top', top) + if top: self.__update_top_ref(top) return True else: @@ -296,9 +282,6 @@ class Patch(StgitObject): self._set_field('log', value) self.__update_log_ref(value) -# The current StGIT metadata format version. -FORMAT_VERSION = 2 - class PatchSet(StgitObject): def __init__(self, name = None): try: @@ -366,7 +349,8 @@ class PatchSet(StgitObject): def is_initialised(self): """Checks if series is already initialised """ - return bool(config.get(self.format_version_key())) + return config.get(stackupgrade.format_version_key(self.get_name()) + ) != None def shortlog(patches): @@ -385,7 +369,8 @@ class Series(PatchSet): # Update the branch to the latest format version if it is # initialized, but don't touch it if it isn't. - self.update_to_current_format_version() + stackupgrade.update_to_current_format_version( + libgit.Repository.default(), self.get_name()) self.__refs_base = 'refs/patches/%s' % self.get_name() @@ -399,86 +384,6 @@ class Series(PatchSet): # trash directory self.__trash_dir = os.path.join(self._dir(), 'trash') - def format_version_key(self): - return 'branch.%s.stgit.stackformatversion' % self.get_name() - - def update_to_current_format_version(self): - """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(self._basedir(), 'patches', self.get_name()) - 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(self.format_version_key()) - ofv = config.get('branch.%s.stgitformatversion' % self.get_name()) - 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(self.format_version_key(), ofv) - config.unset('branch.%s.stgitformatversion' % self.get_name()) - 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' % (self.get_name(), v)) - config.set(self.format_version_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 git.ref_exists(ref): - git.delete_ref(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' % self.get_name() - for patch in (file(os.path.join(branch_dir, 'unapplied')).readlines() - + file(os.path.join(branch_dir, 'applied')).readlines()): - patch = patch.strip() - os.rename(os.path.join(branch_dir, patch), - os.path.join(patch_dir, patch)) - Patch(patch, patch_dir, refs_base).update_top_ref() - 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 = read_string(desc_file) - if desc: - config.set('branch.%s.description' % self.get_name(), desc) - rm(desc_file) - rm(os.path.join(branch_dir, 'current')) - rm_ref('refs/bases/%s' % self.get_name()) - set_format_version(2) - - # Make sure we're at the latest version. - if not get_format_version() in [None, FORMAT_VERSION]: - raise StackException('Branch %s is at format version %d, expected %d' - % (self.get_name(), get_format_version(), FORMAT_VERSION)) - def __patch_name_valid(self, name): """Raise an exception if the patch name is not valid. """ @@ -631,7 +536,8 @@ class Series(PatchSet): self.create_empty_field('applied') self.create_empty_field('unapplied') - config.set(self.format_version_key(), str(FORMAT_VERSION)) + config.set(stackupgrade.format_version_key(self.get_name()), + str(stackupgrade.FORMAT_VERSION)) def rename(self, to_name): """Renames a series @@ -762,6 +668,7 @@ class Series(PatchSet): 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, @@ -803,9 +710,16 @@ class Series(PatchSet): 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, @@ -813,7 +727,6 @@ class Series(PatchSet): committer_name = committer_name, committer_email = committer_email) - patch.set_bottom(bottom, backup = backup) patch.set_top(commit_id, backup = backup) patch.set_description(descr) patch.set_authname(author_name) @@ -827,26 +740,6 @@ class Series(PatchSet): return commit_id - def undo_refresh(self): - """Undo the patch boundaries changes caused by 'refresh' - """ - name = self.get_current() - assert(name) - - patch = self.get_patch(name) - old_bottom = patch.get_old_bottom() - old_top = patch.get_old_top() - - # the bottom of the patch is not changed by refresh. If the - # old_bottom is different, there wasn't any previous 'refresh' - # command (probably only a 'push') - if old_bottom != patch.get_bottom() or old_top == patch.get_top(): - raise StackException, 'No undo information available' - - git.reset(tree_id = old_top, check_out = False) - if patch.restore_old_boundaries(): - self.log_patch(patch, 'undo') - def new_patch(self, name, message = None, can_edit = True, unapplied = False, show_patch = False, top = None, bottom = None, commit = True, @@ -927,11 +820,8 @@ class Series(PatchSet): committer_name = committer_name, committer_email = committer_email) # set the patch top to the new commit - patch.set_bottom(bottom) patch.set_top(commit_id) else: - assert top != bottom - patch.set_bottom(bottom) patch.set_top(top) self.log_patch(patch, 'new') @@ -985,7 +875,6 @@ class Series(PatchSet): if head == bottom: # reset the backup information. No logging since the # patch hasn't changed - patch.set_bottom(head, backup = True) patch.set_top(top, backup = True) else: @@ -1013,7 +902,6 @@ class Series(PatchSet): committer_name = committer_name, committer_email = committer_email) - patch.set_bottom(head, backup = True) patch.set_top(top, backup = True) self.log_patch(patch, 'push(f)') @@ -1086,7 +974,6 @@ class Series(PatchSet): if head == bottom: # A fast-forward push. Just reset the backup # information. No need for logging - patch.set_bottom(bottom, backup = True) patch.set_top(top, backup = True) git.switch(top) @@ -1109,11 +996,10 @@ class Series(PatchSet): # merge can fail but the patch needs to be pushed try: - git.merge(bottom, head, top, recursive = True) + git.merge_recursive(bottom, head, top) except git.GitException, ex: out.error('The merge failed during "push".', - 'Use "refresh" after fixing the conflicts or' - ' revert the operation with "push --undo".') + 'Revert the operation with "stg undo".') append_string(self.__applied_file, name) @@ -1129,39 +1015,14 @@ class Series(PatchSet): log = 'push' self.refresh_patch(bottom = head, cache_update = False, log = log) else: - # we store the correctly merged files only for - # tracking the conflict history. Note that the - # git.merge() operations should always leave the index - # in a valid state (i.e. only stage 0 files) + # we make the patch empty, with the merged state in the + # working tree. self.refresh_patch(bottom = head, cache_update = False, - log = 'push(c)') + empty = True, log = 'push(c)') raise StackException, str(ex) return modified - def undo_push(self): - name = self.get_current() - assert(name) - - patch = self.get_patch(name) - old_bottom = patch.get_old_bottom() - old_top = patch.get_old_top() - - # the top of the patch is changed by a push operation only - # together with the bottom (otherwise the top was probably - # modified by 'refresh'). If they are both unchanged, there - # was a fast forward - if old_bottom == patch.get_bottom() and old_top != patch.get_top(): - raise StackException, 'No undo information available' - - git.reset() - self.pop_patch(name) - ret = patch.restore_old_boundaries() - if ret: - self.log_patch(patch, 'undo') - - return ret - def pop_patch(self, name, keep = False): """Pops the top patch from the stack """ diff --git a/stgit/utils.py b/stgit/utils.py index 3a480c0..751cb4a 100644 --- a/stgit/utils.py +++ b/stgit/utils.py @@ -1,7 +1,7 @@ """Common utility functions """ -import errno, optparse, os, os.path, re, sys +import errno, os, os.path, re, sys from stgit.exception import * from stgit.config import config from stgit.out import * @@ -170,25 +170,36 @@ def rename(basedir, file1, file2): class EditorException(StgException): pass +def get_editor(): + for editor in [os.environ.get('GIT_EDITOR'), + config.get('stgit.editor'), # legacy + config.get('core.editor'), + os.environ.get('VISUAL'), + os.environ.get('EDITOR'), + 'vi']: + if editor: + return editor + def call_editor(filename): """Run the editor on the specified filename.""" - - # the editor - editor = config.get('stgit.editor') - if editor: - pass - elif 'EDITOR' in os.environ: - editor = os.environ['EDITOR'] - else: - editor = 'vi' - editor += ' %s' % filename - - out.start('Invoking the editor: "%s"' % editor) - err = os.system(editor) + 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 edit_string(s, filename): + f = file(filename, 'w') + f.write(s) + f.close() + call_editor(filename) + f = file(filename) + s = f.read() + f.close() + os.remove(filename) + return s + 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.""" @@ -231,21 +242,6 @@ if not 'all' in dir(__builtins__): return False return True -def make_sign_options(): - def callback(option, opt_str, value, parser, sign_str): - if parser.values.sign_str not in [None, sign_str]: - raise optparse.OptionValueError( - '--ack and --sign were both specified') - parser.values.sign_str = sign_str - return [optparse.make_option('--sign', action = 'callback', - callback = callback, dest = 'sign_str', - callback_args = ('Signed-off-by',), - help = 'add Signed-off-by line'), - optparse.make_option('--ack', action = 'callback', - callback = callback, dest = 'sign_str', - callback_args = ('Acked-by',), - help = 'add Acked-by line')] - def add_sign_line(desc, sign_str, name, email): if not sign_str: return desc @@ -256,3 +252,38 @@ def add_sign_line(desc, sign_str, name, email): if not any(s in desc for s in ['\nSigned-off-by:', '\nAcked-by:']): 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('^(.*)\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 diff --git a/stgit/version.py b/stgit/version.py index 15832ad..d57053d 100644 --- a/stgit/version.py +++ b/stgit/version.py @@ -1,4 +1,63 @@ -version = '0.14.3' +from stgit.exception import StgException +from stgit import run, utils +import os, os.path, re, sys + +class VersionUnavailable(StgException): + pass + +def git_describe_version(): + path = sys.path[0] + try: + v = run.Run('git', 'describe', '--tags', '--abbrev=4' + ).cwd(path).output_one_line() + except run.RunException, e: + raise VersionUnavailable(str(e)) + if not re.match(r'^v[0-9]', v): + raise VersionUnavailable('%s: bad version' % v) + try: + dirty = run.Run('git', 'diff-index', '--name-only', 'HEAD' + ).cwd(path).raw_output() + except run.RunException, e: + raise VersionUnavailable(str(e)) + if dirty: + v += '-dirty' + return re.sub('-', '.', utils.strip_prefix('v', v)) + +def builtin_version(): + try: + import builtin_version as bv + except ImportError: + raise VersionUnavailable() + else: + return bv.version + +def _builtin_version_file(ext = 'py'): + return os.path.join(sys.path[0], 'stgit', 'builtin_version.%s' % ext) + +def write_builtin_version(): + try: + v = git_describe_version() + except VersionUnavailable: + return + f = file(_builtin_version_file(), 'w') + f.write('# This file was generated automatically. Do not edit by hand.\n' + 'version = %r\n' % v) + +def delete_builtin_version(): + for ext in ['py', 'pyc', 'pyo']: + fn = _builtin_version_file(ext) + if os.path.exists(fn): + os.remove(fn) + +def get_version(): + for v in [builtin_version, git_describe_version]: + try: + return v() + except VersionUnavailable: + pass + return 'unknown-version' + +version = get_version() # minimum version requirements git_min_ver = '1.5.2' diff --git a/t/README b/t/README index ffb3c66..1e9510b 100644 --- a/t/README +++ b/t/README @@ -163,9 +163,9 @@ library for your script to use. yields success, test is considered a failure. This should _not_ be used for tests that succeed when their - commands fail -- use test_expect_success and shell negation (!) for - that. test_expect_failure is for cases when a test is known to be - broken. + commands fail -- use test_expect_success and one of general_error, + command_error, and conflict for that. test_expect_failure is for + cases when a test is known to be broken. - test_debug