Properly detect that HEAD is detached
[stgit] / stgit / git.py
index cbe7cb5..cc6acb1 100644 (file)
@@ -21,6 +21,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 import sys, os, re, gitmergeonefile
 from shutil import copyfile
 
+from stgit.exception import *
 from stgit import basedir
 from stgit.utils import *
 from stgit.out import *
@@ -28,7 +29,7 @@ from stgit.run import *
 from stgit.config import config
 
 # git exception class
-class GitException(Exception):
+class GitException(StgException):
     pass
 
 # When a subprocess has a problem, we want the exception to be a
@@ -245,11 +246,19 @@ def get_head():
         __head = rev_parse('HEAD')
     return __head
 
+class DetachedHeadException(GitException):
+    def __init__(self):
+        GitException.__init__(self, 'Not on any branch')
+
 def get_head_file():
-    """Returns the name of the file pointed to by the HEAD link
-    """
-    return strip_prefix('refs/heads/',
-                        GRun('git-symbolic-ref', 'HEAD').output_one_line())
+    """Return the name of the file pointed to by the HEAD symref.
+    Throw an exception if HEAD is detached."""
+    try:
+        return strip_prefix(
+            'refs/heads/', GRun('git-symbolic-ref', '-q', 'HEAD'
+                                ).output_one_line())
+    except GitRunException:
+        raise DetachedHeadException()
 
 def set_head_file(ref):
     """Resets HEAD to point to a new ref
@@ -300,7 +309,8 @@ def rev_parse(git_id):
     """Parse the string and return a verified SHA1 id
     """
     try:
-        return GRun('git-rev-parse', '--verify', git_id).output_one_line()
+        return GRun('git-rev-parse', '--verify', git_id
+                    ).discard_stderr().output_one_line()
     except GitRunException:
         raise GitException, 'Unknown revision: %s' % git_id
 
@@ -383,8 +393,11 @@ def rename_ref(from_ref, to_ref):
 def rename_branch(from_name, to_name):
     """Rename a git branch."""
     rename_ref('refs/heads/%s' % from_name, 'refs/heads/%s' % to_name)
-    if get_head_file() == from_name:
-        set_head_file(to_name)
+    try:
+        if get_head_file() == from_name:
+            set_head_file(to_name)
+    except DetachedHeadException:
+        pass # detached HEAD, so the renamee can't be the current branch
     reflog_dir = os.path.join(basedir.get(), 'logs', 'refs', 'heads')
     if os.path.exists(reflog_dir) \
            and os.path.exists(os.path.join(reflog_dir, from_name)):
@@ -711,39 +724,6 @@ def merge(base, head1, head2, recursive = False):
     if errors:
         raise GitException, 'GIT index merging failed (possible conflicts)'
 
-def status(files = None, modified = False, new = False, deleted = False,
-           conflict = False, unknown = False, noexclude = False,
-           diff_flags = []):
-    """Show the tree status
-    """
-    cache_files = tree_status(files,
-                              unknown = (files == None),
-                              noexclude = noexclude,
-                              diff_flags = diff_flags)
-    filtered = (modified or new or deleted or conflict or unknown)
-
-    if filtered:
-        filestat = []
-        if modified:
-            filestat.append('M')
-        if new:
-            filestat.append('A')
-            filestat.append('N')
-        if deleted:
-            filestat.append('D')
-        if conflict:
-            filestat.append('C')
-        if unknown:
-            filestat.append('?')
-        cache_files = [x for x in cache_files if x[0] in filestat]
-
-    for fs in cache_files:
-        assert files == None or fs[1] in files
-        if not filtered:
-            out.stdout('%s %s' % (fs[0], fs[1]))
-        else:
-            out.stdout('%s' % fs[1])
-
 def diff(files = None, rev1 = 'HEAD', rev2 = None, diff_flags = []):
     """Show the diff between rev1 and rev2
     """
@@ -879,6 +859,27 @@ def pull(repository = 'origin', refspec = None):
               config.get('stgit.pullcmd')
     GRun(*(command.split() + args)).run()
 
+def rebase(tree_id = None):
+    """Rebase the current tree to the give tree_id. The tree_id
+    argument may be something other than a GIT id if an external
+    command is invoked.
+    """
+    command = config.get('branch.%s.stgit.rebasecmd' % get_head_file()) \
+                or config.get('stgit.rebasecmd')
+    if tree_id:
+        args = [tree_id]
+    elif command:
+        args = []
+    else:
+        raise GitException, 'Default rebasing requires a commit id'
+    if command:
+        # clear the HEAD cache as the custom rebase command will update it
+        __clear_head_cache()
+        GRun(*(command.split() + args)).run()
+    else:
+        # default rebasing
+        reset(tree_id = tree_id)
+
 def repack():
     """Repack all objects into a single pack
     """
@@ -1015,11 +1016,14 @@ def fetch_head():
         m = re.match('^([^\t]*)\t\t', line)
         if m:
             if fetch_head:
-                raise GitException, "StGit does not support multiple FETCH_HEAD"
+                raise GitException, 'StGit does not support multiple FETCH_HEAD'
             else:
                 fetch_head=m.group(1)
     stream.close()
 
+    if not fetch_head:
+        raise GitException, 'No for-merge remote head found in FETCH_HEAD'
+
     # here we are sure to have a single fetch_head
     return fetch_head