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 parse_svn_unhandled(g):
74 if e.errno != errno.EEXIST:
78 if CONFIG.has_option('core', 'version'):
79 ver = CONFIG.get('core', 'version')
83 FILES.read(FILES_PATH)
84 if CONFIG.has_option('core', 'lastrev'):
85 lastrev = CONFIG.getint('core', 'lastrev')
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*)$")
94 m = re_rev.match(line)
99 if (lastrev >= int(rev)):
102 m = re_keywords.match(line)
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)
110 lastrev = max(int(rev), lastrev)
111 CONFIG.set('core', 'lastrev', lastrev)
112 CONFIG.set('core', 'version', VERSION)
114 with open(FILES_PATH, 'wb') as f:
117 with open(CONFIG_PATH, 'wb') as f:
120 def get_path_info(g, path):
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]
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)
130 commit = CONFIG.get('BlobToCommit', blob)
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))
136 file_rev = CONFIG.get('CommitToRev', commit)
138 # get information about that revision
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)
150 info = CONFIG.get('RevInfo', file_rev)
151 info_dict.update(info if type(info) is dict else eval(info))
154 with open(CONFIG_PATH, 'wb') as f:
157 info_dict['Revision'] = file_rev
160 def find_last_svn_rev(treeish, parent=0):
161 svnRev = g.git.svn('find-rev', "%s~%i" % (treeish, parent))
165 return find_last_svn_rev(treeish, parent+1)
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')
173 FILES.read(FILES_PATH)
174 FILEINFO.read(FILEINFO_PATH)
177 with open(os.path.join(g.wd,'.git','info','exclude')) as f:
180 ignores.append(line.rstrip('\n'))
182 paths = FILES.sections()
185 if not os.path.exists(path):
195 kw_rev = max(filter(lambda x: x <= rev_head, map(int, FILES.options(path))))
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']))
205 with open(os.path.join(g.wd, path), 'r') as f:
208 keywords = eval(FILES.get(path, str(kw_rev)))
210 for sk in svn_keywords:
211 if k in svn_keywords[sk]:
213 buf = re.sub(get_svn_keyword_re(sk), '$\\1$', buf)
215 id_str = ' '.join([info_dict['Name'],
216 info_dict['Revision'],
218 info_dict['Author']])
219 buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + id_str + ' $', buf)
221 buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + info_dict[sk] + ' $', buf)
223 with open(os.path.join(g.wd, path), 'w') as f:
226 print path + ' [' + ', '.join(keywords) + '] [len: ' + str(len(buf)) +']'
228 if __name__ == '__main__':
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()
242 if (options.clean is None):
248 except git.errors.InvalidGitRepositoryError:
249 print "You are not in a git repository or working directory."
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')
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)