1 from mercurial.i18n import _ |
|
2 from mercurial import cmdutil, commands, util |
|
3 import os.path, re, sys |
|
4 |
|
5 hgkeywords = 'Id|Header|Author|Date|Revision|RCSFile|Source' |
|
6 |
|
7 def pretxnkw(ui, repo, hooktype, **args): |
|
8 '''Collects candidates for keyword expansion on commit |
|
9 and expands keywords in working dir. |
|
10 NOTE: for use in combination with hgext.keyword!''' |
|
11 |
|
12 if hooktype != 'pretxncommit': |
|
13 # bail out with error |
|
14 return True |
|
15 |
|
16 # reparse args, opts again as pretxncommit hook is silent about them |
|
17 cmd, sysargs, globalopts, cmdopts = commands.parse(ui, sys.argv[1:])[1:] |
|
18 # exclude tag and import |
|
19 if repr(cmd).split()[1] in ('tag', 'import_'): |
|
20 return False |
|
21 files, match, anypats = cmdutil.matchpats(repo, sysargs, cmdopts) |
|
22 |
|
23 # validity checks should have been done already |
|
24 modified, added = repo.status(files=files, match=match)[:2] |
|
25 candidates = [f for f in modified + added if not f.startswith('.hg')] |
|
26 |
|
27 if not candidates: |
|
28 return False |
|
29 |
|
30 # only check files that have hgkwencode assigned as encode filter |
|
31 files = [] |
|
32 # python2.4: files = set() |
|
33 for pat, opt in repo.ui.configitems('keyword'): |
|
34 if opt == 'expand': |
|
35 mf = util.matcher(repo.root, '', [pat], [], [])[1] |
|
36 for candidate in candidates: |
|
37 if mf(candidate) and candidate not in files: |
|
38 files.append(candidate) |
|
39 # python2.4: |
|
40 # if mf(candidate): files.add(candidate) |
|
41 |
|
42 if not files: # nothing to do |
|
43 return False |
|
44 |
|
45 user, date = repo.changelog.read(repo.changelog.tip())[1:3] |
|
46 strdate = util.datestr(date=date) |
|
47 shortuser = util.shortuser(user) |
|
48 shortdate = util.datestr(date=date, format=util.defaultdateformats[0]) |
|
49 # %Y-%m-%d %H:%M:%S |
|
50 |
|
51 re_kw = re.compile(r'\$(%s)(: [^$]+? )?\$' % hgkeywords) |
|
52 |
|
53 for f in files: |
|
54 data = repo.wfile(f).read() |
|
55 if not util.binary(data): |
|
56 |
|
57 def kwexpand(matchobj): |
|
58 RCSFile = os.path.basename(f)+',v' |
|
59 Source = os.path.join(repo.root, f)+',v' |
|
60 Revision = args['node'][:12] |
|
61 Date = strdate |
|
62 Author = user |
|
63 revdateauth = '%s %s %s' % (Revision, shortdate, shortuser) |
|
64 Header = '%s %s' % (Source, revdateauth) |
|
65 Id = '%s %s' % (RCSFile, revdateauth) |
|
66 return '$%s: %s $' % ( |
|
67 matchobj.group(1), eval(matchobj.group(1))) |
|
68 |
|
69 data, kwct = re_kw.subn(kwexpand, data) |
|
70 if kwct: |
|
71 ui.note(_('expanding keywords in %s\n' % f)) |
|
72 # backup file? |
|
73 repo.wfile(f, 'w').write(data) |
|