chiark / gitweb /
Create stgit/basedir.py for determining the .git directory
[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, basedir
27
28
29 help = 'exports a series of patches to <dir> (or patches)'
30 usage = """%prog [options] [<dir>]
31
32 Export the applied patches into a given directory (defaults to
33 'patches') in a standard unified GNU diff format. A template file
34 (defaulting to '.git/patchexport.tmpl or
35 /usr/share/stgit/templates/patchexport.tmpl') can be used for the
36 patch format. The following variables are supported in the template
37 file:
38
39   %(description)s - patch description
40   %(shortdescr)s  - the first line of the patch description
41   %(longdescr)s   - the rest of the patch description, after the first line
42   %(diffstat)s    - the diff statistics
43   %(authname)s    - author's name
44   %(authemail)s   - author's e-mail
45   %(authdate)s    - patch creation date
46   %(commname)s    - committer's name
47   %(commemail)s   - committer's e-mail
48
49 'export' can also generate a diff for a range of patches."""
50
51 options = [make_option('-n', '--numbered',
52                        help = 'prefix the patch names with order numbers',
53                        action = 'store_true'),
54            make_option('-d', '--diff',
55                        help = 'append .diff to the patch names',
56                        action = 'store_true'),
57            make_option('-p', '--patch',
58                        help = 'append .patch to the patch names',
59                        action = 'store_true'),
60            make_option('-t', '--template', metavar = 'FILE',
61                        help = 'Use FILE as a template'),
62            make_option('-r', '--range',
63                        metavar = '[PATCH1][:[PATCH2]]',
64                        help = 'export patches between PATCH1 and PATCH2'),
65            make_option('-b', '--branch',
66                        help = 'use BRANCH instead of the default one'),
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     if len(args) == 0:
74         dirname = 'patches-%s' % crt_series.get_branch()
75     elif len(args) == 1:
76         dirname = args[0]
77     else:
78         parser.error('incorrect number of arguments')
79
80     if not options.branch and git.local_changes():
81         print 'Warning: 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     applied = crt_series.get_applied()
90     unapplied = crt_series.get_unapplied()
91
92     if options.range:
93         boundaries = options.range.split(':')
94         if len(boundaries) == 1:
95             start = boundaries[0]
96             stop = boundaries[0]
97         elif len(boundaries) == 2:
98             if boundaries[0] == '':
99                 start = applied[0]
100             else:
101                 start = boundaries[0]
102             if boundaries[1] == '':
103                 stop = applied[-1]
104             else:
105                 stop = boundaries[1]
106         else:
107             raise CmdException, 'incorrect parameters to "--range"'
108
109         if start in applied:
110             start_idx = applied.index(start)
111         else:
112             if start in unapplied:
113                 raise CmdException, 'Patch "%s" not applied' % start
114             else:
115                 raise CmdException, 'Patch "%s" does not exist' % start
116
117         if stop in applied:
118             stop_idx = applied.index(stop) + 1
119         else:
120             if stop in unapplied:
121                 raise CmdException, 'Patch "%s" not applied' % stop
122             else:
123                 raise CmdException, 'Patch "%s" does not exist' % stop
124
125         if start_idx >= stop_idx:
126             raise CmdException, 'Incorrect patch range order'
127     else:
128         start_idx = 0
129         stop_idx = len(applied)
130
131     patches = applied[start_idx:stop_idx]
132
133     num = len(patches)
134     if num == 0:
135         raise CmdException, 'No patches applied'
136
137     zpadding = len(str(num))
138     if zpadding < 2:
139         zpadding = 2
140
141     # get the template
142     if options.template:
143         patch_tmpl_list = [options.template]
144     else:
145         patch_tmpl_list = []
146
147     patch_tmpl_list += [os.path.join(basedir.get(), 'patchexport.tmpl'),
148                         os.path.join(sys.prefix,
149                                      'share/stgit/templates/patchexport.tmpl')]
150     tmpl = ''
151     for patch_tmpl in patch_tmpl_list:
152         if os.path.isfile(patch_tmpl):
153             tmpl = file(patch_tmpl).read()
154             break
155
156     # note the base commit for this series
157     if not options.stdout:
158         base_commit = crt_series.get_patch(patches[0]).get_bottom()
159         print >> series, '# This series applies on GIT commit %s' % base_commit
160
161     patch_no = 1;
162     for p in patches:
163         pname = p
164         if options.diff:
165             pname = '%s.diff' % pname
166         elif options.patch:
167             pname = '%s.patch' % pname
168         if options.numbered:
169             pname = '%s-%s' % (str(patch_no).zfill(zpadding), pname)
170         pfile = os.path.join(dirname, pname)
171         if not options.stdout:
172             print >> series, pname
173
174         # get the patch description
175         patch = crt_series.get_patch(p)
176
177         descr = patch.get_description().strip()
178         descr_lines = descr.split('\n')
179
180         short_descr = descr_lines[0].rstrip()
181         long_descr = reduce(lambda x, y: x + '\n' + y,
182                             descr_lines[1:], '').strip()
183
184         tmpl_dict = {'description': patch.get_description().rstrip(),
185                      'shortdescr': short_descr,
186                      'longdescr': long_descr,
187                      'diffstat': git.diffstat(rev1 = patch.get_bottom(),
188                                               rev2 = patch.get_top()),
189                      'authname': patch.get_authname(),
190                      'authemail': patch.get_authemail(),
191                      'authdate': patch.get_authdate(),
192                      'commname': patch.get_commname(),
193                      'commemail': patch.get_commemail()}
194         for key in tmpl_dict:
195             if not tmpl_dict[key]:
196                 tmpl_dict[key] = ''
197
198         try:
199             descr = tmpl % tmpl_dict
200         except KeyError, err:
201             raise CmdException, 'Unknown patch template variable: %s' \
202                   % err
203         except TypeError:
204             raise CmdException, 'Only "%(name)s" variables are ' \
205                   'supported in the patch template'
206
207         if options.stdout:
208             f = sys.stdout
209         else:
210             f = open(pfile, 'w+')
211
212         if options.stdout and num > 1:
213             print '-------------------------------------------------------------------------------'
214             print patch.get_name()
215             print '-------------------------------------------------------------------------------'
216
217         # write description
218         f.write(descr)
219         # write the diff
220         git.diff(rev1 = patch.get_bottom(),
221                  rev2 = patch.get_top(),
222                  out_fd = f)
223         if not options.stdout:
224             f.close()
225         patch_no += 1
226
227     if not options.stdout:
228         series.close()