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