2 # -*- coding: utf-8 -*-
4 # Copyright (c) 2009 Alejandro R. SedeƱo <asedeno@mit.edu>
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:
14 # The above copyright notice and this permission notice shall be
15 # included in all copies or substantial portions of the Software.
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
26 # git svn keyword parsing, populating, and clearing.
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
37 # Where we keep data in the repo.
39 return os.path.join(g.path, 'svn_keywords')
42 CONFIG = ConfigParser()
43 FILES = ConfigParser()
44 FILEINFO = ConfigParser()
52 svn_keywords = {'Date': ['Date', 'LastDateChanged'],
53 'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
54 'Author': ['Author','LastChangedBy'],
55 'URL': ['HeadURL', 'URL'],
59 # Regular expressions we'll be using to smudge/clean; created as
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]
69 # Parse the unhandled log.
70 def _do_parse_unhandled(directory, lastrev=None):
71 base = os.path.join(directory)
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*)$")
82 m = re_rev.match(line)
87 if (lastrev >= int(rev)):
90 m = re_keywords.match(line)
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)
101 lastrev = max(int(rev), lastrev)
102 CONFIG.set('core', 'lastrev', lastrev)
103 CONFIG.set('core', 'version', VERSION)
105 def parse_svn_unhandled(g):
109 if e.errno != errno.EEXIST:
113 if CONFIG.has_option('core', 'version'):
114 ver = CONFIG.get('core', 'version')
118 FILES.read(FILES_PATH)
119 if CONFIG.has_option('core', 'lastrev'):
121 lastrev = CONFIG.getint('core', 'lastrev')
125 _do_parse_unhandled(os.path.join(g.path, 'svn'), lastrev=lastrev)
127 with open(FILES_PATH, 'wb') as f:
130 with open(CONFIG_PATH, 'wb') as f:
133 def get_path_info(g, path):
136 # parse ls-tree output and get a blob id for path
137 blob = g.git.ls_tree('HEAD', path).split(' ')[2].split("\t")[0]
139 # translate that to a commit id
140 if not CONFIG.has_option('BlobToCommit', blob):
141 CONFIG.set('BlobToCommit', blob, g.commits('HEAD', path, 1)[0].id)
143 commit = CONFIG.get('BlobToCommit', blob)
145 # tranlsate that into an svn revision id
146 if not CONFIG.has_option('CommitToRev', commit):
147 CONFIG.set('CommitToRev',commit,g.git.svn('find-rev', commit))
149 file_rev = CONFIG.get('CommitToRev', commit)
151 # get information about that revision
153 if not CONFIG.has_option('RevInfo', file_rev):
154 for line in g.git.svn('info', path).split("\n"):
155 k, v = line.split(": ", 1)
156 if k == 'Last Changed Date':
157 info_dict['Date'] = v
158 elif k == 'Last Changed Author':
159 info_dict['Author'] = v
160 CONFIG.set('RevInfo', file_rev, info_dict)
163 info = CONFIG.get('RevInfo', file_rev)
164 info_dict.update(info if type(info) is dict else eval(info))
167 with open(CONFIG_PATH, 'wb') as f:
170 info_dict['Revision'] = file_rev
173 def find_last_svn_rev(treeish, parent=0):
174 svnRev = g.git.svn('find-rev', "%s~%i" % (treeish, parent))
178 return find_last_svn_rev(treeish, parent+1)
181 def smudge(g, options):
182 parse_svn_unhandled(g)
183 rev_head = find_last_svn_rev('HEAD')
184 url_base = g.git.svn('info', '--url')
186 FILES.read(FILES_PATH)
187 FILEINFO.read(FILEINFO_PATH)
190 with open(os.path.join(g.wd,'.git','info','exclude')) as f:
193 ignores.append(line.rstrip('\n'))
195 paths = FILES.sections()
198 if not os.path.exists(path):
208 kw_rev = max(filter(lambda x: x <= rev_head, map(int, FILES.options(path))))
213 if not options.clean:
214 info_dict.update(get_path_info(g, path))
215 info_dict['URL'] = '/'.join([url_base, path])
216 info_dict['Name'] = os.path.basename(path)
217 info_dict['Revision'] = str(max(kw_rev, info_dict['Revision']))
220 with open(os.path.join(g.wd, path), 'r') as f:
223 keywords = eval(FILES.get(path, str(kw_rev)))
225 for sk in svn_keywords:
226 if k in svn_keywords[sk]:
228 buf = re.sub(get_svn_keyword_re(sk), '$\\1$', buf)
230 id_str = ' '.join([info_dict['Name'],
231 info_dict['Revision'],
233 info_dict['Author']])
234 buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + id_str + ' $', buf)
236 buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + info_dict[sk] + ' $', buf)
238 with open(os.path.join(g.wd, path), 'w') as f:
241 print path + ' [' + ', '.join(keywords) + '] [len: ' + str(len(buf)) +']'
243 if __name__ == '__main__':
245 parser = OptionParser(version="%prog "+str(VERSION))
246 parser.set_defaults(clean=None)
247 parser.add_option("-s", "--smudge",
248 action="store_false", dest="clean",
249 help="Populate svn:keywords.")
250 parser.add_option("-c", "--clean",
251 action="store_true", dest="clean",
252 help="Return svn:keywords to pristene state.")
253 parser.add_option("-v", "--verbose",
254 action="store_true", dest="verbose", default=False)
255 (options, args) = parser.parse_args()
257 if (options.clean is None):
263 except git.errors.InvalidGitRepositoryError:
264 print "You are not in a git repository or working directory."
267 CONFIG_PATH = os.path.join(gsk(g), 'conf.ini')
268 FILES_PATH = os.path.join(gsk(g), 'files.ini')
269 FILEINFO_PATH = os.path.join(gsk(g), 'fileinfo.ini')
271 CONFIG.read(CONFIG_PATH)
272 for section in ['core','CommitToRev','BlobToCommit', 'RevInfo']:
273 if not CONFIG.has_section(section):
274 CONFIG.add_section(section)