]> asedeno.scripts.mit.edu Git - git-svn-keywords.git/blob - git-svn-keywords.py
Detect bare repositories and path in working directory
[git-svn-keywords.git] / git-svn-keywords.py
1 #!/usr/bin/python2.6
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2009 Alejandro R. SedeƱo <asedeno@mit.edu>
5
6 # Permission is hereby granted, free of charge, to any person
7 # obtaining a copy of this software and associated documentation files
8 # (the "Software"), to deal in the Software without restriction,
9 # including without limitation the rights to use, copy, modify, merge,
10 # publish, distribute, sublicense, and/or sell copies of the Software,
11 # and to permit persons to whom the Software is furnished to do so,
12 # subject to the following conditions:
13
14 # The above copyright notice and this permission notice shall be
15 # included in all copies or substantial portions of the Software.
16
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 # SOFTWARE.
25
26 # git svn keyword parsing, populating, and clearing.
27
28 from __future__ import with_statement
29 import errno, os, re, urllib
30 from ConfigParser import ConfigParser
31 from optparse import OptionParser
32 from fnmatch import fnmatch
33 import git
34
35 VERSION = "0.9.1"
36
37 # Where we keep data in the repo.
38 def gsk(g):
39     return os.path.join(g.path, 'svn_keywords')
40
41 #Configuration Data
42 CONFIG = ConfigParser()
43 FILES = ConfigParser()
44 FILEINFO = ConfigParser()
45
46 CONFIG_PATH = ''
47 FILES_PATH = ''
48 FILEINFO_PATH = ''
49
50
51 # Valid keywords:
52 svn_keywords = {'Date': ['Date', 'LastDateChanged'],
53                 'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
54                 'Author': ['Author','LastChangedBy'],
55                 'URL': ['HeadURL', 'URL'],
56                 'Id': ['Id']
57                 }
58
59 # Regular expressions we'll be using to smudge/clean; created as
60 # needed and cached.
61 svn_keywords_re = {}
62 def get_svn_keyword_re(s):
63     if not s in svn_keywords:
64         raise 'Invalid SVN Keyword'
65     if not s in svn_keywords_re:
66         svn_keywords_re[s] = re.compile('\$(' + ('|'.join(svn_keywords[s])) + ')[^$]*\$')
67     return svn_keywords_re[s]
68
69 def conf_right_version():
70     ver = -1
71     if CONFIG.has_option('core', 'version'):
72         ver = CONFIG.get('core', 'version')
73     return ver == VERSION
74
75 def read_file_data():
76     if conf_right_version():
77         FILES.read(FILES_PATH)
78
79 def get_last_rev(path):
80     if not CONFIG.has_section(path):
81         CONFIG.add_section(path)
82
83     lastrev = None
84     if conf_right_version() and CONFIG.has_option(path, 'lastrev'):
85         try:
86             lastrev = CONFIG.getint(path, 'lastrev')
87         except ValueError:
88             lastrev = None
89     return lastrev
90
91
92 # Parse the unhandled log.
93 def _do_parse_unhandled(directory):
94     base = os.path.join(directory)
95     for d in os.listdir(base):
96         subent = os.path.join(base, d)
97         if (d == 'unhandled.log' and os.path.isfile(subent)):
98             rev = None
99             strip_prefix = g.git.config('--get','svn-remote.svn.fetch').split(':')[0]
100             lastrev = get_last_rev(subent)
101             with open(subent, 'r') as f:
102                 # Compile the regular expressions we'll be using here.
103                 re_rev = re.compile("^r(\d+)$")
104                 re_keywords = re.compile("^\s+[-+]file_prop: (\S+) svn:keywords ?(\S*)$")
105
106                 for line in f:
107                     m = re_rev.match(line)
108                     if m:
109                         rev = m.group(1)
110                         continue
111
112                     if (lastrev >= int(rev)):
113                         continue
114
115                     m = re_keywords.match(line)
116                     if m:
117                         path = urllib.unquote(m.group(1))
118                         path = os.path.relpath(path, strip_prefix)
119                         keywords = set(urllib.unquote(m.group(2)).split(' '))
120                         if not FILES.has_section(path):
121                             FILES.add_section(path)
122                         FILES.set(path, rev, keywords)
123             if rev:
124                 lastrev = max(int(rev), lastrev)
125                 CONFIG.set(subent, 'lastrev', lastrev)
126         elif (os.path.isdir(subent)):
127             _do_parse_unhandled(subent)
128
129 def parse_svn_unhandled(g):
130     try:
131         os.mkdir(gsk(g))
132     except os.error, e:
133         if e.errno != errno.EEXIST:
134             raise
135
136     _do_parse_unhandled(os.path.join(g.path, 'svn'))
137     CONFIG.set('core', 'version', VERSION)
138
139     with open(FILES_PATH, 'wb') as f:
140         FILES.write(f)
141
142     with open(CONFIG_PATH, 'wb') as f:
143         CONFIG.write(f)
144
145 def get_path_info(g, path):
146     write_config = False
147
148     # parse ls-tree output and get a blob id for path
149     blob = g.git.ls_tree('HEAD', path).split(' ')[2].split("\t")[0]
150
151     # translate that to a commit id
152     if not CONFIG.has_option('BlobToCommit', blob):
153         CONFIG.set('BlobToCommit', blob, g.commits('HEAD', path, 1)[0].id)
154         write_config = True
155     commit = CONFIG.get('BlobToCommit', blob)
156
157     # tranlsate that into an svn revision id
158     if not CONFIG.has_option('CommitToRev', commit):
159         CONFIG.set('CommitToRev',commit,g.git.svn('find-rev', commit))
160         write_config = True
161     file_rev = CONFIG.get('CommitToRev', commit)
162
163     # get information about that revision
164     info_dict = {}
165     if not CONFIG.has_option('RevInfo', file_rev):
166         for line in g.git.svn('info', path).split("\n"):
167             k, v = line.split(": ", 1)
168             if k == 'Last Changed Date':
169                 info_dict['Date'] = v
170             elif k == 'Last Changed Author':
171                 info_dict['Author'] = v
172         CONFIG.set('RevInfo', file_rev, info_dict)
173         write_config = True
174     else:
175         info = CONFIG.get('RevInfo', file_rev)
176         info_dict.update(info if type(info) is dict else eval(info))
177
178     if write_config:
179         with open(CONFIG_PATH, 'wb') as f:
180             CONFIG.write(f)
181
182     info_dict['Revision'] = file_rev
183     return info_dict
184
185 def find_last_svn_rev(treeish, parent=0):
186     svnRev = g.git.svn('find-rev', "%s~%i" % (treeish, parent))
187     if svnRev:
188         return int(svnRev)
189     else:
190         return find_last_svn_rev(treeish, parent+1)
191
192 # Do the work.
193 def smudge(g, options):
194     read_file_data()
195     parse_svn_unhandled(g)
196     rev_head = find_last_svn_rev('HEAD')
197     url_base = g.git.svn('info', '--url')
198
199     FILES.read(FILES_PATH)
200     FILEINFO.read(FILEINFO_PATH)
201
202     ignores = []
203     with open(os.path.join(g.wd,'.git','info','exclude')) as f:
204         for line in f:
205             if line[0] != '#':
206                 ignores.append(line.rstrip('\n'))
207
208     paths = FILES.sections()
209     paths.sort()
210     for path in paths:
211         if not os.path.exists(path):
212             continue
213
214         ignore = False
215         for i in ignores:
216             if fnmatch(path, i):
217                 ignore = True
218         if ignore:
219             continue
220         try:
221             kw_rev = max(filter(lambda x: x <= rev_head, map(int, FILES.options(path))))
222         except ValueError:
223             continue
224
225         info_dict = {}
226         if not options.clean:
227             info_dict.update(get_path_info(g, path))
228             info_dict['URL'] = '/'.join([url_base, path])
229             info_dict['Name'] = os.path.basename(path)
230             info_dict['Revision'] = str(max(kw_rev, info_dict['Revision']))
231
232         buf = ''
233         with open(os.path.join(g.wd, path), 'r') as f:
234             buf = f.read()
235
236         keywords = eval(FILES.get(path, str(kw_rev)))
237         for k in keywords:
238             for sk in svn_keywords:
239                 if k in svn_keywords[sk]:
240                     if options.clean:
241                         buf = re.sub(get_svn_keyword_re(sk), '$\\1$', buf)
242                     elif sk == 'Id':
243                         id_str = ' '.join([info_dict['Name'],
244                                            info_dict['Revision'],
245                                            info_dict['Date'],
246                                            info_dict['Author']])
247                         buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + id_str + ' $', buf)
248                     else:
249                         buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + info_dict[sk] + ' $', buf)
250
251         with open(os.path.join(g.wd, path), 'w') as f:
252             f.write(buf)
253         if options.verbose:
254             print path + ' [' + ', '.join(keywords) + '] [len: ' + str(len(buf)) +']'
255
256 if __name__ == '__main__':
257
258     parser = OptionParser(version="%prog "+str(VERSION))
259     parser.set_defaults(clean=None)
260     parser.add_option("-s", "--smudge",
261                       action="store_false", dest="clean",
262                       help="Populate svn:keywords.")
263     parser.add_option("-c", "--clean",
264                       action="store_true", dest="clean",
265                       help="Return svn:keywords to pristene state.")
266     parser.add_option("-v", "--verbose",
267                       action="store_true", dest="verbose", default=False)
268     (options, args) = parser.parse_args()
269
270     if (options.clean is None):
271         parser.print_help()
272         exit(0)
273     else:
274         try:
275             g = git.Repo()
276         except git.errors.InvalidGitRepositoryError:
277             print "You are not in a git repository or working directory."
278             exit(1)
279
280         if g.bare:
281             print "This appears to be a bare git repository."
282             exit(1)
283
284         os.chdir(g.wd)
285
286         CONFIG_PATH = os.path.join(gsk(g), 'conf.ini')
287         FILES_PATH = os.path.join(gsk(g), 'files.ini')
288         FILEINFO_PATH = os.path.join(gsk(g), 'fileinfo.ini')
289
290         CONFIG.read(CONFIG_PATH)
291         for section in ['core','CommitToRev','BlobToCommit', 'RevInfo']:
292             if not CONFIG.has_section(section):
293                 CONFIG.add_section(section)
294
295         smudge(g, options)