diff --git a/swh/loader/cvs/cvs2gitdump/cvs2gitdump.py b/swh/loader/cvs/cvs2gitdump/cvs2gitdump.py index 3d60add..e139b84 100644 --- a/swh/loader/cvs/cvs2gitdump/cvs2gitdump.py +++ b/swh/loader/cvs/cvs2gitdump/cvs2gitdump.py @@ -1,726 +1,726 @@ #!/usr/local/bin/python # # Copyright (c) 2012 YASUOKA Masahiko # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Usage # # First import: # % git init --bare /git/openbsd.git # % python cvs2gitdump.py -k OpenBSD -e openbsd.org /cvs/openbsd/src \ # > openbsd.dump # % git --git-dir /git/openbsd.git fast-import < openbsd.dump # # Periodic import: # % sudo cvsync # % python cvs2gitdump.py -k OpenBSD -e openbsd.org /cvs/openbsd/src \ # /git/openbsd.git > openbsd2.dump # % git --git-dir /git/openbsd.git fast-import < openbsd2.dump # import copy import getopt import os import re import subprocess import sys import time from typing import Dict, List, Optional, Tuple, TypeVar import swh.loader.cvs.rcsparse as rcsparse CHANGESET_FUZZ_SEC = 300 def usage(): print('usage: cvs2gitdump [-ah] [-z fuzz] [-e email_domain] ' '[-E log_encodings]\n' '\t[-k rcs_keywords] [-b branch] [-m module] [-l last_revision]\n' '\tcvsroot [git_dir]', file=sys.stderr) def main() -> None: email_domain = None do_incremental = False git_tip = None git_branch = 'master' dump_all = False log_encoding = 'utf-8,iso-8859-1' rcs = RcsKeywords() modules = [] last_revision = None fuzzsec = CHANGESET_FUZZ_SEC try: opts, args = getopt.getopt(sys.argv[1:], 'ab:hm:z:e:E:k:t:l:') for opt, v in opts: if opt == '-z': fuzzsec = int(v) elif opt == '-e': email_domain = v elif opt == '-a': dump_all = True elif opt == '-b': git_branch = v elif opt == '-E': log_encoding = v elif opt == '-k': rcs.add_id_keyword(v) elif opt == '-m': if v == '.git': print('Cannot handle the path named \'.git\'', file=sys.stderr) sys.exit(1) modules.append(v) elif opt == '-l': last_revision = v elif opt == '-h': usage() sys.exit(1) except getopt.GetoptError as msg: print(msg, file=sys.stderr) usage() sys.exit(1) if len(args) == 0 or len(args) > 2: usage() sys.exit(1) log_encodings = log_encoding.split(',') cvsroot = args[0] while cvsroot[-1] == '/': cvsroot = cvsroot[:-1] if len(args) == 2: do_incremental = True git = subprocess.Popen( ['git', '--git-dir=' + args[1], '-c', 'i18n.logOutputEncoding=UTF-8', 'log', '--max-count', '1', '--date=raw', '--format=%ae%n%ad%n%H', git_branch], encoding='utf-8', stdout=subprocess.PIPE) assert git.stdout is not None outs = git.stdout.readlines() git.wait() if git.returncode != 0: print("Couldn't exec git", file=sys.stderr) sys.exit(git.returncode) git_tip = outs[2].strip() if last_revision is not None: git = subprocess.Popen( ['git', '--git-dir=' + args[1], '-c', 'i18n.logOutputEncoding=UTF-8', 'log', '--max-count', '1', '--date=raw', '--format=%ae%n%ad%n%H', last_revision], encoding='utf-8', stdout=subprocess.PIPE) assert git.stdout is not None outs = git.stdout.readlines() git.wait() if git.returncode != 0: print("Coundn't exec git", file=sys.stderr) sys.exit(git.returncode) last_author = outs[0].strip() last_ctime = float(outs[1].split()[0]) # strip off the domain part from the last author since cvs doesn't have # the domain part. if do_incremental and email_domain is not None and \ last_author.lower().endswith(('@' + email_domain).lower()): last_author = last_author[:-1 * (1 + len(email_domain))] cvs = CvsConv(cvsroot, rcs, not do_incremental, fuzzsec) print('** walk cvs tree', file=sys.stderr) if len(modules) == 0: cvs.walk() else: for module in modules: cvs.walk(module) changesets = sorted(cvs.changesets) nchangesets = len(changesets) print('** cvs has %d changeset' % (nchangesets), file=sys.stderr) if nchangesets <= 0: sys.exit(0) if not dump_all: # don't use last 10 minutes for safety max_time_max = changesets[-1].max_time - 600 else: max_time_max = changesets[-1].max_time found_last_revision = False markseq = cvs.markseq extags = set() for k in changesets: if do_incremental and not found_last_revision: if k.min_time == last_ctime and k.author == last_author: found_last_revision = True for tag in k.tags: extags.add(tag) continue if k.max_time > max_time_max: break marks = {} for f in k.revs: if not do_incremental: marks[f.markseq] = f else: markseq = markseq + 1 git_dump_file(f.path, f.rev, rcs, markseq) marks[markseq] = f log = rcsparse.rcsfile(k.revs[0].path).getlog(k.revs[0].rev) for i, e in enumerate(log_encodings): try: how = 'ignore' if i == len(log_encodings) - 1 else 'strict' log_str = log.decode(e, how) break except UnicodeError: pass log = log_str.encode('utf-8', 'ignore') output('commit refs/heads/' + git_branch) markseq = markseq + 1 output('mark :%d' % (markseq)) email = k.author if email_domain is None \ else k.author + '@' + email_domain output('author %s <%s> %d +0000' % (k.author, email, k.min_time)) output('committer %s <%s> %d +0000' % (k.author, email, k.min_time)) output('data', len(log)) output(log, end='') if do_incremental and git_tip is not None: output('from', git_tip) git_tip = None for m in marks: f = marks[m] mode = 0o100755 if os.access(f.path, os.X_OK) else 0o100644 fn = file_path(cvs.cvsroot, f.path) if f.state == 'dead': output('D', fn) else: output('M %o :%d %s' % (mode, m, fn)) output('') for tag in k.tags: if tag in extags: continue output('reset refs/tags/%s' % (tag)) output('from :%d' % (markseq)) output('') if do_incremental and not found_last_revision: raise Exception('could not find the last revision') print('** dumped', file=sys.stderr) # # Encode by UTF-8 always for string objects since encoding for git-fast-import # is UTF-8. Also write without conversion for a bytes object (file bodies # might be various encodings) # def output(*args, end='\n') -> None: if len(args) == 0: pass elif len(args) > 1 or isinstance(args[0], str): lines = ' '.join( [arg if isinstance(arg, str) else str(arg) for arg in args]) sys.stdout.buffer.write(lines.encode('utf-8')) else: sys.stdout.buffer.write(args[0]) if len(end) > 0: sys.stdout.buffer.write(end.encode('utf-8')) class FileRevision: - def __init__(self, path: str, rev: str, state: str, markseq: int) -> None: + def __init__(self, path: bytes, rev: str, state: str, markseq: int) -> None: self.path = path self.rev = rev self.state = state self.markseq = markseq class ChangeSetKey: def __init__( self, branch: str, author, timestamp: int, log: bytes, commitid: Optional[str], fuzzsec: int ) -> None: self.branch = branch self.author = author self.min_time = timestamp self.max_time = timestamp self.commitid = commitid self.fuzzsec = fuzzsec self.revs: List[FileRevision] = [] self.tags: List[str] = [] self.log_hash = 0 h = 0 for c in log: h = 31 * h + c self.log_hash = h def __lt__(self, other) -> bool: return self._cmp(other) < 0 def __gt__(self, other) -> bool: return self._cmp(other) > 0 def __eq__(self, other) -> bool: return self._cmp(other) == 0 def __le__(self, other) -> bool: return self._cmp(other) <= 0 def __ge__(self, other) -> bool: return self._cmp(other) >= 0 def __ne__(self, other) -> bool: return self._cmp(other) != 0 def _cmp(self, anon) -> int: if not isinstance(anon, ChangeSetKey): raise TypeError() # compare by the commitid cid = _cmp2(self.commitid, anon.commitid) if cid == 0 and self.commitid is not None: # both have commitid and they are same return 0 # compare by the time ma = anon.min_time - self.max_time mi = self.min_time - anon.max_time ct = self.min_time - anon.min_time if ma > self.fuzzsec or mi > self.fuzzsec: return ct if cid != 0: # only one has the commitid, this means different commit return cid if ct == 0 else ct # compare by log, branch and author c = _cmp2(self.log_hash, anon.log_hash) if c == 0: c = _cmp2(self.branch, anon.branch) if c == 0: c = _cmp2(self.author, anon.author) if c == 0: return 0 return ct if ct != 0 else c def merge(self, anot: "ChangeSetKey") -> None: self.max_time = max(self.max_time, anot.max_time) self.min_time = min(self.min_time, anot.min_time) self.revs.extend(anot.revs) def __hash__(self) -> int: return hash(self.branch + '/' + self.author) * 31 + self.log_hash - def put_file(self, path: str, rev: str, state: str, markseq: int): + def put_file(self, path: bytes, rev: str, state: str, markseq: int): self.revs.append(FileRevision(path, rev, state, markseq)) TCmp = TypeVar("TCmp", int, str) def _cmp2(a: Optional[TCmp], b: Optional[TCmp]) -> int: _a = a is not None _b = b is not None return (a > b) - (a < b) if _a and _b else (_a > _b) - (_a < _b) # type: ignore class CvsConv: def __init__(self, cvsroot: str, rcs: "RcsKeywords", dumpfile: bool, fuzzsec: int) -> None: self.cvsroot = cvsroot self.rcs = rcs self.changesets: Dict[ChangeSetKey, ChangeSetKey] = dict() self.dumpfile = dumpfile self.markseq = 0 self.tags: Dict[str, ChangeSetKey] = dict() self.fuzzsec = fuzzsec def walk(self, module: Optional[str] =None) -> None: p = [self.cvsroot] if module is not None: p.append(module) path = os.path.join(*p) - for root, dirs, files in os.walk(path): - if '.git' in dirs: + for root, dirs, files in os.walk(os.fsencode(path)): + if b'.git' in dirs: print('Ignore %s: cannot handle the path named \'.git\'' % ( - root + os.sep + '.git'), file=sys.stderr) - dirs.remove('.git') - if '.git' in files: + os.path.join(root, b'.git')), file=sys.stderr) + dirs.remove(b'.git') + if b'.git' in files: print('Ignore %s: cannot handle the path named \'.git\'' % ( - root + os.sep + '.git'), file=sys.stderr) - files.remove('.git') + os.path.join(root, b'.git')), file=sys.stderr) + files.remove(b'.git') for f in files: - if not f[-2:] == ',v': + if not f[-2:] == b',v': continue - self.parse_file(root + os.sep + f) + self.parse_file(os.path.join(root, f)) for t, c in list(self.tags.items()): c.tags.append(t) def parse_file(self, path: str) -> None: rtags: Dict[str, List[str]] = dict() rcsfile = rcsparse.rcsfile(path) branches = {'1': 'HEAD', '1.1.1': 'VENDOR'} for k, v_ in list(rcsfile.symbols.items()): r = v_.split('.') if len(r) == 3: branches[v_] = 'VENDOR' elif len(r) >= 3 and r[-2] == '0': branches['.'.join(r[:-2] + r[-1:])] = k if len(r) == 2 and branches[r[0]] == 'HEAD': if v_ not in rtags: rtags[v_] = list() rtags[v_].append(k) revs: List[Tuple[str, Tuple[str, int, str, str, List[str], str, str]]] = list(rcsfile.revs.items()) # sort by revision descending to priorize 1.1.1.1 than 1.1 revs.sort(key=lambda a: a[1][0], reverse=True) # sort by time revs.sort(key=lambda a: a[1][1]) novendor = False have_initial_revision = False last_vendor_status = None for k, v in revs: r = k.split('.') if len(r) == 4 and r[0] == '1' and r[1] == '1' and r[2] == '1' \ and r[3] == '1': if have_initial_revision: continue if v[3] == 'dead': continue last_vendor_status = v[3] have_initial_revision = True elif len(r) == 4 and r[0] == '1' and r[1] == '1' and r[2] == '1': if novendor: continue last_vendor_status = v[3] elif len(r) == 2: if r[0] == '1' and r[1] == '1': if have_initial_revision: continue if v[3] == 'dead': continue have_initial_revision = True elif r[0] == '1' and r[1] != '1': novendor = True if last_vendor_status == 'dead' and v[3] == 'dead': last_vendor_status = None continue last_vendor_status = None else: # trunk only continue if self.dumpfile: self.markseq = self.markseq + 1 git_dump_file(path, k, self.rcs, self.markseq) b = '.'.join(r[:-1]) try: a = ChangeSetKey( branches[b], v[2], v[1], rcsfile.getlog(v[0]), v[6], self.fuzzsec) except Exception as e: print('Aborted at %s %s' % (path, v[0]), file=sys.stderr) raise e a.put_file(path, k, v[3], self.markseq) while a in self.changesets: c = self.changesets[a] del self.changesets[a] c.merge(a) a = c self.changesets[a] = a if k in rtags: for t in rtags[k]: if t not in self.tags or \ self.tags[t].max_time < a.max_time: self.tags[t] = a -def file_path(r: str, p: str) -> str: - if r.endswith('/'): +def file_path(r: bytes, p: bytes) -> bytes: + if r.endswith(b'/'): r = r[:-1] - if p[-2:] == ',v': + if p[-2:] == b',v': path = p[:-2] # drop ",v" else: path = p - p_ = path.split('/') - if len(p_) > 0 and p_[-2] == 'Attic': - path = '/'.join(p_[:-2] + [p_[-1]]) + p_ = path.split(b'/') + if len(p_) > 0 and p_[-2] == b'Attic': + path = b'/'.join(p_[:-2] + [p_[-1]]) if path.startswith(r): path = path[len(r) + 1:] return path def git_dump_file(path: str, k, rcs, markseq) -> None: try: cont = rcs.expand_keyword(path, rcsparse.rcsfile(path), k, []) except RuntimeError as msg: print('Unexpected runtime error on parsing', path, k, ':', msg, file=sys.stderr) print('unlimit the resource limit may fix this problem.', file=sys.stderr) sys.exit(1) output('blob') output('mark :%d' % markseq) output('data', len(cont)) output(cont) class RcsKeywords: RCS_KW_AUTHOR = (1 << 0) RCS_KW_DATE = (1 << 1) RCS_KW_LOG = (1 << 2) RCS_KW_NAME = (1 << 3) RCS_KW_RCSFILE = (1 << 4) RCS_KW_REVISION = (1 << 5) RCS_KW_SOURCE = (1 << 6) RCS_KW_STATE = (1 << 7) RCS_KW_FULLPATH = (1 << 8) RCS_KW_MDOCDATE = (1 << 9) RCS_KW_LOCKER = (1 << 10) RCS_KW_ID = (RCS_KW_RCSFILE | RCS_KW_REVISION | RCS_KW_DATE | RCS_KW_AUTHOR | RCS_KW_STATE) RCS_KW_HEADER = (RCS_KW_ID | RCS_KW_FULLPATH) rcs_expkw = { b"Author": RCS_KW_AUTHOR, b"Date": RCS_KW_DATE, b"Header": RCS_KW_HEADER, b"Id": RCS_KW_ID, b"Log": RCS_KW_LOG, b"Name": RCS_KW_NAME, b"RCSfile": RCS_KW_RCSFILE, b"Revision": RCS_KW_REVISION, b"Source": RCS_KW_SOURCE, b"State": RCS_KW_STATE, b"Mdocdate": RCS_KW_MDOCDATE, b"Locker": RCS_KW_LOCKER } RCS_KWEXP_NONE = (1 << 0) RCS_KWEXP_NAME = (1 << 1) # include keyword name RCS_KWEXP_VAL = (1 << 2) # include keyword value RCS_KWEXP_LKR = (1 << 3) # include name of locker RCS_KWEXP_OLD = (1 << 4) # generate old keyword string RCS_KWEXP_ERR = (1 << 5) # mode has an error RCS_KWEXP_DEFAULT = (RCS_KWEXP_NAME | RCS_KWEXP_VAL) RCS_KWEXP_KVL = (RCS_KWEXP_NAME | RCS_KWEXP_VAL | RCS_KWEXP_LKR) def __init__(self) -> None: self.rerecomple() def rerecomple(self) -> None: pat = b'|'.join(list(self.rcs_expkw.keys())) self.re_kw = re.compile(b".*?\\$(" + pat + b")[\\$:]") def add_id_keyword(self, keyword) -> None: self.rcs_expkw[keyword.encode('ascii')] = self.RCS_KW_ID self.rerecomple() def kflag_get(self, flags: Optional[str]) -> int: if flags is None: return self.RCS_KWEXP_DEFAULT fl = 0 for fc in flags: if fc == 'k': fl |= self.RCS_KWEXP_NAME elif fc == 'v': fl |= self.RCS_KWEXP_VAL elif fc == 'l': fl |= self.RCS_KWEXP_LKR elif fc == 'o': if len(flags) != 1: fl |= self.RCS_KWEXP_ERR fl |= self.RCS_KWEXP_OLD elif fc == 'b': if len(flags) != 1: fl |= self.RCS_KWEXP_ERR fl |= self.RCS_KWEXP_NONE else: fl |= self.RCS_KWEXP_ERR return fl - def expand_keyword(self, filename: str, rcs: rcsparse.rcsfile, r: str, excluded_keywords: List[str]) -> bytes: + def expand_keyword(self, filename: str, rcs: rcsparse.rcsfile, r: str, excluded_keywords: List[str], filename_encoding="utf-8") -> bytes: """ Check out a file with keywords expanded. Expansion rules are specific to each keyword, and some cases specific to undocumented behaviour of CVS. Our implementation does not expand some keywords (see comments in the code). For a list of keywords and their expansion rules, see: https://www.gnu.org/software/trans-coord/manual/cvs/cvs.html#Keyword-list (also available in 'info cvs' if cvs is installed) """ rev = rcs.revs[r] mode = self.kflag_get(rcs.expand) if (mode & (self.RCS_KWEXP_NONE | self.RCS_KWEXP_OLD)) != 0: return rcs.checkout(rev[0]) ret = [] for line in rcs.checkout(rev[0]).splitlines(keepends=True): logbuf = None m = self.re_kw.match(line) if m is None: # No RCS Keywords, use it as it is ret.append(line) continue expkw = 0 line0 = b'' while m is not None: logbuf = None try: dsign = m.end(1) + line[m.end(1):].index(b'$') except ValueError: # No RCS Keywords, use it as it is ret.append(line) break prefix = line[:m.start(1) - 1] next_match_segment = copy.deepcopy(line[dsign:]) expbuf = '' try: kwname = m.group(1).decode('ascii') except UnicodeDecodeError: # Not a valid RCS keyword, use it as it is ret.append(line) break if kwname in excluded_keywords: line0 += prefix + m.group(1) m = self.re_kw.match(next_match_segment) if m: line = next_match_segment continue else: ret.append(line0 + line[dsign + 1:]) break line = line[dsign + 1:] if (mode & self.RCS_KWEXP_NAME) != 0: expbuf += '$%s' % kwname if (mode & self.RCS_KWEXP_VAL) != 0: expbuf += ': ' if (mode & self.RCS_KWEXP_VAL) != 0: expkw = self.rcs_expkw[m.group(1)] if (expkw & self.RCS_KW_RCSFILE) != 0: expbuf += filename \ if (expkw & self.RCS_KW_FULLPATH) != 0 \ else os.path.basename(filename) expbuf += " " if (expkw & self.RCS_KW_REVISION) != 0: expbuf += rev[0] expbuf += " " if (expkw & self.RCS_KW_DATE) != 0: expbuf += time.strftime( "%Y/%m/%d %H:%M:%S ", time.gmtime(rev[1])) if (expkw & self.RCS_KW_MDOCDATE) != 0: d = time.gmtime(rev[1]) expbuf += time.strftime( "%B%e %Y " if (d.tm_mday < 10) else "%B %e %Y ", d) if (expkw & self.RCS_KW_AUTHOR) != 0: expbuf += rev[2] expbuf += " " if (expkw & self.RCS_KW_STATE) != 0: expbuf += rev[3] expbuf += " " if (expkw & self.RCS_KW_LOG) != 0: # Unlike other keywords, the Log keyword expands over multiple lines. # The terminating '$' of the Log keyword appears on the line which # contains the log keyword itself. Then follow all log message lines, # and those lines are followed by content which follows the Log keyword. # For example, the line: # # foo $Log$content which follows # # will be expanded like this by CVS: # # foo $Log: delta,v $ # foo Revision 1.2 2021/11/29 14:24:18 stsp # foo log message line 1 # foo log message line 2 # foocontent which follows # # (Side note: Trailing whitespace is stripped from "foo " when # the content which follows gets written to the output file.) # # If we did not trim the Log keyword's trailing "$" here then # the last line would read instead: # # foo$content which follows assert(next_match_segment[0] == ord('$')) next_match_segment = next_match_segment[1:] expbuf += filename \ if (expkw & self.RCS_KW_FULLPATH) != 0 \ else os.path.basename(filename) expbuf += " " logbuf = prefix + ( 'Revision %s %s %s\n' % ( rev[0], time.strftime( "%Y/%m/%d %H:%M:%S", time.gmtime(rev[1])), rev[2])).encode('ascii') for lline in rcs.getlog(rev[0]).splitlines(keepends=True): logbuf += prefix + lline if (expkw & self.RCS_KW_SOURCE) != 0: expbuf += filename expbuf += " " if (expkw & (self.RCS_KW_NAME | self.RCS_KW_LOCKER)) != 0: # We do not expand Name and Locker keywords. # The Name keyword is only expanded when a file is checked # out with an explicit tag name .perhaps this will be needed # if the loader learns about CVS tags some day. # The Locker keyword only expands if the file is currently # locked via 'cvs admin -l', which is not part of the # information we want to preserve about source code. expbuf += " " if (mode & self.RCS_KWEXP_NAME) != 0: expbuf += '$' if logbuf is not None: - ret.append(prefix + expbuf.encode('ascii') + b'\n' + logbuf) + ret.append(prefix + expbuf.encode(filename_encoding) + b'\n' + logbuf) else: - line0 += prefix + expbuf[:255].encode('ascii') + line0 += prefix + expbuf[:255].encode(filename_encoding) m = self.re_kw.match(next_match_segment) if m: line = next_match_segment if (mode & self.RCS_KWEXP_NAME) != 0 and expkw and (expkw & self.RCS_KW_LOG) == 0 and line0[-1] == ord('$'): # There is another keyword on this line that needs expansion. # Avoid a double "$$" in the expanded string. This $ terminates # the previous keyword and marks the beginning of the next one. line0 = line0[:-1] elif logbuf is not None: # Trim whitespace from tail of prefix if appending a suffix which # followed the Log keyword on the same line. # Testing suggests that this matches CVS's behaviour. ret.append(line0 + prefix.rstrip() + line) else: ret.append(line0 + line) return b''.join(ret) # ---------------------------------------------------------------------- # entry point # ---------------------------------------------------------------------- if __name__ == '__main__': main() diff --git a/swh/loader/cvs/cvsclient.py b/swh/loader/cvs/cvsclient.py index 397d3f9..76c3f07 100644 --- a/swh/loader/cvs/cvsclient.py +++ b/swh/loader/cvs/cvsclient.py @@ -1,445 +1,477 @@ # Copyright (C) 2015-2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information """Minimal CVS client implementation """ import os.path import socket import subprocess import tempfile +from typing import Tuple from tenacity import retry from tenacity.retry import retry_if_exception_type from tenacity.stop import stop_after_attempt from swh.loader.exception import NotFound CVS_PSERVER_PORT = 2401 CVS_PROTOCOL_BUFFER_SIZE = 8192 EXAMPLE_PSERVER_URL = "pserver://user:password@cvs.example.com/cvsroot/repository" EXAMPLE_SSH_URL = "ssh://user@cvs.example.com/cvsroot/repository" VALID_RESPONSES = [ "ok", "error", "Valid-requests", "Checked-in", "New-entry", "Checksum", "Copy-file", "Updated", "Created", "Update-existing", "Merged", "Patched", "Rcs-diff", "Mode", "Removed", "Remove-entry", "Template", "Notified", "Module-expansion", "Wrapper-rcsOption", "M", "Mbinary", "E", "F", "MT", ] # Trivially encode strings to protect them from innocent eyes (i.e., # inadvertent password compromises, like a network administrator # who's watching packets for legitimate reasons and accidentally sees # the password protocol go by). # # This is NOT secure encryption. def scramble_password(password): s = ["A"] # scramble scheme version number # fmt: off scramble_shifts = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, # noqa: E241 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, # noqa: E241,E131,B950 114,120, 53, 79, 96,109, 72,108, 70, 64, 76, 67,116, 74, 68, 87, # noqa: E241,E131,B950 111, 52, 75,119, 49, 34, 82, 81, 95, 65,112, 86,118,110,122,105, # noqa: E241,E131,B950 41, 57, 83, 43, 46,102, 40, 89, 38,103, 45, 50, 42,123, 91, 35, # noqa: E241,E131,B950 125, 55, 54, 66,124,126, 59, 47, 92, 71,115, 78, 88,107,106, 56, # noqa: E241,E131,B950 36,121,117,104,101,100, 69, 73, 99, 63, 94, 93, 39, 37, 61, 48, # noqa: E241,E131,B950 58,113, 32, 90, 44, 98, 60, 51, 33, 97, 62, 77, 84, 80, 85,223, # noqa: E241,E131,B950 225,216,187,166,229,189,222,188,141,249,148,200,184,136,248,190, # noqa: E241,E131,B950 199,170,181,204,138,232,218,183,255,234,220,247,213,203,226,193, # noqa: E241,E131,B950 174,172,228,252,217,201,131,230,197,211,145,238,161,179,160,212, # noqa: E241,E131,B950 207,221,254,173,202,146,224,151,140,196,205,130,135,133,143,246, # noqa: E241,E131,B950 192,159,244,239,185,168,215,144,139,165,180,157,147,186,214,176, # noqa: E241,E131,B950 227,231,219,169,175,156,206,198,129,164,150,210,154,177,134,127, # noqa: E241,E131,B950 182,128,158,208,162,132,167,209,149,241,153,251,237,236,171,195, # noqa: E241,E131,B950 243,233,253,240,194,250,191,155,142,137,245,235,163,242,178,152] # noqa: E241,E131,B950 # fmt: on for c in password: s.append("%c" % scramble_shifts[ord(c)]) return "".join(s) +def decode_path(path: bytes) -> Tuple[str, str]: + """Attempt to decode a file path based on encodings known to be used + in CVS repositories that can be found in the wild. + + Args: + path: raw bytes path + + Returns: + A tuple (decoded path, encoding) + + """ + path_encodings = ["ascii", "iso-8859-1", "utf-8"] + for encoding in path_encodings: + try: + how = "ignore" if encoding == path_encodings[-1] else "strict" + path_str = path.decode(encoding, how) + break + except UnicodeError: + pass + return path_str, encoding + + class CVSProtocolError(Exception): pass class CVSClient: # connection to an existing pserver might sometimes fail, # retrying the operation usually fixes the issue @retry( retry=retry_if_exception_type(NotFound), stop=stop_after_attempt(max_attempt_number=3), reraise=True, ) def connect_pserver(self, hostname, port, username, password): if port is None: port = CVS_PSERVER_PORT if username is None: raise NotFound( "Username is required for " "a pserver connection: %s" % EXAMPLE_PSERVER_URL ) try: self.socket = socket.create_connection((hostname, port)) except ConnectionRefusedError: raise NotFound("Could not connect to %s:%s", hostname, port) # use empty password if it is None scrambled_password = scramble_password(password or "") request = "BEGIN AUTH REQUEST\n%s\n%s\n%s\nEND AUTH REQUEST\n" % ( self.cvsroot_path, username, scrambled_password, ) print("Request: %s\n" % request) self.socket.sendall(request.encode("UTF-8")) response = self.conn_read_line() if response != b"I LOVE YOU\n": raise NotFound( "pserver authentication failed for %s:%s: %s" % (hostname, port, response) ) def connect_ssh(self, hostname, port, username): command = ["ssh"] if username is not None: # Assume 'auth' contains only a user name. # We do not support password authentication with SSH since the # anoncvs user is usually granted access without a password. command += ["-l", "%s" % username] if port is not None: command += ["-p", "%d" % port] # accept new SSH hosts keys upon first use; changed host keys # will require intervention command += ["-o", "StrictHostKeyChecking=accept-new"] # disable interactive prompting command += ["-o", "BatchMode=yes"] # disable further option processing by adding '--' command += ["--"] command += ["%s" % hostname, "cvs", "server"] # use non-buffered I/O to match behaviour of self.socket self.ssh = subprocess.Popen( command, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE ) def connect_fake(self): command = ["cvs", "server"] # use non-buffered I/O to match behaviour of self.socket self.ssh = subprocess.Popen( command, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE ) def conn_read_line(self, require_newline=True): if len(self.linebuffer) != 0: return self.linebuffer.pop(0) buf = b"" idx = -1 while idx == -1: if len(buf) >= CVS_PROTOCOL_BUFFER_SIZE: if require_newline: raise CVSProtocolError( "Overlong response from " "CVS server: %s" % buf ) else: break if self.socket: buf += self.socket.recv(CVS_PROTOCOL_BUFFER_SIZE) elif self.ssh: buf += self.ssh.stdout.read(CVS_PROTOCOL_BUFFER_SIZE) else: raise Exception("No valid connection") if not buf: return None idx = buf.rfind(b"\n") if idx != -1: self.linebuffer = buf[: idx + 1].splitlines(keepends=True) else: if require_newline: raise CVSProtocolError("Invalid response from CVS server: %s" % buf) else: self.linebuffer.append(buf) if len(self.incomplete_line) > 0: self.linebuffer[0] = self.incomplete_line + self.linebuffer[0] if idx != -1: self.incomplete_line = buf[idx + 1 :] else: self.incomplete_line = b"" return self.linebuffer.pop(0) def conn_write(self, data): if self.socket: return self.socket.sendall(data) if self.ssh: self.ssh.stdin.write(data) return self.ssh.stdin.flush() raise Exception("No valid connection") - def conn_write_str(self, s): - return self.conn_write(s.encode("UTF-8")) + def conn_write_str(self, s, encoding="utf-8"): + return self.conn_write(s.encode(encoding)) def conn_close(self): if self.socket: self.socket.close() if self.ssh: self.ssh.kill() try: self.ssh.wait(timeout=10) except subprocess.TimeoutExpired as e: raise subprocess.TimeoutExpired( "Could not terminate " "ssh program: %s" % e ) def __init__(self, url): """ Connect to a CVS server at the specified URL and perform the initial CVS protocol handshake. """ self.hostname = url.hostname self.cvsroot_path = os.path.dirname(url.path) self.cvs_module_name = os.path.basename(url.path) self.socket = None self.ssh = None self.linebuffer = list() self.incomplete_line = b"" if url.scheme == "pserver": self.connect_pserver(url.hostname, url.port, url.username, url.password) elif url.scheme == "ssh": self.connect_ssh(url.hostname, url.port, url.username) elif url.scheme == "fake": self.connect_fake() else: raise NotFound("Invalid CVS origin URL '%s'" % url) # we should have a connection now assert self.socket or self.ssh self.conn_write_str( "Root %s\nValid-responses %s\nvalid-requests\n" "UseUnchanged\n" % (self.cvsroot_path, " ".join(VALID_RESPONSES)) ) response = self.conn_read_line() if not response: raise CVSProtocolError("No response from CVS server") try: if response[0:15] != b"Valid-requests ": raise CVSProtocolError( "Invalid response from " "CVS server: %s" % response ) except IndexError: raise CVSProtocolError("Invalid response from CVS server: %s" % response) response = self.conn_read_line() if response != b"ok\n": raise CVSProtocolError("Invalid response from CVS server: %s" % response) def __del__(self): self.conn_close() def _parse_rlog_response(self, fp): rlog_output = tempfile.TemporaryFile() expect_error = False for line in fp.readlines(): if expect_error: raise CVSProtocolError("CVS server error: %s" % line) if line == b"ok\n": break elif line[0:2] == b"M ": rlog_output.write(line[2:]) elif line[0:8] == b"MT text ": rlog_output.write(line[8:-1]) elif line[0:8] == b"MT date ": rlog_output.write(line[8:-1]) elif line[0:10] == b"MT newline": rlog_output.write(line[10:]) elif line[0:7] == b"error ": expect_error = True continue else: raise CVSProtocolError("Bad CVS protocol response: %s" % line) rlog_output.seek(0) return rlog_output - def fetch_rlog(self, path="", state=""): - path_arg = path or self.cvs_module_name + def fetch_rlog(self, path: bytes = b"", state=""): + if path: + path_arg, encoding = decode_path(path) + else: + path_arg, encoding = self.cvs_module_name, "utf-8" + if len(state) > 0: state_arg = "Argument -s%s\n" % state else: state_arg = "" fp = tempfile.TemporaryFile() self.conn_write_str( "Global_option -q\n" f"{state_arg}" "Argument --\n" f"Argument {path_arg}\n" - "rlog\n" + "rlog\n", + encoding=encoding, ) while True: response = self.conn_read_line() if response is None: raise CVSProtocolError("No response from CVS server") if response[0:2] == b"E ": if len(path) > 0 and response[-11:] == b" - ignored\n": response = self.conn_read_line() if response != b"error \n": raise CVSProtocolError( "Invalid response from CVS server: %s" % response ) return None # requested path does not exist (ignore) raise CVSProtocolError("Error response from CVS server: %s" % response) fp.write(response) if response == b"ok\n": break fp.seek(0) return self._parse_rlog_response(fp) - def checkout(self, path, rev, dest_dir, expand_keywords): + def checkout(self, path: bytes, rev: str, dest_dir: bytes, expand_keywords: bool): """ Download a file revision from the cvs server and store the file's contents in a temporary file. If expand_keywords is set then ask the server to expand RCS keywords in file content. From the server's point of view this function behaves much like 'cvs update -r rev path'. The server is unaware that we do not actually maintain a CVS working copy. Because of this it sends more information than we need. We simply skip responses that are of no interest to us. """ skip_line = False expect_modeline = False expect_bytecount = False have_bytecount = False bytecount = 0 - dirname = os.path.dirname(path) + + path_str, encoding = decode_path(path) + + dirname = os.path.dirname(path_str) if dirname: self.conn_write_str( "Directory %s\n%s\n" % (dirname, os.path.join(self.cvsroot_path, dirname)) ) - filename = os.path.basename(path) + filename = os.path.basename(path_str) co_output = tempfile.NamedTemporaryFile( - dir=dest_dir, + dir=os.fsdecode(dest_dir), delete=True, prefix="cvsclient-checkout-%s-r%s-" % (filename, rev), ) if expand_keywords: # use server-side per-file default expansion rules karg = "" else: # force binary file mode karg = "Argument -kb\n" # TODO: cvs <= 1.10 servers expect to be given every Directory along the path. self.conn_write_str( "Directory %s\n%s\n" "Global_option -q\n" "Argument -r%s\n" "%s" "Argument --\nArgument %s\nco \n" % ( self.cvs_module_name, os.path.join(self.cvsroot_path, self.cvs_module_name), rev, karg, - path, - ) + path_str, + ), + encoding=encoding, ) while True: if have_bytecount: if bytecount < 0: raise CVSProtocolError("server sent too much file content data") response = self.conn_read_line(require_newline=False) if response is None: raise CVSProtocolError("Incomplete response from CVS server") if len(response) > bytecount: # When a file lacks a final newline we receive a line which # contains file content as well as CVS protocol response data. # Split last line of file content from CVS protocol data... co_output.write(response[:bytecount]) response = response[bytecount:] bytecount = 0 # ...and process the CVS protocol response below. else: co_output.write(response) bytecount -= len(response) continue else: response = self.conn_read_line() if response[0:2] == b"E ": raise CVSProtocolError("Error from CVS server: %s" % response) if response == b"ok\n": if have_bytecount: break else: raise CVSProtocolError("server sent 'ok' but no file contents") if skip_line: skip_line = False continue elif expect_bytecount: try: bytecount = int(response[0:-1]) # strip trailing \n except ValueError: raise CVSProtocolError("Bad CVS protocol response: %s" % response) have_bytecount = True continue elif response in (b"M \n", b"MT +updated\n", b"MT -updated\n"): continue elif response[0:9] == b"MT fname ": continue elif response.split(b" ")[0] in ( b"Created", b"Checked-in", b"Update-existing", b"Updated", b"Removed", ): skip_line = True continue elif response[0:1] == b"/": expect_modeline = True continue elif expect_modeline and response[0:2] == b"u=": expect_modeline = False expect_bytecount = True continue elif response[0:2] == b"M ": continue elif response[0:8] == b"MT text ": continue elif response[0:10] == b"MT newline": continue else: raise CVSProtocolError("Bad CVS protocol response: %s" % response) co_output.seek(0) return co_output diff --git a/swh/loader/cvs/loader.py b/swh/loader/cvs/loader.py index d44a756..0aaa3c6 100644 --- a/swh/loader/cvs/loader.py +++ b/swh/loader/cvs/loader.py @@ -1,655 +1,661 @@ # Copyright (C) 2015-2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information """Loader in charge of injecting either new or existing cvs repositories to swh-storage. """ from datetime import datetime import os import os.path import subprocess import tempfile import time from typing import Any, BinaryIO, Dict, Iterator, List, Optional, Sequence, Tuple, cast from urllib.parse import urlparse import sentry_sdk from tenacity import retry from tenacity.retry import retry_if_exception_type from tenacity.stop import stop_after_attempt from swh.loader.core.loader import BaseLoader from swh.loader.core.utils import clean_dangling_folders from swh.loader.cvs.cvs2gitdump.cvs2gitdump import ( CHANGESET_FUZZ_SEC, ChangeSetKey, CvsConv, FileRevision, RcsKeywords, file_path, ) -from swh.loader.cvs.cvsclient import CVSClient +from swh.loader.cvs.cvsclient import CVSClient, decode_path import swh.loader.cvs.rcsparse as rcsparse from swh.loader.cvs.rlog import RlogConv from swh.loader.exception import NotFound from swh.model import from_disk, hashutil from swh.model.model import ( Content, Directory, Person, Revision, RevisionType, Sha1Git, SkippedContent, Snapshot, SnapshotBranch, TargetType, TimestampWithTimezone, ) from swh.storage.algos.snapshot import snapshot_get_latest from swh.storage.interface import StorageInterface DEFAULT_BRANCH = b"HEAD" TEMPORARY_DIR_PREFIX_PATTERN = "swh.loader.cvs." def rsync_retry(): return retry( retry=retry_if_exception_type(subprocess.CalledProcessError), stop=stop_after_attempt(max_attempt_number=4), reraise=True, ) class BadPathException(Exception): pass class CvsLoader(BaseLoader): """Swh cvs loader. The repository is local. The loader deals with update on an already previously loaded repository. """ visit_type = "cvs" cvs_module_name: str cvsclient: CVSClient # remote CVS repository access (history is parsed from CVS rlog): rlog_file: BinaryIO swh_revision_gen: Iterator[ Tuple[List[Content], List[SkippedContent], List[Directory], Revision] ] def __init__( self, storage: StorageInterface, url: str, origin_url: Optional[str] = None, visit_date: Optional[datetime] = None, cvsroot_path: Optional[str] = None, temp_directory: str = "/tmp", **kwargs: Any, ): self.cvsroot_url = url # origin url as unique identifier for origin in swh archive origin_url = origin_url if origin_url else self.cvsroot_url super().__init__(storage=storage, origin_url=origin_url, **kwargs) self.temp_directory = temp_directory # internal state used to store swh objects self._contents: List[Content] = [] self._skipped_contents: List[SkippedContent] = [] self._directories: List[Directory] = [] self._revisions: List[Revision] = [] # internal state, current visit self._last_revision: Optional[Revision] = None self._visit_status = "full" self.visit_date = visit_date or self.visit_date self.cvsroot_path = cvsroot_path self.custom_id_keyword = None self.excluded_keywords: List[str] = [] self.snapshot: Optional[Snapshot] = None self.last_snapshot: Optional[Snapshot] = snapshot_get_latest( self.storage, self.origin.url ) def compute_swh_revision( self, k: ChangeSetKey, logmsg: Optional[bytes] ) -> Tuple[Revision, from_disk.Directory]: """Compute swh hash data per CVS changeset. Returns: tuple (rev, swh_directory) - rev: current SWH revision computed from checked out work tree - swh_directory: dictionary of path, swh hash data with type """ # Compute SWH revision from the on-disk state swh_dir = from_disk.Directory.from_disk(path=os.fsencode(self.worktree_path)) parents: Tuple[Sha1Git, ...] if self._last_revision: parents = (self._last_revision.id,) else: parents = () revision = self.build_swh_revision(k, logmsg, swh_dir.hash, parents) self.log.debug("SWH revision ID: %s", hashutil.hash_to_hex(revision.id)) self._last_revision = revision return (revision, swh_dir) - def file_path_is_safe(self, wtpath): - if "%s..%s" % (os.path.sep, os.path.sep) in wtpath: + def file_path_is_safe(self, wtpath: bytes): + tempdir = os.fsencode(self.tempdir_path) + if os.fsencode("%s..%s" % (os.path.sep, os.path.sep)) in wtpath: # Paths with back-references should not appear # in CVS protocol messages or CVS rlog output return False - elif ( - os.path.commonpath([self.tempdir_path, os.path.normpath(wtpath)]) - != self.tempdir_path - ): + elif os.path.commonpath([tempdir, os.path.normpath(wtpath)]) != tempdir: # The path must be a child of our temporary directory. return False else: return True def checkout_file_with_rcsparse( self, k: ChangeSetKey, f: FileRevision, rcsfile: rcsparse.rcsfile ) -> None: assert self.cvsroot_path assert self.server_style_cvsroot - path = file_path(self.cvsroot_path, f.path) - wtpath = os.path.join(self.tempdir_path, path) + path = file_path(os.fsencode(self.cvsroot_path), f.path) + wtpath = os.path.join(os.fsencode(self.tempdir_path), path) if not self.file_path_is_safe(wtpath): - raise BadPathException(f"unsafe path found in RCS file: {f.path}") + raise BadPathException(f"unsafe path found in RCS file: {f.path!r}") self.log.debug("rev %s state %s file %s", f.rev, f.state, f.path) if f.state == "dead": # remove this file from work tree try: os.remove(wtpath) except FileNotFoundError: pass else: # create, or update, this file in the work tree if not rcsfile: rcsfile = rcsparse.rcsfile(f.path) rcs = RcsKeywords() # We try our best to generate the same commit hashes over both pserver # and rsync. To avoid differences in file content due to expansion of # RCS keywords which contain absolute file paths (such as "Header"), # attempt to expand such paths in the same way as a regular CVS server # would expand them. # Whether this will avoid content differences depends on pserver and # rsync servers exposing the same server-side path to the CVS repository. # However, this is the best we can do, and only matters if an origin can # be fetched over both pserver and rsync. Each will still be treated as # a distinct origin, but will hopefully point at the same SWH snapshot. # In any case, an absolute path based on the origin URL looks nicer than # an absolute path based on a temporary directory used by the CVS loader. - server_style_path = f.path.replace( + + path_str, encoding = decode_path(f.path) + + server_style_path = path_str.replace( self.cvsroot_path, self.server_style_cvsroot ) if server_style_path[0] != "/": server_style_path = "/" + server_style_path if self.custom_id_keyword is not None: rcs.add_id_keyword(self.custom_id_keyword) contents = rcs.expand_keyword( - server_style_path, rcsfile, f.rev, self.excluded_keywords + server_style_path, + rcsfile, + f.rev, + self.excluded_keywords, + filename_encoding=encoding, ) os.makedirs(os.path.dirname(wtpath), exist_ok=True) outfile = open(wtpath, mode="wb") outfile.write(contents) outfile.close() def checkout_file_with_cvsclient( self, k: ChangeSetKey, f: FileRevision, cvsclient: CVSClient ): assert self.cvsroot_path - path = file_path(self.cvsroot_path, f.path) - wtpath = os.path.join(self.tempdir_path, path) + path = file_path(os.fsencode(self.cvsroot_path), f.path) + wtpath = os.path.join(os.fsencode(self.tempdir_path), path) if not self.file_path_is_safe(wtpath): - raise BadPathException(f"unsafe path found in cvs rlog output: {f.path}") + raise BadPathException(f"unsafe path found in cvs rlog output: {f.path!r}") self.log.debug("rev %s state %s file %s", f.rev, f.state, f.path) if f.state == "dead": # remove this file from work tree try: os.remove(wtpath) except FileNotFoundError: pass else: dirname = os.path.dirname(wtpath) os.makedirs(dirname, exist_ok=True) self.log.debug("checkout to %s\n", wtpath) fp = cvsclient.checkout(path, f.rev, dirname, expand_keywords=True) os.rename(fp.name, wtpath) try: fp.close() except FileNotFoundError: # Well, we have just renamed the file... pass def process_cvs_changesets( self, cvs_changesets: List[ChangeSetKey], use_rcsparse: bool, ) -> Iterator[ Tuple[List[Content], List[SkippedContent], List[Directory], Revision] ]: """Process CVS revisions. At each CVS revision, check out contents and compute swh hashes. Yields: tuple (contents, skipped-contents, directories, revision) of dict as a dictionary with keys, sha1_git, sha1, etc... """ for k in cvs_changesets: tstr = time.strftime("%c", time.gmtime(k.max_time)) self.log.debug( "changeset from %s by %s on branch %s", tstr, k.author, k.branch ) logmsg: Optional[bytes] = b"" # Check out all files of this revision and get a log message. # # The log message is obtained from the first file in the changeset. # The message will usually be the same for all affected files, and # the SWH archive will only store one version of the log message. for f in k.revs: rcsfile = None if use_rcsparse: if rcsfile is None: rcsfile = rcsparse.rcsfile(f.path) if not logmsg: logmsg = rcsfile.getlog(k.revs[0].rev) self.checkout_file_with_rcsparse(k, f, rcsfile) else: if not logmsg: logmsg = self.rlog.getlog(self.rlog_file, f.path, k.revs[0].rev) self.checkout_file_with_cvsclient(k, f, self.cvsclient) # TODO: prune empty directories? (revision, swh_dir) = self.compute_swh_revision(k, logmsg) (contents, skipped_contents, directories) = from_disk.iter_directory( swh_dir ) yield contents, skipped_contents, directories, revision def pre_cleanup(self) -> None: """Cleanup potential dangling files from prior runs (e.g. OOM killed tasks) """ clean_dangling_folders( self.temp_directory, pattern_check=TEMPORARY_DIR_PREFIX_PATTERN, log=self.log, ) def cleanup(self) -> None: self.log.debug("cleanup") def configure_custom_id_keyword(self, cvsconfig): """Parse CVSROOT/config and look for a custom keyword definition. There are two different configuration directives in use for this purpose. The first variant stems from a patch which was never accepted into upstream CVS and uses the tag directive: tag=MyName With this, the "MyName" keyword becomes an alias for the "Id" keyword. This variant is prelevant in CVS versions shipped on BSD. The second variant stems from upstream CVS 1.12 and looks like: LocalKeyword=MyName=SomeKeyword KeywordExpand=iMyName We only support "SomeKeyword" if it specifies "Id" or "CVSHeader", for now. The KeywordExpand directive can be used to suppress expansion of keywords by listing keywords after an initial "e" character ("exclude", as opposed to an "include" list which uses an initial "i" character). For example, this disables expansion of the Date and Name keywords: KeywordExpand=eDate,Name """ for line in cvsconfig.readlines(): line = line.strip() try: (config_key, value) = line.split("=", 1) except ValueError: continue config_key = config_key.strip() value = value.strip() if config_key == "tag": self.custom_id_keyword = value elif config_key == "LocalKeyword": try: (custom_kwname, kwname) = value.split("=", 1) except ValueError: continue if kwname.strip() in ("Id", "CVSHeader"): self.custom_id_keyword = custom_kwname.strip() elif config_key == "KeywordExpand" and value.startswith("e"): excluded_keywords = value[1:].split(",") for k in excluded_keywords: self.excluded_keywords.append(k.strip()) @rsync_retry() def execute_rsync( self, rsync_cmd: List[str], **run_opts ) -> subprocess.CompletedProcess: rsync = subprocess.run(rsync_cmd, **run_opts) rsync.check_returncode() return rsync def fetch_cvs_repo_with_rsync(self, host: str, path: str) -> None: # URL *must* end with a trailing slash in order to get CVSROOT listed url = "rsync://%s%s/" % (host, os.path.dirname(path)) rsync = self.execute_rsync( ["rsync", url], capture_output=True, encoding="ascii" ) have_cvsroot = False have_module = False for line in rsync.stdout.split("\n"): self.log.debug("rsync server: %s", line) if line.endswith(" CVSROOT"): have_cvsroot = True elif line.endswith(" %s" % self.cvs_module_name): have_module = True if have_module and have_cvsroot: break if not have_module: raise NotFound(f"CVS module {self.cvs_module_name} not found at {url}") if not have_cvsroot: raise NotFound(f"No CVSROOT directory found at {url}") # Fetch the CVSROOT directory and the desired CVS module. assert self.cvsroot_path for d in ("CVSROOT", self.cvs_module_name): target_dir = os.path.join(self.cvsroot_path, d) os.makedirs(target_dir, exist_ok=True) # Append trailing path separators ("/" in the URL and os.path.sep in the # local target directory path) to ensure that rsync will place files # directly within our target directory . self.execute_rsync( ["rsync", "-az", url + d + "/", target_dir + os.path.sep] ) def prepare(self) -> None: self._last_revision = None self.tempdir_path = tempfile.mkdtemp( suffix="-%s" % os.getpid(), prefix=TEMPORARY_DIR_PREFIX_PATTERN, dir=self.temp_directory, ) url = urlparse(self.origin.url) self.log.debug( "prepare; origin_url=%s scheme=%s path=%s", self.origin.url, url.scheme, url.path, ) if not url.path: raise NotFound(f"Invalid CVS origin URL '{self.origin.url}'") self.cvs_module_name = os.path.basename(url.path) self.server_style_cvsroot = os.path.dirname(url.path) self.worktree_path = os.path.join(self.tempdir_path, self.cvs_module_name) if url.scheme == "file" or url.scheme == "rsync": # local CVS repository conversion if not self.cvsroot_path: self.cvsroot_path = tempfile.mkdtemp( suffix="-%s" % os.getpid(), prefix=TEMPORARY_DIR_PREFIX_PATTERN, dir=self.temp_directory, ) if url.scheme == "file": if not os.path.exists(url.path): raise NotFound elif url.scheme == "rsync": assert url.hostname is not None self.fetch_cvs_repo_with_rsync(url.hostname, url.path) have_rcsfile = False have_cvsroot = False - for root, dirs, files in os.walk(self.cvsroot_path): - if "CVSROOT" in dirs: + for root, dirs, files in os.walk(os.fsencode(self.cvsroot_path)): + if b"CVSROOT" in dirs: have_cvsroot = True - dirs.remove("CVSROOT") + dirs.remove(b"CVSROOT") continue for f in files: filepath = os.path.join(root, f) - if f[-2:] == ",v": + if f[-2:] == b",v": rcsfile = rcsparse.rcsfile(filepath) # noqa: F841 self.log.debug( "Looks like we have data to convert; " "found a valid RCS file at %s", filepath, ) have_rcsfile = True break if have_rcsfile: break if not have_rcsfile: raise NotFound( f"Directory {self.cvsroot_path} does not contain any valid " "RCS files", ) if not have_cvsroot: self.log.warn( "The CVS repository at '%s' lacks a CVSROOT directory; " "we might be ingesting an incomplete copy of the repository", self.cvsroot_path, ) # The file CVSROOT/config will usually contain ASCII data only. # We allow UTF-8 just in case. Other encodings may result in an # error and will require manual intervention, for now. cvsconfig_path = os.path.join(self.cvsroot_path, "CVSROOT", "config") cvsconfig = open(cvsconfig_path, mode="r", encoding="utf-8") self.configure_custom_id_keyword(cvsconfig) cvsconfig.close() # Unfortunately, there is no way to convert CVS history in an # iterative fashion because the data is not indexed by any kind # of changeset ID. We need to walk the history of each and every # RCS file in the repository during every visit, even if no new # changes will be added to the SWH archive afterwards. # "CVS’s repository is the software equivalent of a telephone book # sorted by telephone number." # https://corecursive.com/software-that-doesnt-suck-with-jim-blandy/ # # An implicit assumption made here is that self.cvs_changesets will # fit into memory in its entirety. If it won't fit then the CVS walker # will need to be modified such that it spools the list of changesets # to disk instead. cvs = CvsConv(self.cvsroot_path, RcsKeywords(), False, CHANGESET_FUZZ_SEC) self.log.debug("Walking CVS module %s", self.cvs_module_name) cvs.walk(self.cvs_module_name) cvs_changesets = sorted(cvs.changesets) self.log.debug( "CVS changesets found in %s: %d", self.cvs_module_name, len(cvs_changesets), ) self.swh_revision_gen = self.process_cvs_changesets( cvs_changesets, use_rcsparse=True ) elif url.scheme == "pserver" or url.scheme == "fake" or url.scheme == "ssh": # remote CVS repository conversion if not self.cvsroot_path: self.cvsroot_path = os.path.dirname(url.path) self.cvsclient = CVSClient(url) cvsroot_path = os.path.dirname(url.path) self.log.debug( "Fetching CVS rlog from %s:%s/%s", url.hostname, cvsroot_path, self.cvs_module_name, ) self.rlog = RlogConv(cvsroot_path, CHANGESET_FUZZ_SEC) main_rlog_file = self.cvsclient.fetch_rlog() self.rlog.parse_rlog(main_rlog_file) # Find file deletion events only visible in Attic directories. main_changesets = self.rlog.changesets attic_paths = [] attic_rlog_files = [] assert self.cvsroot_path + cvsroot_path_bytes = os.fsencode(self.cvsroot_path) for k in main_changesets: for changed_file in k.revs: - path = file_path(self.cvsroot_path, changed_file.path) - if path.startswith(self.cvsroot_path): + path = file_path(cvsroot_path_bytes, changed_file.path) + if path.startswith(cvsroot_path_bytes): path = path[ - len(os.path.commonpath([self.cvsroot_path, path])) + 1 : + len(os.path.commonpath([cvsroot_path_bytes, path])) + 1 : ] parent_path = os.path.dirname(path) - if parent_path.split("/")[-1] == "Attic": + if parent_path.split(b"/")[-1] == b"Attic": continue - attic_path = parent_path + "/Attic" + attic_path = parent_path + b"/Attic" if attic_path in attic_paths: continue attic_paths.append(attic_path) # avoid multiple visits # Try to fetch more rlog data from this Attic directory. attic_rlog_file = self.cvsclient.fetch_rlog( path=attic_path, state="dead", ) if attic_rlog_file: attic_rlog_files.append(attic_rlog_file) if len(attic_rlog_files) == 0: self.rlog_file = main_rlog_file else: # Combine all the rlog pieces we found and re-parse. fp = tempfile.TemporaryFile() for attic_rlog_file in attic_rlog_files: for line in attic_rlog_file.readlines(): fp.write(line) attic_rlog_file.close() main_rlog_file.seek(0) for line in main_rlog_file.readlines(): fp.write(line) main_rlog_file.close() fp.seek(0) self.rlog.parse_rlog(cast(BinaryIO, fp)) self.rlog_file = cast(BinaryIO, fp) cvs_changesets = sorted(self.rlog.changesets) self.log.debug( "CVS changesets found for %s: %d", self.cvs_module_name, len(cvs_changesets), ) self.swh_revision_gen = self.process_cvs_changesets( cvs_changesets, use_rcsparse=False ) else: raise NotFound(f"Invalid CVS origin URL '{self.origin.url}'") def fetch_data(self) -> bool: """Fetch the next CVS revision.""" try: data = next(self.swh_revision_gen) except StopIteration: assert self._last_revision is not None self.snapshot = self.generate_and_load_snapshot(self._last_revision) self.log.debug( "SWH snapshot ID: %s", hashutil.hash_to_hex(self.snapshot.id) ) self.flush() self.loaded_snapshot_id = self.snapshot.id return False except Exception: self.log.exception("Exception in fetch_data:") sentry_sdk.capture_exception() self._visit_status = "failed" return False # Stopping iteration self._contents, self._skipped_contents, self._directories, rev = data self._revisions = [rev] return True def build_swh_revision( self, k: ChangeSetKey, logmsg: Optional[bytes], dir_id: bytes, parents: Sequence[bytes], ) -> Revision: """Given a CVS revision, build a swh revision. Args: k: changeset data logmsg: the changeset's log message dir_id: the tree's hash identifier parents: the revision's parents identifier Returns: The swh revision dictionary. """ author = Person.from_fullname(k.author.encode("UTF-8")) date = TimestampWithTimezone.from_dict(k.max_time) return Revision( type=RevisionType.CVS, date=date, committer_date=date, directory=dir_id, message=logmsg, author=author, committer=author, synthetic=True, extra_headers=[], parents=tuple(parents), ) def generate_and_load_snapshot(self, revision: Revision) -> Snapshot: """Create the snapshot either from existing revision. Args: revision (dict): Last revision seen if any (None by default) Returns: Optional[Snapshot] The newly created snapshot """ snap = Snapshot( branches={ DEFAULT_BRANCH: SnapshotBranch( target=revision.id, target_type=TargetType.REVISION ) } ) self.log.debug("snapshot: %s", snap) self.storage.snapshot_add([snap]) return snap def store_data(self) -> None: "Add our current CVS changeset to the archive." self.storage.skipped_content_add(self._skipped_contents) self.storage.content_add(self._contents) self.storage.directory_add(self._directories) self.storage.revision_add(self._revisions) self.flush() self._skipped_contents = [] self._contents = [] self._directories = [] self._revisions = [] def load_status(self) -> Dict[str, Any]: if self.snapshot is None: load_status = "failed" elif self.last_snapshot == self.snapshot: load_status = "uneventful" else: load_status = "eventful" return { "status": load_status, } def visit_status(self) -> str: return self._visit_status diff --git a/swh/loader/cvs/rcsparse.pyi b/swh/loader/cvs/rcsparse.pyi index b5a7498..6aab7d2 100644 --- a/swh/loader/cvs/rcsparse.pyi +++ b/swh/loader/cvs/rcsparse.pyi @@ -1,27 +1,27 @@ # Copyright (C) 2021 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from collections.abc import Mapping from typing import Any, List, Tuple def __getattr__(name) -> Any: ... class rcsfile: head: str branch: str access: List[str] symbols: Mapping[str, str] # actually rcsparse.rcstokmap locks: Mapping[str, str] # actually rcsparse.rcstokmap strict: bool comment: str expand: str revs: Mapping[str, Tuple[str, int, str, str, List[str], str, str]] # actually rcsparse.rcsrevtree desc: str - def __init__(self, path: str): ... + def __init__(self, path: bytes): ... def checkout(self, rev: str = "HEAD") -> bytes: ... def getlog(self, rev: str) -> bytes: ... def sym2rev(self, rev: str = "HEAD") -> str: ... diff --git a/swh/loader/cvs/rcsparse/py-rcsparse.c b/swh/loader/cvs/rcsparse/py-rcsparse.c index 2bc6309..32da489 100644 --- a/swh/loader/cvs/rcsparse/py-rcsparse.c +++ b/swh/loader/cvs/rcsparse/py-rcsparse.c @@ -1,842 +1,843 @@ /* * This file is part of rcsparse. * * rcsparse is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * rcsparse is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with rcsparse. If not, see . */ #include #include #include #include "queue.h" #include "rcsparse.h" #if PY_MAJOR_VERSION >= 3 #define PyString_AsStringAndSize _PyUnicode_AsUTF8AndSize #define PyString_CheckExact PyUnicode_CheckExact #define PyString_FromString PyUnicode_FromString #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #endif static void _PyUnicode_AsUTF8AndSize(PyObject *obj, char **strp, Py_ssize_t *sizep) { *strp = PyUnicode_AsUTF8AndSize(obj, sizep); } static PyObject * rcstoken2pystr(struct rcstoken *tok) { if (tok == NULL) Py_RETURN_NONE; return PyString_FromStringAndSize(tok->str, tok->len); } static PyObject * rcstoklist2py(struct rcstoklist *head) { PyObject *list; struct rcstoken *tok; list = PyList_New(0); if (list == NULL) return NULL; for (tok = SLIST_FIRST(head); tok != NULL; tok = SLIST_NEXT(tok, link)) { PyObject *o; o = rcstoken2pystr(tok); if (PyList_Append(list, o) < 0) { Py_XDECREF(o); Py_XDECREF(list); return NULL; } Py_XDECREF(o); } return list; } struct pyrcsrevtree { PyObject_HEAD struct pyrcsfile *pyrcs; struct rcsrevtree *tree; }; static int pyrcsrevtree_find_internal(struct pyrcsrevtree *self, PyObject *key, struct rcsrev **frev) { struct rcsrev rev; struct rcstoken tok; Py_ssize_t l; if (!PyString_CheckExact(key)) return -1; PyString_AsStringAndSize(key, &tok.str, &l); if (l < 0) return -1; tok.len = (unsigned)l; rev.rev = &tok; *frev = RB_FIND(rcsrevtree, self->tree, &rev); return *frev != NULL; } static PyObject * rcsrev2py(struct rcsrev *rev) { struct tm tm; const char *month; bzero(&tm, sizeof(struct tm)); #define readdate(str, dest, len) do { \ const char *pos; \ int scale; \ for (pos = str + len - 1, scale = 1; pos >= str; pos--, scale *= 10) \ if (*pos < '0' || *pos > '9') \ return PyErr_Format(PyExc_RuntimeError, "Invalid date format"); \ else \ dest += scale * (*pos - '0'); \ } while (0) if (rev->date->len == 17) { /* 2-digit year */ readdate(rev->date->str, tm.tm_year, 2); month = rev->date->str + 3; } else { /* 4-digit year */ readdate(rev->date->str, tm.tm_year, 4); tm.tm_year -= 1900; month = rev->date->str + 5; } readdate(month, tm.tm_mon, 2); tm.tm_mon--; readdate(month + 3, tm.tm_mday, 2); readdate(month + 6, tm.tm_hour, 2); readdate(month + 9, tm.tm_min, 2); readdate(month + 12, tm.tm_sec, 2); #undef readdate return Py_BuildValue("NNNNNNN", rcstoken2pystr(rev->rev), #if PY_MAJOR_VERSION >= 3 PyLong_FromLong(timegm(&tm)), #else PyInt_FromLong(timegm(&tm)), #endif rcstoken2pystr(rev->author), rcstoken2pystr(rev->state), rcstoklist2py(&rev->branches), rcstoken2pystr(rev->next), rcstoken2pystr(rev->commitid)); } static PyObject * pyrcsrevtree_find(struct pyrcsrevtree *self, PyObject *key) { struct rcsrev *frev; switch (pyrcsrevtree_find_internal(self, key, &frev)) { case 1: return rcsrev2py(frev); case 0: PyErr_SetObject(PyExc_KeyError, key); return NULL; case -1: default: return NULL; } } static PyObject * pyrcsrevtree_get(struct pyrcsrevtree *self, PyObject *args) { PyObject *key, *def = Py_None; struct rcsrev *frev; if (!PyArg_ParseTuple(args, "O|O", &key, &def)) return NULL; switch (pyrcsrevtree_find_internal(self, key, &frev)) { case 1: return rcsrev2py(frev); case 0: return Py_INCREF(def), def; case -1: default: return NULL; } } static int pyrcsrevtree_contains(struct pyrcsrevtree *self, PyObject *key) { struct rcsrev *rev; return pyrcsrevtree_find_internal(self, key, &rev); } static PyObject * pyrcsrevtree_has_key(struct pyrcsrevtree *self, PyObject *key) { switch (pyrcsrevtree_contains(self, key)) { case 1: Py_RETURN_TRUE; case 0: Py_RETURN_FALSE; case -1: default: return NULL; } } static PyObject * pyrcsrevtree_items(struct pyrcsrevtree *self) { PyObject *list; struct rcsrev *rev; list = PyList_New(0); if (list == NULL) return NULL; for (rev = RB_MIN(rcsrevtree, self->tree); rev != NULL; rev = RB_NEXT(rcsrevtree, self->tree, rev)) { PyObject *f, *s, *p; f = rcstoken2pystr(rev->rev); s = rcsrev2py(rev); p = PyTuple_Pack(2, f, s); Py_XDECREF(f); Py_XDECREF(s); if (PyList_Append(list, p) < 0) { Py_XDECREF(p); Py_DECREF(list); return NULL; } Py_XDECREF(p); } return list; } static PyObject * pyrcsrevtree_keys(struct pyrcsrevtree *self) { PyObject *list; struct rcsrev *rev; list = PyList_New(0); if (list == NULL) return NULL; for (rev = RB_MIN(rcsrevtree, self->tree); rev != NULL; rev = RB_NEXT(rcsrevtree, self->tree, rev)) { PyObject *i; i = rcstoken2pystr(rev->rev); if (PyList_Append(list, i) < 0) { Py_XDECREF(i); Py_DECREF(list); return NULL; } Py_XDECREF(i); } return list; } static PyObject * pyrcsrevtree_values(struct pyrcsrevtree *self) { PyObject *list; struct rcsrev *rev; list = PyList_New(0); if (list == NULL) return NULL; for (rev = RB_MIN(rcsrevtree, self->tree); rev != NULL; rev = RB_NEXT(rcsrevtree, self->tree, rev)) { PyObject *i; i = rcsrev2py(rev); if (PyList_Append(list, i) < 0) { Py_XDECREF(i); Py_DECREF(list); return NULL; } Py_XDECREF(i); } return list; } static void pyrcsrevtree_dealloc(struct pyrcsrevtree *self) { Py_DECREF((PyObject *)self->pyrcs); Py_TYPE(self)->tp_free(self); } static PyMappingMethods pyrcsrevtree_mapmethods = { NULL, (binaryfunc)pyrcsrevtree_find, NULL }; static PySequenceMethods pyrcsrevtree_seqmethods = { .sq_contains= (objobjproc)pyrcsrevtree_contains }; static PyMethodDef pyrcsrevtree_methods[] = { {"__contains__",(PyCFunction)pyrcsrevtree_has_key, METH_O | METH_COEXIST, NULL}, {"__getitem__", (PyCFunction)pyrcsrevtree_find, METH_O | METH_COEXIST, NULL}, {"has_key", (PyCFunction)pyrcsrevtree_has_key, METH_O, NULL}, {"get", (PyCFunction)pyrcsrevtree_get, METH_VARARGS, NULL}, {"keys", (PyCFunction)pyrcsrevtree_keys, METH_NOARGS, NULL}, {"items", (PyCFunction)pyrcsrevtree_items, METH_NOARGS, NULL}, {"values", (PyCFunction)pyrcsrevtree_values, METH_NOARGS, NULL}, {NULL} }; static PyTypeObject pyrcsrevtree_type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) .tp_name= "rcsparse.rcsrevtree", .tp_basicsize= sizeof(struct pyrcsrevtree), .tp_dealloc= (destructor)pyrcsrevtree_dealloc, .tp_as_mapping= &pyrcsrevtree_mapmethods, .tp_as_sequence= &pyrcsrevtree_seqmethods, .tp_flags= Py_TPFLAGS_DEFAULT, .tp_doc= "RCS Revision Tree Map", .tp_new= PyType_GenericNew, .tp_methods= pyrcsrevtree_methods }; static PyObject * rcsrevtree2py(struct pyrcsfile *pyrcs, struct rcsrevtree *tree) { struct pyrcsrevtree *pytree; if (tree == NULL) Py_RETURN_NONE; pytree = PyObject_New(struct pyrcsrevtree, &pyrcsrevtree_type); pytree->pyrcs = pyrcs; Py_INCREF((PyObject *)pyrcs); pytree->tree = tree; return (PyObject *)pytree; } struct pyrcstokmap { PyObject_HEAD struct pyrcsfile *pyrcs; struct rcstokmap *map; }; static int pyrcstokmap_find_internal(struct pyrcstokmap *self, PyObject *key, struct rcstokpair **fpair) { struct rcstokpair pair; struct rcstoken tok; Py_ssize_t l; if (!PyString_CheckExact(key)) return -1; PyString_AsStringAndSize(key, &tok.str, &l); if (l < 0) return -1; tok.len = (unsigned)l; pair.first = &tok; *fpair = RB_FIND(rcstokmap, self->map, &pair); return *fpair != NULL; } static PyObject * pyrcstokmap_find(struct pyrcstokmap *self, PyObject *key) { struct rcstokpair *fpair; switch (pyrcstokmap_find_internal(self, key, &fpair)) { case 1: return rcstoken2pystr(fpair->second); case 0: PyErr_SetObject(PyExc_KeyError, key); return NULL; case -1: default: return NULL; } } static PyObject * pyrcstokmap_get(struct pyrcstokmap *self, PyObject *args) { PyObject *key, *def = Py_None; struct rcstokpair *fpair; if (!PyArg_ParseTuple(args, "O|O", &key, &def)) return NULL; switch (pyrcstokmap_find_internal(self, key, &fpair)) { case 1: return rcstoken2pystr(fpair->second); case 0: return Py_INCREF(def), def; case -1: default: return NULL; } } static int pyrcstokmap_contains(struct pyrcstokmap *self, PyObject *key) { struct rcstokpair *pair; return pyrcstokmap_find_internal(self, key, &pair); } static PyObject * pyrcstokmap_has_key(struct pyrcstokmap *self, PyObject *key) { switch (pyrcstokmap_contains(self, key)) { case 1: Py_RETURN_TRUE; case 0: Py_RETURN_FALSE; case -1: default: return NULL; } } static PyObject * pyrcstokmap_items(struct pyrcstokmap *self) { PyObject *list; struct rcstokpair *pair; list = PyList_New(0); if (list == NULL) return NULL; for (pair = RB_MIN(rcstokmap, self->map); pair != NULL; pair = RB_NEXT(rcstokmap, self->map, pair)) { PyObject *f, *s, *p; f = rcstoken2pystr(pair->first); s = rcstoken2pystr(pair->second); p = PyTuple_Pack(2, f, s); Py_XDECREF(f); Py_XDECREF(s); if (PyList_Append(list, p) < 0) { Py_XDECREF(p); Py_DECREF(list); return NULL; } Py_XDECREF(p); } return list; } static PyObject * pyrcstokmap_keys(struct pyrcstokmap *self) { PyObject *list; struct rcstokpair *pair; list = PyList_New(0); if (list == NULL) return NULL; for (pair = RB_MIN(rcstokmap, self->map); pair != NULL; pair = RB_NEXT(rcstokmap, self->map, pair)) { PyObject *i; i = rcstoken2pystr(pair->first); if (PyList_Append(list, i) < 0) { Py_XDECREF(i); Py_DECREF(list); return NULL; } Py_XDECREF(i); } return list; } static PyObject * pyrcstokmap_values(struct pyrcstokmap *self) { PyObject *list; struct rcstokpair *pair; list = PyList_New(0); if (list == NULL) return NULL; for (pair = RB_MIN(rcstokmap, self->map); pair != NULL; pair = RB_NEXT(rcstokmap, self->map, pair)) { PyObject *i; i = rcstoken2pystr(pair->second); if (PyList_Append(list, i) < 0) { Py_XDECREF(i); Py_DECREF(list); return NULL; } Py_XDECREF(i); } return list; } static void pyrcstokmap_dealloc(struct pyrcstokmap *self) { Py_DECREF((PyObject *)self->pyrcs); Py_TYPE(self)->tp_free(self); } static PyMappingMethods pyrcstokmap_mapmethods = { NULL, (binaryfunc)pyrcstokmap_find, NULL }; static PySequenceMethods pyrcstokmap_seqmethods = { .sq_contains= (objobjproc)pyrcstokmap_contains }; static PyMethodDef pyrcstokmap_methods[] = { {"__contains__",(PyCFunction)pyrcstokmap_has_key, METH_O | METH_COEXIST, NULL}, {"__getitem__", (PyCFunction)pyrcstokmap_find, METH_O | METH_COEXIST, NULL}, {"has_key", (PyCFunction)pyrcstokmap_has_key, METH_O, NULL}, {"get", (PyCFunction)pyrcstokmap_get, METH_VARARGS, NULL}, {"keys", (PyCFunction)pyrcstokmap_keys, METH_NOARGS, NULL}, {"items", (PyCFunction)pyrcstokmap_items, METH_NOARGS, NULL}, {"values", (PyCFunction)pyrcstokmap_values, METH_NOARGS, NULL}, {NULL} }; static PyTypeObject pyrcstokmap_type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) .tp_name= "rcsparse.rcstokmap", .tp_basicsize= sizeof(struct pyrcstokmap), .tp_dealloc= (destructor)pyrcstokmap_dealloc, .tp_as_mapping= &pyrcstokmap_mapmethods, .tp_as_sequence= &pyrcstokmap_seqmethods, .tp_flags= Py_TPFLAGS_DEFAULT, .tp_doc= "RCS Token Map", .tp_new= PyType_GenericNew, .tp_methods= pyrcstokmap_methods }; static PyObject * rcstokmap2py(struct pyrcsfile *pyrcs, struct rcstokmap *map) { struct pyrcstokmap *pymap; if (map == NULL) Py_RETURN_NONE; pymap = PyObject_New(struct pyrcstokmap, &pyrcstokmap_type); pymap->pyrcs = pyrcs; Py_INCREF((PyObject *)pyrcs); pymap->map = map; return (PyObject *)pymap; } struct pyrcsfile { PyObject_HEAD struct rcsfile *rcs; }; enum { PYRCSADM_HEAD, PYRCSADM_BRANCH, PYRCSADM_SYMBOLS, PYRCSADM_LOCKS, PYRCSADM_COMMENT, PYRCSADM_EXPAND, PYRCSADM_DESC, }; static PyObject * pyrcsfile_getstr(struct pyrcsfile *self, void *closure) { struct rcstoken *tok; struct rcsadmin *adm; if (rcsparseadmin(self->rcs) < 0) return PyErr_Format(PyExc_RuntimeError, "Error parsing"); adm = &self->rcs->admin; switch ((int)(uintptr_t)closure) { case PYRCSADM_HEAD: tok = adm->head; break; case PYRCSADM_BRANCH: tok = adm->branch; break; case PYRCSADM_COMMENT: tok = adm->comment; break; case PYRCSADM_EXPAND: tok = adm->expand; break; case PYRCSADM_DESC: tok = adm->desc; break; default: return PyErr_Format(PyExc_RuntimeError, "Wrong closure"); } return rcstoken2pystr(tok); } static PyObject * pyrcsfile_gettokmap(struct pyrcsfile *self, void *closure) { struct rcstokmap *map; struct rcsadmin *adm; if (rcsparseadmin(self->rcs) < 0) return PyErr_Format(PyExc_RuntimeError, "Error parsing"); adm = &self->rcs->admin; switch ((int)(uintptr_t)closure) { case PYRCSADM_SYMBOLS: map = &adm->symbols; break; case PYRCSADM_LOCKS: map = &adm->locks; break; default: return PyErr_Format(PyExc_RuntimeError, "Wrong closure"); } return rcstokmap2py(self, map); } static PyObject * pyrcsfile_getaccess(struct pyrcsfile *self, void *closure) { if (rcsparseadmin(self->rcs) < 0) return PyErr_Format(PyExc_RuntimeError, "Error parsing"); return rcstoklist2py(&self->rcs->admin.access); } static PyObject * pyrcsfile_getstrict(struct pyrcsfile *self, void *closure) { if (rcsparseadmin(self->rcs) < 0) return PyErr_Format(PyExc_RuntimeError, "Error parsing"); if (self->rcs->admin.strict) Py_RETURN_TRUE; else Py_RETURN_FALSE; } static PyObject * pyrcsfile_checkout(struct pyrcsfile *self, PyObject *args) { PyObject *o; const char *rev = "HEAD"; char *buf; size_t len; if (!PyArg_ParseTuple(args, "|s", &rev)) return NULL; buf = rcscheckout(self->rcs, rev, &len); if (buf == NULL) return PyErr_Format(PyExc_RuntimeError, "Error parsing"); #if PY_MAJOR_VERSION >= 3 o = PyBytes_FromStringAndSize(buf, len); #else o = PyString_FromStringAndSize(buf, len); #endif free(buf); return o; } static PyObject * pyrcsfile_getlog(struct pyrcsfile *self, PyObject *args) { PyObject *o; const char *rev; char *buf; if (!PyArg_ParseTuple(args, "s", &rev)) return NULL; buf = rcsgetlog(self->rcs, rev); if (buf == NULL) return PyErr_Format(PyExc_RuntimeError, "Error parsing"); #if PY_MAJOR_VERSION >= 3 o = PyBytes_FromString(buf); #else o = PyString_FromString(buf); #endif free(buf); return o; } static PyObject * pyrcsfile_sym2rev(struct pyrcsfile *self, PyObject *args) { PyObject *o; const char *rev = "HEAD"; char *buf; if (!PyArg_ParseTuple(args, "|s", &rev)) return NULL; buf = rcsrevfromsym(self->rcs, rev); if (buf == NULL) return PyErr_Format(PyExc_RuntimeError, "Error parsing"); o = PyString_FromString(buf); free(buf); return o; } static PyObject * pyrcsfile_getrevs(struct pyrcsfile *self, void *closure) { if (rcsparsetree(self->rcs) < 0) return PyErr_Format(PyExc_RuntimeError, "Error parsing"); return rcsrevtree2py(self, &self->rcs->admin.revs); } static int pyrcsfile_init(struct pyrcsfile *pyrcs, PyObject *args) { const char *filename; + Py_ssize_t length; - if (!PyArg_ParseTuple(args, "s", &filename)) + if (!PyArg_ParseTuple(args, "s#", &filename, &length)) return -1; pyrcs->rcs = rcsopen(filename); if (pyrcs->rcs == NULL) { PyErr_SetFromErrnoWithFilename(PyExc_IOError, (char *)(long)filename); return -1; } return 0; } static void pyrcsfile_dealloc(struct pyrcsfile *self) { if (self->rcs != NULL) rcsclose(self->rcs); Py_TYPE(self)->tp_free(self); } static PyGetSetDef pyrcsfile_getseters[] = { {"head", (getter)pyrcsfile_getstr, NULL, "rcsfile head data", (void *)PYRCSADM_HEAD}, {"branch", (getter)pyrcsfile_getstr, NULL, "rcsfile branch data", (void *)PYRCSADM_BRANCH}, {"access", (getter)pyrcsfile_getaccess, NULL, "rcsfile access data", NULL}, {"symbols", (getter)pyrcsfile_gettokmap, NULL, "rcsfile symbols data", (void *)PYRCSADM_SYMBOLS}, {"locks", (getter)pyrcsfile_gettokmap, NULL, "rcsfile locks data", (void *)PYRCSADM_LOCKS}, {"strict", (getter)pyrcsfile_getstrict, NULL, "rcsfile strict data", NULL}, {"comment", (getter)pyrcsfile_getstr, NULL, "rcsfile comment data", (void *)PYRCSADM_COMMENT}, {"expand", (getter)pyrcsfile_getstr, NULL, "rcsfile expand data", (void *)PYRCSADM_EXPAND}, {"revs", (getter)pyrcsfile_getrevs, NULL, "rcsfile revs data", NULL}, {"desc", (getter)pyrcsfile_getstr, NULL, "rcsfile desc data", (void *)PYRCSADM_DESC}, {NULL} }; static PyMethodDef pyrcsfile_methods[] = { {"checkout", (PyCFunction)pyrcsfile_checkout, METH_VARARGS, NULL}, {"getlog", (PyCFunction)pyrcsfile_getlog, METH_VARARGS, NULL}, {"sym2rev", (PyCFunction)pyrcsfile_sym2rev, METH_VARARGS, NULL}, {NULL} }; static PyTypeObject pyrcsfile_type = { PyObject_HEAD_INIT(&PyType_Type) .tp_name= "rcsparse.rcsfile", .tp_basicsize= sizeof(struct pyrcsfile), .tp_dealloc= (destructor)pyrcsfile_dealloc, .tp_flags= Py_TPFLAGS_DEFAULT, .tp_doc= "RCS File", .tp_getset= pyrcsfile_getseters, .tp_init= (initproc)pyrcsfile_init, .tp_new= PyType_GenericNew, .tp_methods= pyrcsfile_methods, }; static PyMethodDef pyrcsparse_methods[] = { {NULL} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "rcsparse", /* m_name */ "RCS file parser", /* m_doc */ -1, /* m_size */ pyrcsparse_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PY_MAJOR_VERSION >= 3 #define retnull return NULL PyMODINIT_FUNC PyInit_rcsparse(void) #else #define retnull return PyMODINIT_FUNC initrcsparse(void) #endif { PyObject *m; if (PyType_Ready(&pyrcsfile_type) < 0) retnull; if (PyType_Ready(&pyrcstokmap_type) < 0) retnull; if (PyType_Ready(&pyrcsrevtree_type) < 0) retnull; #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else m = Py_InitModule3("rcsparse", pyrcsparse_methods, "RCS file parser"); #endif if (m == NULL) retnull; Py_INCREF(&pyrcsfile_type); PyModule_AddObject(m, "rcsfile", (PyObject *)&pyrcsfile_type); Py_INCREF(&pyrcstokmap_type); PyModule_AddObject(m, "rcstokmap", (PyObject *)&pyrcstokmap_type); Py_INCREF(&pyrcsrevtree_type); PyModule_AddObject(m, "rcsrevtree", (PyObject *)&pyrcsrevtree_type); #if PY_MAJOR_VERSION >= 3 return m; #endif } diff --git a/swh/loader/cvs/rlog.py b/swh/loader/cvs/rlog.py index 5a80e85..f11e498 100644 --- a/swh/loader/cvs/rlog.py +++ b/swh/loader/cvs/rlog.py @@ -1,523 +1,497 @@ """ RCS/CVS rlog parser, derived from viewvc and cvs2gitdump.py """ # Copyright (C) 1999-2021 The ViewCVS Group. All Rights Reserved. # # By using ViewVC, you agree to the terms and conditions set forth # below: # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Copyright (c) 2012 YASUOKA Masahiko # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import calendar import re import string import time from typing import BinaryIO, Dict, List, NamedTuple, Optional, Tuple from swh.loader.cvs.cvs2gitdump.cvs2gitdump import ChangeSetKey -# There is no known encoding of path names in CVS. The actual encoding used -# will depend on the CVS server's operating system and perhaps even the -# underlying filesystem used to host a CVS repository. -# It is even conceivable that a given repository may use multiple encodings, -# e.g. due to migrations of the repository between different servers over time. -# -# This issue also affects the CVS network protocol which is communicating -# paths between the CVS server and the CVS client. For this reason, most -# public-facing repositories should stick to ASCII in practice. -# -# TODO: If known, the actual path encoding used by the repository should -# be specified as a parameter. This parameter should be a list since -# multiple encodings may be present in a given repository. -path_encodings = ["ascii", "utf-8"] - class revtuple(NamedTuple): number: str date: int author: bytes state: str branches: None revnumstr: None commitid: Optional[str] class RlogConv: def __init__(self, cvsroot_path: str, fuzzsec: int) -> None: self.cvsroot_path = cvsroot_path self.fuzzsec = fuzzsec self.changesets: Dict[ChangeSetKey, ChangeSetKey] = dict() self.tags: Dict[str, ChangeSetKey] = dict() - self.offsets: Dict[str, Dict[str, int]] = dict() + self.offsets: Dict[bytes, Dict[str, int]] = dict() def _process_rlog_revisions( self, - path: str, + path: bytes, taginfo: Dict[bytes, bytes], revisions: Dict[str, revtuple], logmsgs: Dict[str, Optional[bytes]], ) -> None: """Convert RCS revision history of a file into self.changesets items""" rtags: Dict[str, List[str]] = dict() # RCS and CVS represent branches by adding digits to revision numbers. # And CVS assigns special meaning to certain revision number ranges. # # Revision numbers on the main branch have only two digits: # # 1.1, 1.2, 1.3, ... # # Branches created with 'cvs tag -b' use even numbers for # the third digit: # # 1.1, 1.2, 1.3, ... main branch history of the file # | # 1.1.2.1, 1.1.2.2 ... a branch (2) forked off r1.1 of the file # # Branches are given human-readable names by associating # RCS tag labels with their revision numbers. # Given a file on the above branch which has been changed 10 times # since history was forked, the branch tag would look like this: # # MY_BRANCH: r1.1.2.10 # # Odd branch numbers are reserved for CVS "vendor" branches. # The default vendor branch is 1.1.1. # Vendor branches are populated with 'cvs import'. # Files on the vendor branch are merged to the main branch automatically # unless there are merge conflicts. Such conflicts have to be resolved # manually each time 'cvs import' is used to update the vendor branch. # # See here for details: # https://www.gnu.org/software/trans-coord/manual/cvs/html_node/Branches-and-revisions.html#Branches-and-revisions # # There are also "magic" branch numbers with a zero inserted # at the second-rightmost position: # # 1.1, 1.2, 1.3, ... main branch history of the file # | # 1.1.2.0.1 magic branch (2) # # This allows CVS to store information about a branch's existence # before any files on this branch have been modified. # Even-numbered branch revisions appear once the file is modified. branches = {"1": "HEAD", "1.1.1": "VENDOR"} k: str v_: str for k, v_ in list(taginfo.items()): # type: ignore # FIXME, inconsistent types r = v_.split(".") if len(r) == 3: # vendor branch number branches[v_] = "VENDOR" elif len(r) >= 3 and r[-2] == "0": # magic branch number branches[".".join(r[:-2] + r[-1:])] = k if len(r) == 2 and branches[r[0]] == "HEAD": # main branch number if v_ not in rtags: rtags[v_] = list() rtags[v_].append(k) revs: List[Tuple[str, revtuple]] = list(revisions.items()) # sort by revision descending to priorize 1.1.1.1 than 1.1 revs.sort(key=lambda a: a[1][0], reverse=True) # sort by time revs.sort(key=lambda a: a[1][1]) novendor = False have_initial_revision = False last_vendor_status = None for k, v in revs: r = k.split(".") if ( len(r) == 4 and r[0] == "1" and r[1] == "1" and r[2] == "1" and r[3] == "1" ): if have_initial_revision: continue if v[3] == "dead": continue last_vendor_status = v[3] have_initial_revision = True elif len(r) == 4 and r[0] == "1" and r[1] == "1" and r[2] == "1": if novendor: continue last_vendor_status = v[3] elif len(r) == 2: if r[0] == "1" and r[1] == "1": if have_initial_revision: continue if v[3] == "dead": continue have_initial_revision = True elif r[0] == "1" and r[1] != "1": novendor = True if last_vendor_status == "dead" and v[3] == "dead": last_vendor_status = None continue last_vendor_status = None else: # trunk only continue b = ".".join(r[:-1]) # decode author name in a potentially lossy way; # it is only used for internal hashing in this case author = v[2].decode("utf-8", "ignore") logmsg = logmsgs[k] assert logmsg is not None a = ChangeSetKey(branches[b], author, v[1], logmsg, v[6], self.fuzzsec) a.put_file(path, k, v[3], 0) while a in self.changesets: c = self.changesets[a] del self.changesets[a] c.merge(a) a = c self.changesets[a] = a if k in rtags: for t in rtags[k]: if t not in self.tags or self.tags[t].max_time < a.max_time: self.tags[t] = a def parse_rlog(self, fp: BinaryIO) -> None: self.changesets = dict() self.tags = dict() self.offsets = dict() eof = None while eof != _EOF_LOG and eof != _EOF_ERROR: filename, branch, taginfo, lockinfo, errmsg, eof = _parse_log_header(fp) revisions: Dict[str, revtuple] = {} logmsgs: Dict[str, Optional[bytes]] = {} - path = "" + path = b"" if filename: - # There is no known encoding of filenames in CVS. - # Attempt to decode the path with our list of known encodings. - # If none of them work, forcefully decode the path assuming - # the final path encoding provided in the list. - for i, e in enumerate(path_encodings): - try: - how = "ignore" if i == len(path_encodings) - 1 else "strict" - fname = filename.decode(e, how) - break - except UnicodeError: - pass - path = fname + path = filename elif not eof: raise ValueError("No filename found in rlog header") while not eof: off = fp.tell() rev, logmsg, eof = _parse_log_entry(fp) if rev: revisions[rev[0]] = rev logmsgs[rev[0]] = logmsg if eof != _EOF_LOG and eof != _EOF_ERROR: if path not in self.offsets.keys(): self.offsets[path] = dict() if rev: self.offsets[path][rev[0]] = off self._process_rlog_revisions(path, taginfo, revisions, logmsgs) - def getlog(self, fp: BinaryIO, path: str, rev: str) -> Optional[bytes]: + def getlog(self, fp: BinaryIO, path: bytes, rev: str) -> Optional[bytes]: off = self.offsets[path][rev] fp.seek(off) _rev, logmsg, eof = _parse_log_entry(fp) return logmsg # if your rlog doesn't use 77 '=' characters, then this must change LOG_END_MARKER = b"=" * 77 + b"\n" ENTRY_END_MARKER = b"-" * 28 + b"\n" _EOF_FILE = b"end of file entries" # no more entries for this RCS file _EOF_LOG = b"end of log" # hit the true EOF on the pipe _EOF_ERROR = b"error message found" # rlog issued an error # rlog error messages look like # # rlog: filename/goes/here,v: error message # rlog: filename/goes/here,v:123: error message # # so we should be able to match them with a regex like # # ^rlog\: (.*)(?:\:\d+)?\: (.*)$ # # But for some reason the windows version of rlog omits the "rlog: " prefix # for the first error message when the standard error stream has been # redirected to a file or pipe. (the prefix is present in subsequent errors # and when rlog is run from the console). So the expression below is more # complicated _re_log_error = re.compile(rb"^(?:rlog\: )*(.*,v)(?:\:\d+)?\: (.*)$") # CVSNT error messages look like: # cvs rcsfile: `C:/path/to/file,v' does not appear to be a valid rcs file # cvs [rcsfile aborted]: C:/path/to/file,v: No such file or directory # cvs [rcsfile aborted]: cannot open C:/path/to/file,v: Permission denied _re_cvsnt_error = re.compile( rb"^(?:cvs rcsfile\: |cvs \[rcsfile aborted\]: )" rb"(?:\`(.*,v)' |" rb"cannot open (.*,v)\: |(.*,v)\: |)" rb"(.*)$" ) def _parse_log_header( fp: BinaryIO, ) -> Tuple[ bytes, bytes, Dict[bytes, bytes], Dict[bytes, bytes], bytes, Optional[bytes] ]: """Parse and RCS/CVS log header. fp is a file (pipe) opened for reading the log information. On entry, fp should point to the start of a log entry. On exit, fp will have consumed the separator line between the header and the first revision log. If there is no revision information (e.g. the "-h" switch was passed to rlog), then fp will consumed the file separator line on exit. Returns: filename, default branch, tag dictionary, lock dictionary, rlog error message, and eof flag """ filename = branch = msg = b"" taginfo: Dict[bytes, bytes] = {} # tag name => number lockinfo: Dict[bytes, bytes] = {} # revision => locker state = 0 # 0 = base, 1 = parsing symbols, 2 = parsing locks eof = None while 1: line = fp.readline() if not line: # the true end-of-file eof = _EOF_LOG break if state == 1: if line[0] == b"\t": [tag, rev] = [x.strip() for x in line.split(b":")] taginfo[tag] = rev else: # oops. this line isn't tag info. stop parsing tags. state = 0 if state == 2: if line[0] == b"\t": [locker, rev] = [x.strip() for x in line.split(b":")] lockinfo[rev] = locker else: # oops. this line isn't lock info. stop parsing tags. state = 0 if state == 0: if line == "\n": continue elif line[:9] == b"RCS file:": filename = line[10:-1] elif line[:5] == b"head:": # head = line[6:-1] pass elif line[:7] == b"branch:": branch = line[8:-1] elif line[:6] == b"locks:": # start parsing the lock information state = 2 elif line[:14] == b"symbolic names": # start parsing the tag information state = 1 elif line == ENTRY_END_MARKER: # end of the headers break elif line == LOG_END_MARKER: # end of this file's log information eof = _EOF_FILE break else: error = _re_cvsnt_error.match(line) if error: p1, p2, p3, msg = error.groups() filename = p1 or p2 or p3 if not filename: raise ValueError( "Could not get filename from CVSNT error:\n%r" % line ) eof = _EOF_ERROR break error = _re_log_error.match(line) if error: filename, msg = error.groups() if msg[:30] == b"warning: Unknown phrases like ": # don't worry about this warning. it can happen with some RCS # files that have unknown fields in them e.g. "permissions 644;" continue eof = _EOF_ERROR break return filename, branch, taginfo, lockinfo, msg, eof _re_log_info = re.compile( rb"^date:\s+([^;]+);" rb"\s+author:\s+([^;]+);" rb"\s+state:\s+([^;]+);" rb"(\s+lines:\s+([0-9\s+-]+);?)?" rb"(\s+commitid:\s+([a-zA-Z0-9]+);)?\n$" ) # TODO: _re_rev should be updated to extract the "locked" flag _re_rev = re.compile(rb"^revision\s+([0-9.]+).*") def cvs_strptime(timestr): try: return time.strptime(timestr, "%Y/%m/%d %H:%M:%S")[:-1] + (0,) except ValueError: return time.strptime(timestr, "%Y-%m-%d %H:%M:%S %z")[:-1] + (0,) def _parse_commitid(commitid: bytes) -> Optional[str]: s = commitid.decode("ascii").strip() # Strip "commitid: " tag and the trailing semicolon. s = s[len("commitid: ") : -len(";")] # The commitid itself contains digit and ASCII letters only: for c in s: if ( c not in string.digits and c not in string.ascii_lowercase and c not in string.ascii_uppercase ): raise ValueError("invalid commitid") return s def _parse_log_entry(fp) -> Tuple[Optional[revtuple], Optional[bytes], Optional[bytes]]: """Parse a single log entry. On entry, fp should point to the first line of the entry (the "revision" line). On exit, fp will have consumed the log separator line (dashes) or the end-of-file marker (equals). Returns: Revision data tuple (number string, date, author, state, branches, revnumstr, commitid) if any, log, and eof flag (see _EOF_*) """ rev = None line = fp.readline() if not line: return None, None, _EOF_LOG if line == LOG_END_MARKER: # Needed because some versions of RCS precede LOG_END_MARKER # with ENTRY_END_MARKER return None, None, _EOF_FILE if line[:8] == b"revision": match = _re_rev.match(line) if not match: return None, None, _EOF_LOG rev = match.group(1) line = fp.readline() if not line: return None, None, _EOF_LOG match = _re_log_info.match(line) eof = None log = b"" while 1: line = fp.readline() if not line: # true end-of-file eof = _EOF_LOG break if line[:9] == b"branches:": continue if line == ENTRY_END_MARKER: break if line == LOG_END_MARKER: # end of this file's log information eof = _EOF_FILE break log = log + line if not rev or not match: # there was a parsing error return None, None, eof # parse out a time tuple for the local time tm = cvs_strptime(match.group(1).decode("UTF-8")) # rlog seems to assume that two-digit years are 1900-based (so, "04" # comes out as "1904", not "2004"). EPOCH = 1970 if tm[0] < EPOCH: tm = list(tm) if (tm[0] - 1900) < 70: tm[0] = tm[0] + 100 if tm[0] < EPOCH: raise ValueError("invalid year") date = calendar.timegm(tm) commitid = match.group(6) or None if commitid: parsed_commitid = _parse_commitid(commitid) else: parsed_commitid = None # return a revision tuple compatible with 'rcsparse', the log message, # and the EOF marker return ( revtuple( rev.decode("ascii"), # revision number string date, match.group(2), # author (encoding is arbitrary; don't attempt to decode) match.group(3).decode( "ascii" ), # state, usually "Exp" or "dead"; non-ASCII data here would be weird None, # TODO: branches of this rev None, # TODO: revnumstr of previous rev parsed_commitid, ), log, eof, ) diff --git a/swh/loader/cvs/tests/test_loader.py b/swh/loader/cvs/tests/test_loader.py index 7df211c..dc8b915 100644 --- a/swh/loader/cvs/tests/test_loader.py +++ b/swh/loader/cvs/tests/test_loader.py @@ -1,1259 +1,1290 @@ # Copyright (C) 2016-2022 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information import os import subprocess import tempfile from typing import Any, Dict from urllib.parse import urlparse import pytest from swh.loader.cvs.cvsclient import CVSClient from swh.loader.cvs.loader import BadPathException, CvsLoader from swh.loader.tests import ( assert_last_visit_matches, check_snapshot, get_stats, prepare_repository_from_archive, ) from swh.model.hashutil import hash_to_bytes from swh.model.model import Snapshot, SnapshotBranch, TargetType RUNBABY_SNAPSHOT = Snapshot( id=hash_to_bytes("e64667c400049f560a3856580e0d9e511ffa66c9"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("0f6db8ce49472d7829ddd6141f71c68c0d563f0e"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_not_found_no_mock(swh_storage, tmp_path): """Given an unknown repository, the loader visit ends up in status not_found""" unknown_repo_url = "unknown-repository" loader = CvsLoader(swh_storage, unknown_repo_url, cvsroot_path=tmp_path) assert loader.load() == {"status": "uneventful"} assert_last_visit_matches( swh_storage, unknown_repo_url, status="not_found", type="cvs", ) def test_loader_cvs_visit(swh_storage, datadir, tmp_path): """Eventful visit should yield 1 snapshot""" archive_name = "runbaby" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=RUNBABY_SNAPSHOT.id, ) stats = get_stats(loader.storage) assert stats == { "content": 5, "directory": 1, "origin": 1, "origin_visit": 1, "release": 0, "revision": 1, "skipped_content": 0, "snapshot": 1, } check_snapshot(RUNBABY_SNAPSHOT, loader.storage) def test_loader_cvs_2_visits_no_change(swh_storage, datadir, tmp_path): """Eventful visit followed by uneventful visit should yield the same snapshot""" archive_name = "runbaby" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} visit_status1 = assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=RUNBABY_SNAPSHOT.id, ) loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "uneventful"} visit_status2 = assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=RUNBABY_SNAPSHOT.id, ) assert visit_status1.date < visit_status2.date assert visit_status1.snapshot == visit_status2.snapshot stats = get_stats(loader.storage) assert stats["origin_visit"] == 1 + 1 # computed twice the same snapshot assert stats["snapshot"] == 1 GREEK_SNAPSHOT = Snapshot( id=hash_to_bytes("c76f8b58a6dfbe6fccb9a85b695f914aa5c4a95a"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("e138207ddd5e1965b5ab9a522bfc2e0ecd233b67"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_with_file_additions_and_deletions(swh_storage, datadir, tmp_path): """Eventful conversion of history with file additions and deletions""" archive_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT.id, ) stats = get_stats(loader.storage) assert stats == { "content": 8, "directory": 13, "origin": 1, "origin_visit": 1, "release": 0, "revision": 7, "skipped_content": 0, "snapshot": 1, } check_snapshot(GREEK_SNAPSHOT, loader.storage) def test_loader_cvs_pserver_with_file_additions_and_deletions( swh_storage, datadir, tmp_path ): """Eventful CVS pserver conversion with file additions and deletions""" archive_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/greek-tree" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT.id, ) stats = get_stats(loader.storage) assert stats == { "content": 8, "directory": 13, "origin": 1, "origin_visit": 1, "release": 0, "revision": 7, "skipped_content": 0, "snapshot": 1, } check_snapshot(GREEK_SNAPSHOT, loader.storage) GREEK_SNAPSHOT2 = Snapshot( id=hash_to_bytes("e3d2e8860286000f546c01aa2a3e1630170eb3b6"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("f1ff9a3c7624b1be5e5d51f9ec0abf7dcddbf0b2"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_2_visits_with_change(swh_storage, datadir, tmp_path): """Eventful visit followed by eventful visit should yield two snapshots""" archive_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} visit_status1 = assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT.id, ) stats = get_stats(loader.storage) assert stats == { "content": 8, "directory": 13, "origin": 1, "origin_visit": 1, "release": 0, "revision": 7, "skipped_content": 0, "snapshot": 1, } archive_name2 = "greek-repository2" archive_path2 = os.path.join(datadir, f"{archive_name2}.tgz") repo_url = prepare_repository_from_archive(archive_path2, archive_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} visit_status2 = assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT2.id, ) stats = get_stats(loader.storage) assert stats == { "content": 10, "directory": 15, "origin": 1, "origin_visit": 2, "release": 0, "revision": 8, "skipped_content": 0, "snapshot": 2, } check_snapshot(GREEK_SNAPSHOT2, loader.storage) assert visit_status1.date < visit_status2.date assert visit_status1.snapshot != visit_status2.snapshot def test_loader_cvs_visit_pserver(swh_storage, datadir, tmp_path): """Eventful visit to CVS pserver should yield 1 snapshot""" archive_name = "runbaby" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/runbaby" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=RUNBABY_SNAPSHOT.id, ) stats = get_stats(loader.storage) assert stats == { "content": 5, "directory": 1, "origin": 1, "origin_visit": 1, "release": 0, "revision": 1, "skipped_content": 0, "snapshot": 1, } check_snapshot(RUNBABY_SNAPSHOT, loader.storage) GREEK_SNAPSHOT3 = Snapshot( id=hash_to_bytes("6e9910ed072662cb482d9017cbf5e1973e6dc09f"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("d9f4837dc55a87d83730c6e277c88b67dae80272"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_visit_pserver_no_eol(swh_storage, datadir, tmp_path): """Visit to CVS pserver with file that lacks trailing eol""" archive_name = "greek-repository3" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT3.id, ) stats = get_stats(loader.storage) assert stats == { "content": 9, "directory": 15, "origin": 1, "origin_visit": 1, "release": 0, "revision": 8, "skipped_content": 0, "snapshot": 1, } check_snapshot(GREEK_SNAPSHOT3, loader.storage) GREEK_SNAPSHOT4 = Snapshot( id=hash_to_bytes("a8593e9233601b31e012d36975f817d2c993d04b"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("51bb99655225c810ee259087fcae505899725360"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_visit_expand_id_keyword(swh_storage, datadir, tmp_path): """Visit to CVS repository with file with an RCS Id keyword""" archive_name = "greek-repository4" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT4.id, ) stats = get_stats(loader.storage) assert stats == { "content": 12, "directory": 20, "origin": 1, "origin_visit": 1, "release": 0, "revision": 11, "skipped_content": 0, "snapshot": 1, } check_snapshot(GREEK_SNAPSHOT4, loader.storage) def test_loader_cvs_visit_pserver_expand_id_keyword(swh_storage, datadir, tmp_path): """Visit to CVS pserver with file with an RCS Id keyword""" archive_name = "greek-repository4" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT4.id, ) stats = get_stats(loader.storage) assert stats == { "content": 12, "directory": 20, "origin": 1, "origin_visit": 1, "release": 0, "revision": 11, "skipped_content": 0, "snapshot": 1, } check_snapshot(GREEK_SNAPSHOT4, loader.storage) GREEK_SNAPSHOT5 = Snapshot( id=hash_to_bytes("6484ec9bfff677731cbb6d2bd5058dabfae952ed"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("514b3bef07d56e393588ceda18cc1dfa2dc4e04a"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_with_file_deleted_and_readded(swh_storage, datadir, tmp_path): """Eventful conversion of history with file deletion and re-addition""" archive_name = "greek-repository5" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT5.id, ) stats = get_stats(loader.storage) assert stats == { "content": 9, "directory": 14, "origin": 1, "origin_visit": 1, "release": 0, "revision": 8, "skipped_content": 0, "snapshot": 1, } check_snapshot(GREEK_SNAPSHOT5, loader.storage) def test_loader_cvs_pserver_with_file_deleted_and_readded( swh_storage, datadir, tmp_path ): """Eventful pserver conversion with file deletion and re-addition""" archive_name = "greek-repository5" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT5.id, ) stats = get_stats(loader.storage) assert stats == { "content": 9, "directory": 14, "origin": 1, "origin_visit": 1, "release": 0, "revision": 8, "skipped_content": 0, "snapshot": 1, } check_snapshot(GREEK_SNAPSHOT5, loader.storage) DINO_SNAPSHOT = Snapshot( id=hash_to_bytes("6cf774cec1030ff3e9a301681303adb537855d09"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("b7d3ea1fa878d51323b5200ad2c6ee9d5b656f10"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_readded_file_in_attic(swh_storage, datadir, tmp_path): """Conversion of history with RCS files in the Attic""" # This repository has some file revisions marked "dead" in the Attic only. # This is different to the re-added file tests above, where the RCS file # was moved out of the Attic again as soon as the corresponding deleted # file was re-added. Failure to detect the "dead" file revisions in the # Attic would result in errors in our converted history. archive_name = "dino-readded-file" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/src" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=DINO_SNAPSHOT.id, ) stats = get_stats(loader.storage) assert stats == { "content": 38, "directory": 70, "origin": 1, "origin_visit": 1, "release": 0, "revision": 35, "skipped_content": 0, "snapshot": 1, } check_snapshot(DINO_SNAPSHOT, loader.storage) def test_loader_cvs_pserver_readded_file_in_attic(swh_storage, datadir, tmp_path): """Conversion over pserver with RCS files in the Attic""" # This repository has some file revisions marked "dead" in the Attic only. # This is different to the re-added file tests above, where the RCS file # was moved out of the Attic again as soon as the corresponding deleted # file was re-added. Failure to detect the "dead" file revisions in the # Attic would result in errors in our converted history. # This has special implications for the pserver case, because the "dead" # revisions will not appear in in the output of 'cvs rlog' by default. archive_name = "dino-readded-file" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/src" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=DINO_SNAPSHOT.id, ) stats = get_stats(loader.storage) assert stats == { "content": 38, "directory": 70, "origin": 1, "origin_visit": 1, "release": 0, "revision": 35, "skipped_content": 0, "snapshot": 1, } check_snapshot(DINO_SNAPSHOT, loader.storage) DINO_SNAPSHOT2 = Snapshot( id=hash_to_bytes("afdeca6b8ec8f58367b4e014e2210233f1c5bf3d"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("84e428103d42b84713c77afb9420d667062f8676"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_split_commits_by_commitid(swh_storage, datadir, tmp_path): """Conversion of RCS history which needs to be split by commit ID""" # This repository has some file revisions which use the same log message # and can only be told apart by commit IDs. Without commit IDs, these commits # would get merged into a single commit in our conversion result. archive_name = "dino-commitid" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/dino" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=DINO_SNAPSHOT2.id, ) check_snapshot(DINO_SNAPSHOT2, loader.storage) stats = get_stats(loader.storage) assert stats == { "content": 18, "directory": 18, "origin": 1, "origin_visit": 1, "release": 0, "revision": 18, "skipped_content": 0, "snapshot": 1, } def test_loader_cvs_pserver_split_commits_by_commitid(swh_storage, datadir, tmp_path): """Conversion via pserver which needs to be split by commit ID""" # This repository has some file revisions which use the same log message # and can only be told apart by commit IDs. Without commit IDs, these commits # would get merged into a single commit in our conversion result. archive_name = "dino-commitid" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/dino" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=DINO_SNAPSHOT2.id, ) check_snapshot(DINO_SNAPSHOT2, loader.storage) stats = get_stats(loader.storage) assert stats == { "content": 18, "directory": 18, "origin": 1, "origin_visit": 1, "release": 0, "revision": 18, "skipped_content": 0, "snapshot": 1, } GREEK_SNAPSHOT6 = Snapshot( id=hash_to_bytes("859ae7ca5b31fee594c98abecdd41eff17cae079"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("fa48fb4551898cd8d3305cace971b3b95639e83e"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_empty_lines_in_log_message(swh_storage, datadir, tmp_path): """Conversion of RCS history with empty lines in a log message""" archive_name = "greek-repository6" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT6.id, ) check_snapshot(GREEK_SNAPSHOT6, loader.storage) stats = get_stats(loader.storage) assert stats == { "content": 9, "directory": 14, "origin": 1, "origin_visit": 1, "release": 0, "revision": 8, "skipped_content": 0, "snapshot": 1, } def test_loader_cvs_pserver_empty_lines_in_log_message(swh_storage, datadir, tmp_path): """Conversion via pserver with empty lines in a log message""" archive_name = "greek-repository6" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT6.id, ) check_snapshot(GREEK_SNAPSHOT6, loader.storage) stats = get_stats(loader.storage) assert stats == { "content": 9, "directory": 14, "origin": 1, "origin_visit": 1, "release": 0, "revision": 8, "skipped_content": 0, "snapshot": 1, } def get_head_revision_paths_info(loader: CvsLoader) -> Dict[bytes, Dict[str, Any]]: assert loader.snapshot is not None root_dir = loader.snapshot.branches[b"HEAD"].target revision = loader.storage.revision_get([root_dir])[0] assert revision is not None paths = {} for entry in loader.storage.directory_ls(revision.directory, recursive=True): paths[entry["name"]] = entry return paths def test_loader_cvs_with_header_keyword(swh_storage, datadir, tmp_path): """Eventful conversion of history with Header keyword in a file""" archive_name = "greek-repository7" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} repo_url = f"fake://{repo_url[7:]}" loader2 = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader2.load() == {"status": "eventful"} # We cannot verify the snapshot ID. It is unpredicable due to use of the $Header$ # RCS keyword which contains the temporary directory where the repository is stored. expected_stats = { "content": 9, "directory": 14, "origin": 2, "origin_visit": 2, "release": 0, "revision": 8, "skipped_content": 0, "snapshot": 1, } stats = get_stats(loader.storage) assert stats == expected_stats stats = get_stats(loader2.storage) assert stats == expected_stats # Ensure that file 'alpha', which contains a $Header$ keyword, # was imported with equal content via file:// and fake:// URLs. paths = get_head_revision_paths_info(loader) paths2 = get_head_revision_paths_info(loader2) alpha = paths[b"alpha"] alpha2 = paths2[b"alpha"] assert alpha["sha1"] == alpha2["sha1"] GREEK_SNAPSHOT8 = Snapshot( id=hash_to_bytes("5278a1f73ed0f804c68f72614a5f78ca5074ab9c"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("b389258fec8151d719e79da80b5e5355a48ec8bc"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_expand_log_keyword(swh_storage, datadir, tmp_path): """Conversion of RCS history with Log keyword in files""" archive_name = "greek-repository8" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT8.id, ) check_snapshot(GREEK_SNAPSHOT8, loader.storage) stats = get_stats(loader.storage) assert stats == { "content": 14, "directory": 20, "origin": 1, "origin_visit": 1, "release": 0, "revision": 11, "skipped_content": 0, "snapshot": 1, } def test_loader_cvs_pserver_expand_log_keyword(swh_storage, datadir, tmp_path): """Conversion of RCS history with Log keyword in files""" archive_name = "greek-repository8" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT8.id, ) check_snapshot(GREEK_SNAPSHOT8, loader.storage) stats = get_stats(loader.storage) assert stats == { "content": 14, "directory": 20, "origin": 1, "origin_visit": 1, "release": 0, "revision": 11, "skipped_content": 0, "snapshot": 1, } GREEK_SNAPSHOT9 = Snapshot( id=hash_to_bytes("3d08834666df7a589abea07ac409771ebe7e8fe4"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("9971cbb3b540dfe75f3bcce5021cb73d63b47df3"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_visit_expand_custom_keyword(swh_storage, datadir, tmp_path): """Visit to CVS repository with file with a custom RCS keyword""" archive_name = "greek-repository9" extracted_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, extracted_name, tmp_path) repo_url += "/greek-tree" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, extracted_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=GREEK_SNAPSHOT9.id, ) stats = get_stats(loader.storage) assert stats == { "content": 9, "directory": 14, "origin": 1, "origin_visit": 1, "release": 0, "revision": 8, "skipped_content": 0, "snapshot": 1, } check_snapshot(GREEK_SNAPSHOT9, loader.storage) RCSBASE_SNAPSHOT = Snapshot( id=hash_to_bytes("2c75041ba8868df04349c1c8f4c29f992967b8aa"), branches={ b"HEAD": SnapshotBranch( target=hash_to_bytes("46f076387ff170dc3d4da5e43d953c1fc744c821"), target_type=TargetType.REVISION, ) }, ) def test_loader_cvs_expand_log_keyword2(swh_storage, datadir, tmp_path): """Another conversion of RCS history with Log keyword in files""" archive_name = "rcsbase-log-kw-test-repo" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/src" # CVS module name loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=RCSBASE_SNAPSHOT.id, ) check_snapshot(RCSBASE_SNAPSHOT, loader.storage) stats = get_stats(loader.storage) assert stats == { "content": 2, "directory": 3, "origin": 1, "origin_visit": 1, "release": 0, "revision": 3, "skipped_content": 0, "snapshot": 1, } def test_loader_cvs_pserver_expand_log_keyword2(swh_storage, datadir, tmp_path): """Another conversion of RCS history with Log keyword in files""" archive_name = "rcsbase-log-kw-test-repo" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/src" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) ) assert loader.load() == {"status": "eventful"} assert_last_visit_matches( loader.storage, repo_url, status="full", type="cvs", snapshot=RCSBASE_SNAPSHOT.id, ) check_snapshot(RCSBASE_SNAPSHOT, loader.storage) stats = get_stats(loader.storage) assert stats == { "content": 2, "directory": 3, "origin": 1, "origin_visit": 1, "release": 0, "revision": 3, "skipped_content": 0, "snapshot": 1, } @pytest.mark.parametrize( "rlog_unsafe_path", [ # paths that walk to parent directory: "unsafe_rlog_with_unsafe_relative_path.rlog", # absolute path outside the CVS server's root directory: "unsafe_rlog_wrong_arborescence.rlog", ], ) def test_loader_cvs_weird_paths_in_rlog( swh_storage, datadir, tmp_path, mocker, rlog_unsafe_path ): """Handle cvs rlog output which contains unsafe paths""" archive_name = "greek-repository" archive_path = os.path.join(datadir, f"{archive_name}.tgz") repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) repo_url += "/greek-tree" # CVS module name # Ask our cvsclient to connect via the 'cvs server' command repo_url = f"fake://{repo_url[7:]}" # And let's pretend the server returned this rlog output instead of # what it would actually return. rlog_file = tempfile.NamedTemporaryFile( dir=tmp_path, mode="w+", delete=False, prefix="weird-path-rlog-" ) rlog_file_path = rlog_file.name rlog_weird_paths = open(os.path.join(datadir, rlog_unsafe_path)) for line in rlog_weird_paths.readlines(): rlog_file.write(line.replace("{cvsroot_path}", os.path.dirname(repo_url[7:]))) rlog_file.close() rlog_file_override = open(rlog_file_path, "rb") # re-open as bytes instead of str mock_read = mocker.patch("swh.loader.cvs.cvsclient.CVSClient.fetch_rlog") mock_read.return_value = rlog_file_override def side_effect(self, path="", state=""): return None mock_read.side_effect = side_effect(side_effect) try: loader = CvsLoader( swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name), ) except BadPathException: pass assert loader.load() == {"status": "failed"} assert_last_visit_matches( swh_storage, repo_url, status="failed", type="cvs", ) assert mock_read.called rlog_file_override.close() os.unlink(rlog_file_path) def test_loader_rsync_retry(swh_storage, mocker, tmp_path): module_name = "module" host = "example.org" path = f"/cvsroot/{module_name}" repo_url = f"rsync://{host}{path}/" rsync_first_call = ["rsync", repo_url] rsync_second_call = [ "rsync", "-az", f"{repo_url}CVSROOT/", os.path.join(tmp_path, "CVSROOT/"), ] rsync_third_call = [ "rsync", "-az", f"{repo_url}{module_name}/", os.path.join(tmp_path, f"{module_name}/"), ] mock_subprocess = mocker.patch("swh.loader.cvs.loader.subprocess") mock_subprocess.run.side_effect = [ subprocess.CompletedProcess(args=rsync_first_call, returncode=23), subprocess.CompletedProcess( args=rsync_first_call, returncode=0, stdout=f""" drwxr-xr-x 21 2012/11/04 06:58:58 . drwxr-xr-x 39 2021/01/22 10:21:05 CVSROOT drwxr-xr-x 15 2020/12/28 00:50:21 {module_name}""", ), subprocess.CompletedProcess( args=rsync_second_call, returncode=23, ), subprocess.CompletedProcess( args=rsync_second_call, returncode=23, ), subprocess.CompletedProcess(args=rsync_second_call, returncode=0), subprocess.CompletedProcess( args=rsync_third_call, returncode=23, ), subprocess.CompletedProcess( args=rsync_third_call, returncode=23, ), subprocess.CompletedProcess(args=rsync_third_call, returncode=0), ] loader = CvsLoader(swh_storage, repo_url) loader.cvs_module_name = module_name loader.cvsroot_path = tmp_path loader.fetch_cvs_repo_with_rsync(host, path) @pytest.mark.parametrize( "pserver_url", [ "pserver://anonymous:anonymous@cvs.example.org/cvsroot/project/module", "pserver://anonymous@cvs.example.org/cvsroot/project/module", ], ) def test_cvs_client_connect_pserver(mocker, pserver_url): from swh.loader.cvs.cvsclient import socket conn = mocker.MagicMock() conn.recv.side_effect = [b"I LOVE YOU\n", b"Valid-requests \n", b"ok\n"] mocker.patch.object(socket, "create_connection").return_value = conn parsed_url = urlparse(pserver_url) # check cvs client can be instantiated without errors CVSClient(parsed_url) + + +@pytest.mark.parametrize("protocol", ["rsync", "pserver"]) +def test_loader_cvs_with_non_utf8_directory_paths( + swh_storage, datadir, tmp_path, protocol +): + archive_name = "greek-repository" + archive_path = os.path.join(datadir, f"{archive_name}.tgz") + repo_url = prepare_repository_from_archive(archive_path, archive_name, tmp_path) + repo_url += "/greek-tree" # CVS module name + + protocol_prefix = "file://" + if protocol == "pserver": + protocol_prefix = "fake://" + repo_url = repo_url.replace("file://", protocol_prefix) + + for root, _, files in os.walk(repo_url.replace(protocol_prefix, "")): + for file in files: + # clone existing file in repository but makes it path non UTF-8 encoded + filepath = os.path.join(root, file) + with open(filepath, "rb") as f: + filecontent = f.read() + filepath = root.encode() + ("é" + file).encode("iso-8859-1") + with open(filepath, "wb") as f: + f.write(filecontent) + + loader = CvsLoader( + swh_storage, repo_url, cvsroot_path=os.path.join(tmp_path, archive_name) + ) + + assert loader.load() == {"status": "eventful"}