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
36 # Where we keep data in the repo.
38 return os.path.join(g.path, 'svn_keywords')
41 CONFIG = ConfigParser()
42 FILES = ConfigParser()
43 FILEINFO = ConfigParser()
51 svn_keywords = {'Date': ['Date', 'LastDateChanged'],
52 'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
53 'Author': ['Author','LastChangedBy'],
54 'URL': ['HeadURL', 'URL'],
58 # Regular expressions we'll be using to smudge/clean; created as
61 def get_svn_keyword_re(s):
62 if not s in svn_keywords:
63 raise 'Invalid SVN Keyword'
64 if not s in svn_keywords_re:
65 svn_keywords_re[s] = re.compile('\$(' + ('|'.join(svn_keywords[s])) + ')[^$]*\$')
66 return svn_keywords_re[s]
68 # Parse the unhandled log.
69 def parse_svn_unhandled(g):
73 if e.errno != errno.EEXIST:
77 if CONFIG.has_option('core', 'version'):
78 ver = CONFIG.get('core', 'version')
82 FILES.read(FILES_PATH)
83 if CONFIG.has_option('core', 'lastrev'):
84 lastrev = CONFIG.getint('core', 'lastrev')
86 with open(g.path + '/svn/git-svn/unhandled.log', 'r') as f:
87 # Compile the regular expressions we'll be using here.
88 re_rev = re.compile("^r(\d+)$")
89 re_keywords = re.compile("^\s+[-+]file_prop: (\S+) svn:keywords ?(\S*)$")
93 m = re_rev.match(line)
98 if (lastrev >= int(rev)):
101 m = re_keywords.match(line)
103 path = urllib.unquote(m.group(1))
104 keywords = set(urllib.unquote(m.group(2)).split(' '))
105 if not FILES.has_section(path):
106 FILES.add_section(path)
107 FILES.set(path, rev, keywords)
109 lastrev = max(int(rev), lastrev)
110 CONFIG.set('core', 'lastrev', lastrev)
111 CONFIG.set('core', 'version', VERSION)
113 with open(FILES_PATH, 'wb') as f:
116 with open(CONFIG_PATH, 'wb') as f:
119 def get_path_info(g, path):
122 # parse ls-tree output and get a blob id for path
123 blob = g.git.ls_tree('HEAD', path).split(' ')[2].split("\t")[0]
125 # translate that to a commit id
126 if not CONFIG.has_option('BlobToCommit', blob):
127 CONFIG.set('BlobToCommit', blob, g.commits('HEAD', path, 1)[0].id)
129 commit = CONFIG.get('BlobToCommit', blob)
131 # tranlsate that into an svn revision id
132 if not CONFIG.has_option('CommitToRev', commit):
133 CONFIG.set('CommitToRev',commit,g.git.svn('find-rev', commit))
135 file_rev = CONFIG.get('CommitToRev', commit)
137 # get information about that revision
139 if not CONFIG.has_option('RevInfo', file_rev):
140 for line in g.git.svn('info', path).split("\n"):
141 k, v = line.split(": ", 1)
142 if k == 'Last Changed Date':
143 info_dict['Date'] = v
144 elif k == 'Last Changed Author':
145 info_dict['Author'] = v
146 CONFIG.set('RevInfo', file_rev, info_dict)
149 info = CONFIG.get('RevInfo', file_rev)
150 info_dict.update(info if type(info) is dict else eval(info))
153 with open(CONFIG_PATH, 'wb') as f:
156 info_dict['Revision'] = file_rev
160 def smudge(g, options):
161 parse_svn_unhandled(g)
162 rev_head = int(g.git.svn('find-rev', 'HEAD'))
163 url_base = g.git.svn('info', '--url')
165 FILES.read(FILES_PATH)
166 FILEINFO.read(FILEINFO_PATH)
168 paths = FILES.sections()
171 if not os.path.exists(path):
174 kw_rev = max(filter(lambda x: x <= rev_head, map(int, FILES.options(path))))
177 if not options.clean:
178 info_dict.update(get_path_info(g, path))
179 info_dict['URL'] = '/'.join([url_base, path])
180 info_dict['Name'] = os.path.basename(path)
181 info_dict['Revision'] = str(max(kw_rev, info_dict['Revision']))
184 with open(os.path.join(g.wd, path), 'r') as f:
187 keywords = eval(FILES.get(path, str(kw_rev)))
189 for sk in svn_keywords:
190 if k in svn_keywords[sk]:
192 buf = re.sub(get_svn_keyword_re(sk), '$\\1$', buf)
194 id_str = ' '.join([info_dict['Name'],
195 info_dict['Revision'],
197 info_dict['Author']])
198 buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + id_str + ' $', buf)
200 buf = re.sub(get_svn_keyword_re(sk), '$\\1: ' + info_dict[sk] + ' $', buf)
202 with open(os.path.join(g.wd, path), 'w') as f:
205 print path + ' [' + ', '.join(keywords) + '] [len: ' + str(len(buf)) +']'
207 if __name__ == '__main__':
209 parser = OptionParser(version="%prog "+str(VERSION))
210 parser.set_defaults(clean=None)
211 parser.add_option("-s", "--smudge",
212 action="store_false", dest="clean",
213 help="Populate svn:keywords.")
214 parser.add_option("-c", "--clean",
215 action="store_true", dest="clean",
216 help="Return svn:keywords to pristene state.")
217 parser.add_option("-v", "--verbose",
218 action="store_true", dest="verbose", default=False)
219 (options, args) = parser.parse_args()
221 if (options.clean is None):
227 except git.errors.InvalidGitRepositoryError:
228 print "You are not in a git repository or working directory."
231 CONFIG_PATH = os.path.join(gsk(g), 'conf.ini')
232 FILES_PATH = os.path.join(gsk(g), 'files.ini')
233 FILEINFO_PATH = os.path.join(gsk(g), 'fileinfo.ini')
235 CONFIG.read(CONFIG_PATH)
236 for section in ['core','CommitToRev','BlobToCommit', 'RevInfo']:
237 if not CONFIG.has_section(section):
238 CONFIG.add_section(section)