"""Build a per-author corpus from a git repo snapshot. Files where the author owns >= 90% of blamed lines are copied whole; otherwise the author's lines from non-mechanical commits go to fragments.txt. Usage: build_author_corpus.py repo rev author_regex outdir [include_regex] [exclude_regex]""" import subprocess, re, sys, os, collections repo, rev, auth, outdir = sys.argv[1:5] inc = re.compile(sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else r'\.(c|cc|cpp|cxx|h|hpp)$') exc = re.compile(sys.argv[6]) if len(sys.argv) > 6 and sys.argv[6] else None A = re.compile(auth) BAD = re.compile(r'\b(patch(es)? (from|by)|thanks|merge|move[sd]?|renam\w*|crlf|whitespace|reformat\w*|format(ting)?|indent\w*|revert|cherry|backport|import(ed)?|update[sd]? (to|from) upstream|sync with|copyright|license)\b', re.I) os.makedirs(outdir, exist_ok=True) files = [f for f in subprocess.check_output(['git', '-C', repo, 'ls-tree', '-r', '--name-only', rev], text=True).split('\n') if f and inc.search(f) and not (exc and exc.search(f))] st = collections.Counter(); frag = open(os.path.join(outdir, 'fragments.txt'), 'w') summ = {} for f in files: try: b = subprocess.check_output(['git', '-C', repo, 'blame', '--line-porcelain', rev, '--', f], text=True, errors='replace') except subprocess.CalledProcessError: continue cur = a = None; lines = [] for line in b.split('\n'): m = re.match(r'^([0-9a-f]{40}) ', line) if m: cur = m.group(1); continue if line.startswith('author '): a = line[7:]; continue if line.startswith('summary '): summ.setdefault(cur, line[8:]); continue if line.startswith('\t'): lines.append((a, cur, line[1:])) if not lines: continue mine = [l for l in lines if A.search(l[0] or '')] share = len(mine) / len(lines) if share >= 0.9: dst = os.path.join(outdir, 'files', f); os.makedirs(os.path.dirname(dst), exist_ok=True) open(dst, 'w').write('\n'.join(l[2] for l in lines) + '\n'); st['whole_files'] += 1; st['whole_lines'] += len(lines) elif mine: buf = [] for a2, c, t in lines: if A.search(a2 or '') and not BAD.search(summ.get(c, '')): buf.append(t) elif buf: frag.write('\n'.join(buf) + '\n\n'); st['frag_lines'] += len(buf); buf = [] if buf: frag.write('\n'.join(buf) + '\n\n'); st['frag_lines'] += len(buf) print(os.path.basename(outdir), dict(st))