8 from plugin
import YapPlugin
11 class ShellError(Exception):
12 def __init__(self
, cmd
, rc
):
17 return "%s returned %d" % (self
.cmd
, self
.rc
)
19 class YapError(Exception):
20 def __init__(self
, msg
):
30 plugindir
= os
.path
.expanduser("~/.yap/plugins")
31 for p
in glob
.glob(os
.path
.join(plugindir
, "*.py")):
34 for cls
in glbls
.values():
35 if not type(cls
) == type:
37 if not issubclass(cls
, YapPlugin
):
45 if not func
.startswith('cmd_'):
47 if func
in self
.overrides
:
48 print >>sys
.stderr
, "Plugin %s overrides already overridden function %s. Disabling" % (p
, func
)
49 self
.plugins
.remove(x
)
52 def _add_new_file(self
, file):
53 repo
= get_output('git rev-parse --git-dir')[0]
54 dir = os
.path
.join(repo
, 'yap')
59 files
= self
._get
_new
_files
()
61 path
= os
.path
.join(dir, 'new-files')
62 pickle
.dump(files
, open(path
, 'w'))
64 def _get_new_files(self
):
65 repo
= get_output('git rev-parse --git-dir')[0]
66 path
= os
.path
.join(repo
, 'yap', 'new-files')
68 files
= pickle
.load(file(path
))
75 if get_output("git ls-files --cached '%s'" % f
) != []:
80 def _remove_new_file(self
, file):
81 files
= self
._get
_new
_files
()
82 files
= filter(lambda x
: x
!= file, files
)
84 repo
= get_output('git rev-parse --git-dir')[0]
85 path
= os
.path
.join(repo
, 'yap', 'new-files')
86 pickle
.dump(files
, open(path
, 'w'))
88 def _clear_new_files(self
):
89 repo
= get_output('git rev-parse --git-dir')[0]
90 path
= os
.path
.join(repo
, 'yap', 'new-files')
93 def _assert_file_exists(self
, file):
94 if not os
.access(file, os
.R_OK
):
95 raise YapError("No such file: %s" % file)
97 def _get_staged_files(self
):
98 if run_command("git rev-parse HEAD"):
99 files
= get_output("git ls-files --cached")
101 files
= get_output("git diff-index --cached --name-only HEAD")
102 unmerged
= self
._get
_unmerged
_files
()
104 unmerged
= set(unmerged
)
105 files
= set(files
).difference(unmerged
)
109 def _get_unstaged_files(self
):
110 files
= get_output("git ls-files -m")
111 prefix
= get_output("git rev-parse --show-prefix")
113 files
= [ os
.path
.join(prefix
[0], x
) for x
in files
]
114 files
+= self
._get
_new
_files
()
115 unmerged
= self
._get
_unmerged
_files
()
117 unmerged
= set(unmerged
)
118 files
= set(files
).difference(unmerged
)
122 def _get_unmerged_files(self
):
123 files
= get_output("git ls-files -u")
124 files
= [ x
.replace('\t', ' ').split(' ')[3] for x
in files
]
125 prefix
= get_output("git rev-parse --show-prefix")
127 files
= [ os
.path
.join(prefix
[0], x
) for x
in files
]
128 return list(set(files
))
130 def _delete_branch(self
, branch
, force
):
131 current
= get_output("git symbolic-ref HEAD")
133 current
= current
[0].replace('refs/heads/', '')
134 if branch
== current
:
135 raise YapError("Can't delete current branch")
137 ref
= get_output("git rev-parse --verify 'refs/heads/%s'" % branch
)
139 raise YapError("No such branch: %s" % branch
)
140 run_safely("git update-ref -d 'refs/heads/%s' '%s'" % (branch
, ref
[0]))
143 name
= get_output("git name-rev --name-only '%s'" % ref
[0])[0]
144 if name
== 'undefined':
145 run_command("git update-ref 'refs/heads/%s' '%s'" % (branch
, ref
[0]))
146 raise YapError("Refusing to delete leaf branch (use -f to force)")
147 def _get_pager_cmd(self
):
148 if 'YAP_PAGER' in os
.environ
:
149 return os
.environ
['YAP_PAGER']
150 elif 'GIT_PAGER' in os
.environ
:
151 return os
.environ
['GIT_PAGER']
152 elif 'PAGER' in os
.environ
:
153 return os
.environ
['PAGER']
157 def _add_one(self
, file):
158 self
._assert
_file
_exists
(file)
159 x
= get_output("git ls-files '%s'" % file)
161 raise YapError("File '%s' already in repository" % file)
162 self
._add
_new
_file
(file)
164 def _rm_one(self
, file):
165 self
._assert
_file
_exists
(file)
166 if get_output("git ls-files '%s'" % file) != []:
167 run_safely("git rm --cached '%s'" % file)
168 self
._remove
_new
_file
(file)
170 def _stage_one(self
, file, allow_unmerged
=False):
171 self
._assert
_file
_exists
(file)
172 prefix
= get_output("git rev-parse --show-prefix")
174 tmp
= os
.path
.normpath(os
.path
.join(prefix
[0], file))
177 if not allow_unmerged
and tmp
in self
._get
_unmerged
_files
():
178 raise YapError("Refusing to stage conflicted file: %s" % file)
179 run_safely("git update-index --add '%s'" % file)
181 def _unstage_one(self
, file):
182 self
._assert
_file
_exists
(file)
183 if run_command("git rev-parse HEAD"):
184 run_safely("git update-index --force-remove '%s'" % file)
186 run_safely("git diff-index -p HEAD '%s' | git apply -R --cached" % file)
188 def _revert_one(self
, file):
189 self
._assert
_file
_exists
(file)
190 self
._unstage
_one
(file)
191 run_safely("git checkout-index -u -f '%s'" % file)
193 def _parse_commit(self
, commit
):
194 lines
= get_output("git cat-file commit '%s'" % commit
)
199 if mode
!= 'commit' and l
.strip() == "":
204 commit
['log'].append(l
)
211 commit
['log'] = '\n'.join(commit
['log'])
214 def _check_commit(self
, **flags
):
215 if '-a' in flags
and '-d' in flags
:
216 raise YapError("Conflicting flags: -a and -d")
218 if '-d' not in flags
and self
._get
_unstaged
_files
():
219 if '-a' not in flags
and self
._get
_staged
_files
():
220 raise YapError("Staged and unstaged changes present. Specify what to commit")
221 os
.system("git diff-files -p | git apply --cached")
222 for f
in self
._get
_new
_files
():
225 def _do_uncommit(self
):
226 commit
= self
._parse
_commit
("HEAD")
227 repo
= get_output('git rev-parse --git-dir')[0]
228 dir = os
.path
.join(repo
, 'yap')
233 msg_file
= os
.path
.join(dir, 'msg')
234 fd
= file(msg_file
, 'w')
235 print >>fd
, commit
['log']
238 tree
= get_output("git rev-parse --verify HEAD^")
239 run_safely("git update-ref -m uncommit HEAD '%s'" % tree
[0])
241 def _do_commit(self
, msg
=None):
242 tree
= get_output("git write-tree")[0]
243 parent
= get_output("git rev-parse --verify HEAD 2> /dev/null")[0]
245 if os
.environ
.has_key('YAP_EDITOR'):
246 editor
= os
.environ
['YAP_EDITOR']
247 elif os
.environ
.has_key('GIT_EDITOR'):
248 editor
= os
.environ
['GIT_EDITOR']
249 elif os
.environ
.has_key('EDITOR'):
250 editor
= os
.environ
['EDITOR']
254 fd
, tmpfile
= tempfile
.mkstemp("yap")
259 repo
= get_output('git rev-parse --git-dir')[0]
260 msg_file
= os
.path
.join(repo
, 'yap', 'msg')
261 if os
.access(msg_file
, os
.R_OK
):
263 fd2
= file(tmpfile
, 'w')
264 for l
in fd1
.xreadlines():
265 print >>fd2
, l
.strip()
268 if os
.system("%s '%s'" % (editor
, tmpfile
)) != 0:
269 raise YapError("Editing commit message failed")
276 raise YapError("Refusing to use empty commit message")
278 (fd_w
, fd_r
) = os
.popen2("git stripspace > %s" % tmpfile
)
284 commit
= get_output("git commit-tree '%s' -p '%s' < '%s'" % (tree
, parent
, tmpfile
))
286 commit
= get_output("git commit-tree '%s' < '%s'" % (tree
, tmpfile
))
289 run_safely("git update-ref HEAD '%s'" % commit
[0])
291 def _check_rebasing(self
):
292 repo
= get_output('git rev-parse --git-dir')[0]
293 dotest
= os
.path
.join(repo
, '.dotest')
294 if os
.access(dotest
, os
.R_OK
):
295 raise YapError("A git operation is in progress. Complete it first")
296 dotest
= os
.path
.join(repo
, '..', '.dotest')
297 if os
.access(dotest
, os
.R_OK
):
298 raise YapError("A git operation is in progress. Complete it first")
300 def _check_git(self
):
301 if run_command("git rev-parse --git-dir"):
302 raise YapError("That command must be run from inside a git repository")
304 def _list_remotes(self
):
305 remotes
= get_output("git config --get-regexp '^remote.*.url'")
307 remote
, url
= x
.split(' ')
308 remote
= remote
.replace('remote.', '')
309 remote
= remote
.replace('.url', '')
312 def _unstage_all(self
):
314 run_safely("git read-tree -m HEAD")
316 run_safely("git read-tree HEAD")
317 run_safely("git update-index -q --refresh")
319 def _get_tracking(self
, current
):
320 remote
= get_output("git config branch.%s.remote" % current
)
322 raise YapError("No tracking branch configured for '%s'" % current
)
324 merge
= get_output("git config branch.%s.merge" % current
)
326 raise YapError("No tracking branch configured for '%s'" % current
)
327 return remote
[0], merge
329 @short_help("make a local copy of an existing repository")
331 The first argument is a URL to the existing repository. This can be an
332 absolute path if the repository is local, or a URL with the git://,
333 ssh://, or http:// schemes. By default, the directory used is the last
334 component of the URL, sans '.git'. This can be overridden by providing
337 def cmd_clone(self
, url
, directory
=None):
340 if '://' not in url
and url
[0] != '/':
341 url
= os
.path
.join(os
.getcwd(), url
)
343 url
= url
.rstrip('/')
344 if directory
is None:
345 directory
= url
.rsplit('/')[-1]
346 directory
= directory
.replace('.git', '')
351 raise YapError("Directory exists: %s" % directory
)
354 self
.cmd_repo("origin", url
)
355 self
.cmd_fetch("origin")
358 if not run_command("git rev-parse --verify refs/remotes/origin/HEAD"):
359 hash = get_output("git rev-parse refs/remotes/origin/HEAD")[0]
360 for b
in get_output("git for-each-ref --format='%(refname)' 'refs/remotes/origin/*'"):
361 if get_output("git rev-parse %s" % b
)[0] == hash:
365 if not run_command("git rev-parse --verify refs/remotes/origin/master"):
366 branch
= "refs/remotes/origin/master"
368 branch
= get_output("git for-each-ref --format='%(refname)' 'refs/remotes/origin/*'")
371 hash = get_output("git rev-parse %s" % branch
)
373 branch
= branch
.replace('refs/remotes/origin/', '')
374 run_safely("git update-ref refs/heads/%s %s" % (branch
, hash[0]))
375 run_safely("git symbolic-ref HEAD refs/heads/%s" % branch
)
376 self
.cmd_revert(**{'-a': 1})
378 @short_help("turn a directory into a repository")
380 Converts the current working directory into a repository. The primary
381 side-effect of this command is the creation of a '.git' subdirectory.
382 No files are added nor commits made.
385 os
.system("git init")
387 @short_help("add a new file to the repository")
389 The arguments are the files to be added to the repository. Once added,
390 the files will show as "unstaged changes" in the output of 'status'. To
391 reverse the effects of this command, see 'rm'.
393 def cmd_add(self
, *files
):
404 @short_help("delete a file from the repository")
406 The arguments are the files to be removed from the current revision of
407 the repository. The files will still exist in any past commits that the
408 files may have been a part of. The file is not actually deleted, it is
409 just no longer tracked as part of the repository.
411 def cmd_rm(self
, *files
):
421 @short_help("stage changes in a file for commit")
423 The arguments are the files to be staged. Staging changes is a way to
424 build up a commit when you do not want to commit all changes at once.
425 To commit only staged changes, use the '-d' flag to 'commit.' To
426 reverse the effects of this command, see 'unstage'. Once staged, the
427 files will show as "staged changes" in the output of 'status'.
429 def cmd_stage(self
, *files
):
439 @short_help("unstage changes in a file")
441 The arguments are the files to be unstaged. Once unstaged, the files
442 will show as "unstaged changes" in the output of 'status'. The '-a'
443 flag can be used to unstage all staged changes at once.
446 def cmd_unstage(self
, *files
, **flags
):
461 @short_help("show files with staged and unstaged changes")
463 Show the files in the repository with changes since the last commit,
464 categorized based on whether the changes are staged or not. A file may
465 appear under each heading if the same file has both staged and unstaged
468 def cmd_status(self
):
471 branch
= get_output("git symbolic-ref HEAD")
473 branch
= branch
[0].replace('refs/heads/', '')
476 print "Current branch: %s" % branch
478 print "Files with staged changes:"
479 files
= self
._get
_staged
_files
()
485 print "Files with unstaged changes:"
486 files
= self
._get
_unstaged
_files
()
492 files
= self
._get
_unmerged
_files
()
494 print "Files with conflicts:"
498 @short_help("remove uncommitted changes from a file (*)")
500 The arguments are the files whose changes will be reverted. If the '-a'
501 flag is given, then all files will have uncommitted changes removed.
502 Note that there is no way to reverse this command short of manually
503 editing each file again.
506 def cmd_revert(self
, *files
, **flags
):
511 run_safely("git checkout-index -u -f -a")
522 @short_help("record changes to files as a new commit")
524 Create a new commit recording changes since the last commit. If there
525 are only unstaged changes, those will be recorded. If there are only
526 staged changes, those will be recorded. Otherwise, you will have to
527 specify either the '-a' flag or the '-d' flag to commit all changes or
528 only staged changes, respectively. To reverse the effects of this
529 command, see 'uncommit'.
531 @takes_options("adm:")
532 def cmd_commit(self
, **flags
):
535 self
._check
_rebasing
()
536 self
._check
_commit
(**flags
)
537 if not self
._get
_staged
_files
():
538 raise YapError("No changes to commit")
539 msg
= flags
.get('-m', None)
543 @short_help("reverse the actions of the last commit")
545 Reverse the effects of the last 'commit' operation. The changes that
546 were part of the previous commit will show as "staged changes" in the
547 output of 'status'. This means that if no files were changed since the
548 last commit was created, 'uncommit' followed by 'commit' is a lossless
551 def cmd_uncommit(self
):
557 @short_help("report the current version of yap")
558 def cmd_version(self
):
559 print "Yap version 0.1"
561 @short_help("show the changelog for particular versions or files")
563 The arguments are the files with which to filter history. If none are
564 given, all changes are listed. Otherwise only commits that affected one
565 or more of the given files are listed. The -r option changes the
566 starting revision for traversing history. By default, history is listed
569 @takes_options("pr:")
570 def cmd_log(self
, *paths
, **flags
):
571 "[-p] [-r <rev>] <path>..."
573 rev
= flags
.get('-r', 'HEAD')
582 paths
= ' '.join(paths
)
583 os
.system("git log -M -C %s %s '%s' -- %s"
584 % (follow
, flags
.get('-p', '--name-status'), rev
, paths
))
586 @short_help("show staged, unstaged, or all uncommitted changes")
588 Show staged, unstaged, or all uncommitted changes. By default, all
589 changes are shown. The '-u' flag causes only unstaged changes to be
590 shown. The '-d' flag causes only staged changes to be shown.
593 def cmd_diff(self
, **flags
):
596 if '-u' in flags
and '-d' in flags
:
597 raise YapError("Conflicting flags: -u and -d")
599 pager
= self
._get
_pager
_cmd
()
602 os
.system("git diff-files -p | %s" % pager
)
604 os
.system("git diff-index --cached -p HEAD | %s" % pager
)
606 os
.system("git diff-index -p HEAD | %s" % pager
)
608 @short_help("list, create, or delete branches")
610 If no arguments are specified, a list of local branches is given. The
611 current branch is indicated by a "*" next to the name. If an argument
612 is given, it is taken as the name of a new branch to create. The branch
613 will start pointing at the current HEAD. See 'point' for details on
614 changing the revision of the new branch. Note that this command does
615 not switch the current working branch. See 'switch' for details on
616 changing the current working branch.
618 The '-d' flag can be used to delete local branches. If the delete
619 operation would remove the last branch reference to a given line of
620 history (colloquially referred to as "dangling commits"), yap will
621 report an error and abort. The '-f' flag can be used to force the delete
624 @takes_options("fd:")
625 def cmd_branch(self
, branch
=None, **flags
):
626 "[ [-f] -d <branch> | <branch> ]"
628 force
= '-f' in flags
630 self
._delete
_branch
(flags
['-d'], force
)
634 if branch
is not None:
635 ref
= get_output("git rev-parse --verify HEAD")
637 raise YapError("No branch point yet. Make a commit")
638 run_safely("git update-ref 'refs/heads/%s' '%s'" % (branch
, ref
[0]))
640 current
= get_output("git symbolic-ref HEAD")
641 branches
= get_output("git for-each-ref --format='%(refname)' 'refs/heads/*'")
643 if current
and b
== current
[0]:
647 b
= b
.replace('refs/heads/', '')
650 @short_help("change the current working branch")
652 The argument is the name of the branch to make the current working
653 branch. This command will fail if there are uncommitted changes to any
654 files. Otherwise, the contents of the files in the working directory
655 are updated to reflect their state in the new branch. Additionally, any
656 future commits are added to the new branch instead of the previous line
660 def cmd_switch(self
, branch
, **flags
):
663 self
._check
_rebasing
()
664 ref
= get_output("git rev-parse --verify 'refs/heads/%s'" % branch
)
666 raise YapError("No such branch: %s" % branch
)
668 if '-f' not in flags
and (self
._get
_unstaged
_files
() or self
._get
_staged
_files
()):
669 raise YapError("You have uncommitted changes. Use -f to continue anyway")
671 if self
._get
_unstaged
_files
() and self
._get
_staged
_files
():
672 raise YapError("You have staged and unstaged changes. Perhaps unstage -a?")
674 staged
= bool(self
._get
_staged
_files
())
676 run_command("git diff-files -p | git apply --cached")
677 for f
in self
._get
_new
_files
():
680 idx
= get_output("git write-tree")
681 new
= get_output("git rev-parse refs/heads/%s" % branch
)
682 if os
.system("git read-tree --aggressive -u -m HEAD %s %s" % (idx
[0], new
[0])):
683 raise YapError("Failed to switch")
684 run_safely("git symbolic-ref HEAD refs/heads/%s" % branch
)
690 @short_help("move the current branch to a different revision")
692 The argument is the hash of the commit to which the current branch
693 should point, or alternately a branch or tag (a.k.a, "committish"). If
694 moving the branch would create "dangling commits" (see 'branch'), yap
695 will report an error and abort. The '-f' flag can be used to force the
696 operation in spite of this.
699 def cmd_point(self
, where
, **flags
):
702 self
._check
_rebasing
()
704 head
= get_output("git rev-parse --verify HEAD")
706 raise YapError("No commit yet; nowhere to point")
708 ref
= get_output("git rev-parse --verify '%s'" % where
)
710 raise YapError("Not a valid ref: %s" % where
)
712 if self
._get
_unstaged
_files
() or self
._get
_staged
_files
():
713 raise YapError("You have uncommitted changes. Commit them first")
715 type = get_output("git cat-file -t '%s'" % ref
[0])
716 if type and type[0] == "tag":
717 tag
= get_output("git cat-file tag '%s'" % ref
[0])
718 ref
[0] = tag
[0].split(' ')[1]
720 run_safely("git update-ref HEAD '%s'" % ref
[0])
722 if '-f' not in flags
:
723 name
= get_output("git name-rev --name-only '%s'" % head
[0])[0]
724 if name
== "undefined":
725 os
.system("git update-ref HEAD '%s'" % head
[0])
726 raise YapError("Pointing there will lose commits. Use -f to force")
729 run_safely("git read-tree -u -m HEAD")
731 run_safely("git read-tree HEAD")
732 run_safely("git checkout-index -u -f -a")
734 @short_help("alter history by dropping or amending commits")
736 This command operates in two distinct modes, "amend" and "drop" mode.
737 In drop mode, the given commit is removed from the history of the
738 current branch, as though that commit never happened. By default the
741 In amend mode, the uncommitted changes present are merged into a
742 previous commit. This is useful for correcting typos or adding missed
743 files into past commits. By default the commit used is HEAD.
745 While rewriting history it is possible that conflicts will arise. If
746 this happens, the rewrite will pause and you will be prompted to resolve
747 the conflicts and stage them. Once that is done, you will run "yap
748 history continue." If instead you want the conflicting commit removed
749 from history (perhaps your changes supercede that commit) you can run
750 "yap history skip". Once the rewrite completes, your branch will be on
751 the same commit as when the rewrite started.
753 def cmd_history(self
, subcmd
, *args
):
754 "amend | drop <commit>"
757 if subcmd
not in ("amend", "drop", "continue", "skip"):
761 When you have resolved the conflicts run \"yap history continue\".
762 To skip the problematic patch, run \"yap history skip\"."""
764 if subcmd
== "continue":
765 os
.system("git am -3 -r --resolvemsg='%s'" % resolvemsg
)
768 os
.system("git reset --hard")
769 os
.system("git am -3 --skip --resolvemsg='%s'" % resolvemsg
)
772 if subcmd
== "amend":
773 flags
, args
= getopt
.getopt(args
, "ad")
783 if run_command("git rev-parse --verify '%s'" % commit
):
784 raise YapError("Not a valid commit: %s" % commit
)
786 self
._check
_rebasing
()
788 if subcmd
== "amend":
789 self
._check
_commit
(**flags
)
790 if self
._get
_unstaged
_files
():
791 # XXX: handle unstaged changes better
792 raise YapError("Commit away changes that you aren't amending")
796 start
= get_output("git rev-parse HEAD")
797 stash
= get_output("git stash create")
798 run_command("git reset --hard")
800 fd
, tmpfile
= tempfile
.mkstemp("yap")
804 os
.system("git format-patch -k --stdout '%s' > %s" % (commit
, tmpfile
))
805 if subcmd
== "amend":
806 self
.cmd_point(commit
, **{'-f': True})
808 if subcmd
== "amend":
810 rc
= os
.system("git stash apply %s" % stash
[0])
812 self
.cmd_point(start
[0], **{'-f': True})
813 os
.system("git stash apply %s" % stash
[0])
814 raise YapError("Failed to apply stash")
817 if subcmd
== "amend":
819 for f
in self
._get
_unstaged
_files
():
823 self
.cmd_point("%s^" % commit
, **{'-f': True})
825 stat
= os
.stat(tmpfile
)
828 rc
= os
.system("git am -3 --resolvemsg=\'%s\' %s" % (resolvemsg
, tmpfile
))
830 raise YapError("Failed to apply changes")
835 run_command("git stash apply %s" % stash
[0])
838 @short_help("show the changes introduced by a given commit")
840 By default, the changes in the last commit are shown. To override this,
841 specify a hash, branch, or tag (committish). The hash of the commit,
842 the commit's author, log message, and a diff of the changes are shown.
844 def cmd_show(self
, commit
="HEAD"):
847 os
.system("git show '%s'" % commit
)
849 @short_help("apply the changes in a given commit to the current branch")
851 The argument is the hash, branch, or tag (committish) of the commit to
852 be applied. In general, it only makes sense to apply commits that
853 happened on another branch. The '-r' flag can be used to have the
854 changes in the given commit reversed from the current branch. In
855 general, this only makes sense for commits that happened on the current
859 def cmd_cherry_pick(self
, commit
, **flags
):
863 os
.system("git revert '%s'" % commit
)
865 os
.system("git cherry-pick '%s'" % commit
)
867 @short_help("list, add, or delete configured remote repositories")
869 When invoked with no arguments, this command will show the list of
870 currently configured remote repositories, giving both the name and URL
871 of each. To add a new repository, give the desired name as the first
872 argument and the URL as the second. The '-d' flag can be used to remove
873 a previously added repository.
876 def cmd_repo(self
, name
=None, url
=None, **flags
):
877 "[<name> <url> | -d <name>]"
879 if name
is not None and url
is None:
883 if flags
['-d'] not in [ x
[0] for x
in self
._list
_remotes
() ]:
884 raise YapError("No such repository: %s" % flags
['-d'])
885 os
.system("git config --unset remote.%s.url" % flags
['-d'])
886 os
.system("git config --unset remote.%s.fetch" % flags
['-d'])
889 if name
in [ x
[0] for x
in self
._list
_remotes
() ]:
890 raise YapError("Repository '%s' already exists" % flags
['-d'])
891 os
.system("git config remote.%s.url %s" % (name
, url
))
892 os
.system("git config remote.%s.fetch +refs/heads/*:refs/remotes/%s/*" % (name
, name
))
894 for remote
, url
in self
._list
_remotes
():
895 print "%-20s %s" % (remote
, url
)
897 @short_help("send local commits to a remote repository")
899 When invoked with no arguments, the current branch is synchronized to
900 the tracking branch of the tracking remote. If no tracking remote is
901 specified, the repository will have to be specified on the command line.
902 In that case, the default is to push to a branch with the same name as
903 the current branch. This behavior can be overridden by giving a second
904 argument to specify the remote branch.
906 If the remote branch does not currently exist, the command will abort
907 unless the -c flag is provided. If the remote branch is not a direct
908 descendent of the local branch, the command will abort unless the -f
909 flag is provided. Forcing a push in this way can be problematic to
910 other users of the repository if they are not expecting it.
912 To delete a branch on the remote repository, use the -d flag.
914 @takes_options("cdf")
915 def cmd_push(self
, repo
=None, rhs
=None, **flags
):
918 if '-c' in flags
and '-d' in flags
:
921 if repo
and repo
not in [ x
[0] for x
in self
._list
_remotes
() ]:
922 raise YapError("No such repository: %s" % repo
)
924 current
= get_output("git symbolic-ref HEAD")
926 raise YapError("Not on a branch!")
928 self
._check
_rebasing
()
930 current
= current
[0].replace('refs/heads/', '')
931 remote
= get_output("git config branch.%s.remote" % current
)
932 if repo
is None and remote
:
936 raise YapError("No tracking branch configured; specify destination repository")
938 if rhs
is None and remote
and remote
[0] == repo
:
939 merge
= get_output("git config branch.%s.merge" % current
)
944 rhs
= "refs/heads/%s" % current
946 if '-c' not in flags
and '-d' not in flags
:
947 if run_command("git rev-parse --verify refs/remotes/%s/%s"
948 % (repo
, rhs
.replace('refs/heads/', ''))):
949 raise YapError("No matching branch on that repo. Use -c to create a new branch there.")
950 if '-f' not in flags
:
951 hash = get_output("git rev-parse refs/remotes/%s/%s" % (repo
, rhs
.replace('refs/heads/', '')))
952 base
= get_output("git merge-base HEAD %s" % hash[0])
954 if base
[0] != hash[0]:
955 raise YapError("Branch not up-to-date with remote. Update or use -f")
957 print "About to push local branch '%s' to '%s' on '%s'" % (current
, rhs
, repo
)
958 print "Continue (y/n)? ",
960 ans
= sys
.stdin
.readline().strip()
962 if ans
.lower() != 'y' and ans
.lower() != 'yes':
963 raise YapError("Aborted.")
971 lhs
= "refs/heads/%s" % current
972 rc
= os
.system("git push %s %s %s:%s" % (flags
.get('-f', ''), repo
, lhs
, rhs
))
974 raise YapError("Push failed.")
976 @short_help("retrieve commits from a remote repository")
978 When run with no arguments, the command will retrieve new commits from
979 the remote tracking repository. Note that this does not in any way
980 alter the current branch. For that, see "update". If a remote other
981 than the tracking remote is desired, it can be specified as the first
984 def cmd_fetch(self
, repo
=None):
987 if repo
and repo
not in [ x
[0] for x
in self
._list
_remotes
() ]:
988 raise YapError("No such repository: %s" % repo
)
990 remote
= get_output("git config branch.%s.remote" % current
)
993 raise YapError("No tracking branch configured; specify a repository")
994 os
.system("git fetch %s" % repo
)
996 @short_help("update the current branch relative to its tracking branch")
998 Updates the current branch relative to its remote tracking branch. This
999 command requires that the current branch have a remote tracking branch
1000 configured. If any conflicts occur while applying your changes to the
1001 updated remote, the command will pause to allow you to fix them. Once
1002 that is done, run "update" with the "continue" subcommand. Alternately,
1003 the "skip" subcommand can be used to discard the conflicting changes.
1005 def cmd_update(self
, subcmd
=None):
1008 if subcmd
and subcmd
not in ["continue", "skip"]:
1012 When you have resolved the conflicts run \"yap update continue\".
1013 To skip the problematic patch, run \"yap update skip\"."""
1015 if subcmd
== "continue":
1016 os
.system("git am -3 -r --resolvemsg='%s'" % resolvemsg
)
1018 if subcmd
== "skip":
1019 os
.system("git reset --hard")
1020 os
.system("git am -3 --skip --resolvemsg='%s'" % resolvemsg
)
1023 self
._check
_rebasing
()
1024 if self
._get
_unstaged
_files
() or self
._get
_staged
_files
():
1025 raise YapError("You have uncommitted changes. Commit them first")
1027 current
= get_output("git symbolic-ref HEAD")
1029 raise YapError("Not on a branch!")
1031 current
= current
[0].replace('refs/heads/', '')
1032 remote
, merge
= self
._get
_tracking
(current
)
1033 merge
= merge
[0].replace('refs/heads/', '')
1035 self
.cmd_fetch(remote
)
1036 base
= get_output("git merge-base HEAD refs/remotes/%s/%s" % (remote
, merge
))
1039 fd
, tmpfile
= tempfile
.mkstemp("yap")
1041 os
.system("git format-patch -k --stdout '%s' > %s" % (base
[0], tmpfile
))
1042 self
.cmd_point("refs/remotes/%s/%s" % (remote
, merge
), **{'-f': True})
1044 stat
= os
.stat(tmpfile
)
1047 rc
= os
.system("git am -3 --resolvemsg=\'%s\' %s" % (resolvemsg
, tmpfile
))
1049 raise YapError("Failed to apply changes")
1053 @short_help("query and configure remote branch tracking")
1055 When invoked with no arguments, the command displays the tracking
1056 information for the current branch. To configure the tracking
1057 information, two arguments for the remote repository and remote branch
1058 are given. The tracking information is used to provide defaults for
1059 where to push local changes and from where to get updates to the branch.
1061 def cmd_track(self
, repo
=None, branch
=None):
1065 current
= get_output("git symbolic-ref HEAD")
1067 raise YapError("Not on a branch!")
1068 current
= current
[0].replace('refs/heads/', '')
1070 if repo
is None and branch
is None:
1071 repo
, merge
= self
._get
_tracking
(current
)
1072 merge
= merge
[0].replace('refs/heads/', '')
1073 print "Branch '%s' tracking refs/remotes/%s/%s" % (current
, repo
, merge
)
1076 if repo
is None or branch
is None:
1079 if repo
not in [ x
[0] for x
in self
._list
_remotes
() ]:
1080 raise YapError("No such repository: %s" % repo
)
1082 if run_command("git rev-parse --verify refs/remotes/%s/%s" % (repo
, branch
)):
1083 raise YapError("No such branch '%s' on repository '%s'" % (repo
, branch
))
1085 os
.system("git config branch.%s.remote '%s'" % (current
, repo
))
1086 os
.system("git config branch.%s.merge 'refs/heads/%s'" % (current
, branch
))
1087 print "Branch '%s' now tracking refs/remotes/%s/%s" % (current
, repo
, branch
)
1089 @short_help("mark files with conflicts as resolved")
1091 The arguments are the files to be marked resolved. When a conflict
1092 occurs while merging changes to a file, that file is marked as
1093 "unmerged." Until the file(s) with conflicts are marked resolved,
1094 commits cannot be made.
1096 def cmd_resolved(self
, *args
):
1103 self
._stage
_one
(f
, True)
1106 def cmd_help(self
, cmd
=None):
1109 attr
= self
.__getattribute
__("cmd_"+cmd
.replace('-', '_'))
1110 except AttributeError:
1111 raise YapError("No such command: %s" % cmd
)
1113 help = attr
.long_help
1114 except AttributeError:
1115 raise YapError("Sorry, no help for '%s'. Ask Steven." % cmd
)
1117 print >>sys
.stderr
, "The '%s' command" % cmd
1118 print >>sys
.stderr
, "\tyap %s %s" % (cmd
, attr
.__doc
__)
1119 print >>sys
.stderr
, "%s" % help
1122 print >> sys
.stderr
, "Yet Another (Git) Porcelein"
1125 for name
in dir(self
):
1126 if not name
.startswith('cmd_'):
1128 attr
= self
.__getattribute
__(name
)
1129 if not callable(attr
):
1132 short_msg
= attr
.short_help
1133 except AttributeError:
1136 name
= name
.replace('cmd_', '')
1137 name
= name
.replace('_', '-')
1138 print >> sys
.stderr
, "%-16s%s" % (name
, short_msg
)
1140 print >> sys
.stderr
, "(*) Indicates that the command is not readily reversible"
1142 def cmd_usage(self
):
1143 print >> sys
.stderr
, "usage: %s <command>" % os
.path
.basename(sys
.argv
[0])
1144 print >> sys
.stderr
, " valid commands: help init clone add rm stage unstage status revert commit uncommit log show diff branch switch point cherry-pick repo track push fetch update history resolved version"
1146 def main(self
, args
):
1154 if run_command("git --version"):
1155 print >>sys
.stderr
, "Failed to run git; is it installed?"
1158 debug
= os
.getenv('YAP_DEBUG')
1161 command
= command
.replace('-', '_')
1164 for p
in self
.plugins
:
1166 meth
= p
.__getattribute
__("cmd_"+command
)
1167 except AttributeError:
1171 default_meth
= self
.__getattribute
__("cmd_"+command
)
1172 except AttributeError:
1178 raise AttributeError
1181 if "options" in meth
.__dict
__:
1182 options
= meth
.options
1183 if default_meth
and "options" in default_meth
.__dict
__:
1184 options
+= default_meth
.options
1185 flags
, args
= getopt
.getopt(args
, options
)
1191 for p
in self
.plugins
:
1193 meth
= p
.__getattribute
__("pre_"+command
)
1194 except AttributeError:
1196 meth(*args
, **flags
)
1198 meth(*args
, **flags
)
1201 for p
in self
.plugins
:
1203 meth
= p
.__getattribute
__("post_"+command
)
1204 except AttributeError:
1208 except (TypeError, getopt
.GetoptError
):
1211 print "Usage: %s %s %s" % (os
.path
.basename(sys
.argv
[0]), command
, meth
.__doc
__)
1213 print >> sys
.stderr
, e
1215 except AttributeError: