chiark / gitweb /
8424f9de80145bc5ac04006b580e272bcc946a2e
[stgit] / stgit / commands / export.py
1 """Export command
2 """
3
4 __copyright__ = """
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 import sys, os
22 from optparse import OptionParser, make_option
23
24 from stgit.commands.common import *
25 from stgit.utils import *
26 from stgit import stack, git, templates
27
28
29 help = 'exports patches to a directory'
30 usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
31
32 Export a range of applied patches to a given directory (defaults to
33 'patches-<branch>') in a standard unified GNU diff format. A template
34 file (defaulting to '.git/patchexport.tmpl' or
35 '~/.stgit/templates/patchexport.tmpl' or
36 '/usr/share/stgit/templates/patchexport.tmpl') can be used for the
37 patch format. The following variables are supported in the template
38 file:
39
40   %(description)s - patch description
41   %(shortdescr)s  - the first line of the patch description
42   %(longdescr)s   - the rest of the patch description, after the first line
43   %(diffstat)s    - the diff statistics
44   %(authname)s    - author's name
45   %(authemail)s   - author's e-mail
46   %(authdate)s    - patch creation date
47   %(commname)s    - committer's name
48   %(commemail)s   - committer's e-mail
49 """
50
51 options = [make_option('-d', '--dir',
52                        help = 'export patches to DIR instead of the default'),
53            make_option('-p', '--patch',
54                        help = 'append .patch to the patch names',
55                        action = 'store_true'),
56            make_option('-e', '--extension',
57                        help = 'append .EXTENSION to the patch names'),
58            make_option('-n', '--numbered',
59                        help = 'prefix the patch names with order numbers',
60                        action = 'store_true'),
61            make_option('-t', '--template', metavar = 'FILE',
62                        help = 'Use FILE as a template'),
63            make_option('-b', '--branch',
64                        help = 'use BRANCH instead of the default one'),
65            make_option('-O', '--diff-opts',
66                        help = 'options to pass to git-diff'),
67            make_option('-s', '--stdout',
68                        help = 'dump the patches to the standard output',
69                        action = 'store_true')]
70
71
72 def func(parser, options, args):
73     """Export a range of patches.
74     """
75     if options.dir:
76         dirname = options.dir
77     else:
78         dirname = 'patches-%s' % crt_series.get_name()
79
80     if not options.branch and git.local_changes():
81         out.warn('Local changes in the tree;'
82                  ' you might want to commit them first')
83
84     if not options.stdout:
85         if not os.path.isdir(dirname):
86             os.makedirs(dirname)
87         series = file(os.path.join(dirname, 'series'), 'w+')
88
89     if options.diff_opts:
90         diff_flags = options.diff_opts.split()
91     else:
92         diff_flags = []
93
94     applied = crt_series.get_applied()
95     if len(args) != 0:
96         patches = parse_patches(args, applied)
97     else:
98         patches = applied
99
100     num = len(patches)
101     if num == 0:
102         raise CmdException, 'No patches applied'
103
104     zpadding = len(str(num))
105     if zpadding < 2:
106         zpadding = 2
107
108     # get the template
109     if options.template:
110         tmpl = file(options.template).read()
111     else:
112         tmpl = templates.get_template('patchexport.tmpl')
113         if not tmpl:
114             tmpl = ''
115
116     # note the base commit for this series
117     if not options.stdout:
118         base_commit = crt_series.get_patch(patches[0]).get_bottom()
119         print >> series, '# This series applies on GIT commit %s' % base_commit
120
121     patch_no = 1;
122     for p in patches:
123         pname = p
124         if options.patch:
125             pname = '%s.patch' % pname
126         elif options.extension:
127             pname = '%s.%s' % (pname, options.extension)
128         if options.numbered:
129             pname = '%s-%s' % (str(patch_no).zfill(zpadding), pname)
130         pfile = os.path.join(dirname, pname)
131         if not options.stdout:
132             print >> series, pname
133
134         # get the patch description
135         patch = crt_series.get_patch(p)
136
137         descr = patch.get_description().strip()
138         descr_lines = descr.split('\n')
139
140         short_descr = descr_lines[0].rstrip()
141         long_descr = reduce(lambda x, y: x + '\n' + y,
142                             descr_lines[1:], '').strip()
143
144         tmpl_dict = {'description': patch.get_description().rstrip(),
145                      'shortdescr': short_descr,
146                      'longdescr': long_descr,
147                      'diffstat': git.diffstat(rev1 = patch.get_bottom(),
148                                               rev2 = patch.get_top()),
149                      'authname': patch.get_authname(),
150                      'authemail': patch.get_authemail(),
151                      'authdate': patch.get_authdate(),
152                      'commname': patch.get_commname(),
153                      'commemail': patch.get_commemail()}
154         for key in tmpl_dict:
155             if not tmpl_dict[key]:
156                 tmpl_dict[key] = ''
157
158         try:
159             descr = tmpl % tmpl_dict
160         except KeyError, err:
161             raise CmdException, 'Unknown patch template variable: %s' \
162                   % err
163         except TypeError:
164             raise CmdException, 'Only "%(name)s" variables are ' \
165                   'supported in the patch template'
166
167         if options.stdout:
168             f = sys.stdout
169         else:
170             f = open(pfile, 'w+')
171
172         if options.stdout and num > 1:
173             print '-'*79
174             print patch.get_name()
175             print '-'*79
176
177         # write description
178         f.write(descr)
179         # write the diff
180         git.diff(rev1 = patch.get_bottom(),
181                  rev2 = patch.get_top(),
182                  out_fd = f,
183                  diff_flags = diff_flags )
184         if not options.stdout:
185             f.close()
186         patch_no += 1
187
188     if not options.stdout:
189         series.close()