]> asedeno.scripts.mit.edu Git - git-svn-keywords.git/blob - git-svn-keywords.py
761b10883e10c0b4d4368edb6af4f1145748c471
[git-svn-keywords.git] / git-svn-keywords.py
1 #!/usr/bin/python
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"
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 # Parse the unhandled log.
70 def _do_parse_unhandled(directory, lastrev=None):
71     base = os.path.join(directory)
72     rev = None
73     for d in os.listdir(base):
74         subent = os.path.join(base, d)
75         if (d == 'unhandled.log' and os.path.isfile(subent)):
76             with open(subent, 'r') as f:
77                 # Compile the regular expressions we'll be using here.
78                 re_rev = re.compile("^r(\d+)$")
79                 re_keywords = re.compile("^\s+[-+]file_prop: (\S+) svn:keywords ?(\S*)$")
80
81                 for line in f:
82                     m = re_rev.match(line)
83                     if m:
84                         rev = m.group(1)
85                         continue
86
87                     if (lastrev >= int(rev)):
88                         continue
89
90                     m = re_keywords.match(line)
91                     if m:
92                         path = urllib.unquote(m.group(1))
93                         keywords = set(urllib.unquote(m.group(2)).split(' '))
94                         if not FILES.has_section(path):
95                             FILES.add_section(path)
96                         FILES.set(path, rev, keywords)
97         elif (os.path.isdir(subent)):
98             _do_parse_unhandled(subent, lastrev=lastrev)
99
100     if rev:
101         lastrev = max(int(rev), lastrev)
102     CONFIG.set('core', 'lastrev', lastrev)
103     CONFIG.set('core', 'version', VERSION)
104
105 def parse_svn_unhandled(g):
106     try:
107         os.mkdir(gsk(g))
108     except os.error, e:
109         if e.errno != errno.EEXIST:
110             raise
111
112     ver = -1
113     if CONFIG.has_option('core', 'version'):
114         ver = CONFIG.get('core', 'version')
115
116     lastrev = None
117     if ver == VERSION:
118         FILES.read(FILES_PATH)
119         if CONFIG.has_option('core', 'lastrev'):
120             lastrev = CONFIG.getint('core', 'lastrev')
121
122     _do_parse_unhandled(os.path.join(g.path, 'svn'), lastrev=lastrev)
123
124     with open(FILES_PATH, 'wb') as f:
125         FILES.write(f)
126
127     with open(CONFIG_PATH, 'wb') as f:
128         CONFIG.write(f)
129
130 def get_path_info(g, path):
131     write_config = False
132
133     # parse ls-tree output and get a blob id for path
134     blob = g.git.ls_tree('HEAD', path).split(' ')[2].split("\t")[0]
135
136     # translate that to a commit id
137     if not CONFIG.has_option('BlobToCommit', blob):
138         CONFIG.set('BlobToCommit', blob, g.commits('HEAD', path, 1)[0].id)
139         write_config = True
140     commit = CONFIG.get('BlobToCommit', blob)
141
142     # tranlsate that into an svn revision id
143     if not CONFIG.has_option('CommitToRev', commit):
144         CONFIG.set('CommitToRev',commit,g.git.svn('find-rev', commit))
145         write_config = True
146     file_rev = CONFIG.get('CommitToRev', commit)
147
148     # get information about that revision
149     info_dict = {}
150     if not CONFIG.has_option('RevInfo', file_rev):
151         for line in g.git.svn('info', path).split("\n"):
152             k, v = line.split(": ", 1)
153             if k == 'Last Changed Date':
154                 info_dict['Date'] = v
155             elif k == 'Last Changed Author':
156                 info_dict['Author'] = v
157         CONFIG.set('RevInfo', file_rev, info_dict)
158         write_config = True
159     else:
160         info = CONFIG.get('RevInfo', file_rev)
161         info_dict.update(info if type(info) is dict else eval(info))
162
163     if write_config:
164         with open(CONFIG_PATH, 'wb') as f:
165             CONFIG.write(f)
166
167     info_dict['Revision'] = file_rev
168     return info_dict
169
170 def find_last_svn_rev(treeish, parent=0):
171     svnRev = g.git.svn('find-rev', "%s~%i" % (treeish, parent))
172     if svnRev:
173         return int(svnRev)
174     else:
175         return find_last_svn_rev(treeish, parent+1)
176
177 # Do the work.
178 def smudge(g, options):
179     parse_svn_unhandled(g)
180     rev_head = find_last_svn_rev('HEAD')
181     url_base = g.git.svn('info', '--url')
182
183     FILES.read(FILES_PATH)
184     FILEINFO.read(FILEINFO_PATH)
185
186     ignores = []
187     with open(os.path.join(g.wd,'.git','info','exclude')) as f:
188         for line in f:
189             if line[0] != '#':
190                 ignores.append(line.rstrip('\n'))
191
192     paths = FILES.sections()
193     paths.sort()
194     for path in paths:
195         if not os.path.exists(path):
196             continue
197
198         ignore = False
199         for i in ignores:
200             if fnmatch(path, i):
201                 ignore = True
202         if ignore:
203             continue
204         try:
205             kw_rev = max(filter(lambda x: x <= rev_head, map(int, FILES.options(path))))
206         except ValueError:
207             continue
208
209         info_dict = {}
210         if not options.clean:
211             info_dict.update(get_path_info(g, path))
212             info_dict['URL'] = '/'.join([url_base, path])
213             info_dict['Name'] = os.path.basename(path)
214             info_dict['Revision'] = str(max(kw_rev, info_dict['Revision']))
215
216         buf = ''
217         with open(os.path.join(g.wd, path), 'r') as f:
218             buf = f.read()
219
220         keywords = eval(FILES.get(path, str(kw_rev)))
221         for k in keywords:
222             for sk in svn_keywords:
223                 if k in svn_keywords[sk]:
224                     if options.clean:
225                         buf = re.sub(get_svn_keyword_re(sk), '$\\1$', buf)
226                     elif sk == 'Id':
227                         id_str = ' '.join([info_dict['Name'],
228                                            info_dict['Revision'],
229                                            info_dict['Date'],
230                                            info_dict['Author']])
231                         buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + id_str + ' $', buf)
232                     else:
233                         buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + info_dict[sk] + ' $', buf)
234
235         with open(os.path.join(g.wd, path), 'w') as f:
236             f.write(buf)
237         if options.verbose:
238             print path + ' [' + ', '.join(keywords) + '] [len: ' + str(len(buf)) +']'
239
240 if __name__ == '__main__':
241
242     parser = OptionParser(version="%prog "+str(VERSION))
243     parser.set_defaults(clean=None)
244     parser.add_option("-s", "--smudge",
245                       action="store_false", dest="clean",
246                       help="Populate svn:keywords.")
247     parser.add_option("-c", "--clean",
248                       action="store_true", dest="clean",
249                       help="Return svn:keywords to pristene state.")
250     parser.add_option("-v", "--verbose",
251                       action="store_true", dest="verbose", default=False)
252     (options, args) = parser.parse_args()
253
254     if (options.clean is None):
255         parser.print_help()
256         exit(0)
257     else:
258         try:
259             g = git.Repo()
260         except git.errors.InvalidGitRepositoryError:
261             print "You are not in a git repository or working directory."
262             exit(1)
263
264         CONFIG_PATH = os.path.join(gsk(g), 'conf.ini')
265         FILES_PATH = os.path.join(gsk(g), 'files.ini')
266         FILEINFO_PATH = os.path.join(gsk(g), 'fileinfo.ini')
267
268         CONFIG.read(CONFIG_PATH)
269         for section in ['core','CommitToRev','BlobToCommit', 'RevInfo']:
270             if not CONFIG.has_section(section):
271                 CONFIG.add_section(section)
272
273         smudge(g, options)