Add support for initializing a branch for stgit from Emacs.
[stgit] / stgit / commands / export.py
index ea349c3..fb373a9 100644 (file)
@@ -18,20 +18,20 @@ 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 os
+from optparse import make_option
 
-from stgit.commands.common import *
-from stgit.utils import *
-from stgit import stack, git, templates
+from stgit.commands import common
+from stgit import argparse, git, templates
+from stgit.out import out
+from stgit.lib import git as gitlib
 
+help = 'exports patches to a directory'
+usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
 
-help = 'exports a series of patches to <dir> (or patches)'
-usage = """%prog [options] [<dir>]
-
-Export the applied patches into a given directory (defaults to
-'patches') in a standard unified GNU diff format. A template file
-(defaulting to '.git/patchexport.tmpl' or
+Export a range of applied patches to a given directory (defaults to
+'patches-<branch>') in a standard unified GNU diff format. A template
+file (defaulting to '.git/patchexport.tmpl' or
 '~/.stgit/templates/patchexport.tmpl' or
 '/usr/share/stgit/templates/patchexport.tmpl') can be used for the
 patch format. The following variables are supported in the template
@@ -46,57 +46,58 @@ file:
   %(authdate)s    - patch creation date
   %(commname)s    - committer's name
   %(commemail)s   - committer's e-mail
+"""
 
-'export' can also generate a diff for a range of patches."""
-
-options = [make_option('-n', '--numbered',
-                       help = 'prefix the patch names with order numbers',
-                       action = 'store_true'),
-           make_option('-d', '--diff',
-                       help = 'append .diff to the patch names',
-                       action = 'store_true'),
+directory = common.DirectoryHasRepositoryLib()
+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('-r', '--range',
-                       metavar = '[PATCH1][..[PATCH2]]',
-                       help = 'export patches between PATCH1 and PATCH2'),
            make_option('-b', '--branch',
                        help = 'use BRANCH instead of the default one'),
            make_option('-s', '--stdout',
                        help = 'dump the patches to the standard output',
-                       action = 'store_true')]
-
+                       action = 'store_true')
+           ] + argparse.diff_opts_option()
 
 def func(parser, options, args):
-    if len(args) == 0:
-        dirname = 'patches-%s' % crt_series.get_branch()
-    elif len(args) == 1:
-        dirname = args[0]
+    """Export a range of patches.
+    """
+    stack = directory.repository.get_stack(options.branch)
+
+    if options.dir:
+        dirname = options.dir
     else:
-        parser.error('incorrect number of arguments')
+        dirname = 'patches-%s' % stack.name
+        directory.cd_to_topdir()
 
     if not options.branch and git.local_changes():
-        print 'Warning: local changes in the tree. ' \
-              'You might want to commit them first'
+        out.warn('Local changes in the tree;'
+                 ' you might want to commit them first')
 
     if not options.stdout:
         if not os.path.isdir(dirname):
             os.makedirs(dirname)
         series = file(os.path.join(dirname, 'series'), 'w+')
 
-    applied = crt_series.get_applied()
-
-    if options.range:
-        patches = parse_patches([options.range], applied)
+    applied = stack.patchorder.applied
+    unapplied = stack.patchorder.unapplied
+    if len(args) != 0:
+        patches = common.parse_patches(args, applied + unapplied, len(applied))
     else:
         patches = applied
 
     num = len(patches)
     if num == 0:
-        raise CmdException, 'No patches applied'
+        raise common.CmdException, 'No patches applied'
 
     zpadding = len(str(num))
     if zpadding < 2:
@@ -112,16 +113,16 @@ 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;
     for p in patches:
         pname = p
-        if options.diff:
-            pname = '%s.diff' % pname
-        elif options.patch:
+        if options.patch:
             pname = '%s.patch' % pname
+        elif options.extension:
+            pname = '%s.%s' % (pname, options.extension)
         if options.numbered:
             pname = '%s-%s' % (str(patch_no).zfill(zpadding), pname)
         pfile = os.path.join(dirname, pname)
@@ -129,25 +130,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': git.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] = ''
@@ -155,10 +158,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:
@@ -167,16 +170,12 @@ def func(parser, options, args):
             f = open(pfile, 'w+')
 
         if options.stdout and num > 1:
-            print '-------------------------------------------------------------------------------'
-            print patch.get_name()
-            print '-------------------------------------------------------------------------------'
+            print '-'*79
+            print patch.name
+            print '-'*79
 
-        # write description
         f.write(descr)
-        # write the diff
-        git.diff(rev1 = patch.get_bottom(),
-                 rev2 = patch.get_top(),
-                 out_fd = f)
+        f.write(diff)
         if not options.stdout:
             f.close()
         patch_no += 1