#!/usr/bin/env python3 """Put back what the RetroTechCollection archive cannot hold. python3 restore-after-download.py put it all back python3 restore-after-download.py --check only report Run it in the top folder of the PsionLX release, once, after downloading the release from the archive. The archive keeps every file's contents, but not symbolic links, folders with nothing in them, or permissions, and it leaves out every name that starts with a dot and every CVS and .git folder. The build needs them. They are in restore-after-download.tar.gz, beside this script, and listed in restore-after-download.txt. It never overwrites or deletes anything: what is already in place is left alone, and anything that differs from the release is reported. On a copy that already has everything it changes nothing. It then checks that every file the archive keeps is present at its full size. Python 3.6 or later, nothing else; macOS or Linux. """ import collections, hashlib, os, re, shutil, stat, sys, tarfile BUNDLE = 'restore-after-download.tar.gz' LISTING = 'restore-after-download.txt' MANIFEST = 'restore-after-download.manifest' LATER = (BUNDLE, LISTING, 'SHA256SUMS.txt', '1-IMAGES/SHA256SUMS.txt') # written after the manifest VCS = {'.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg'} def die(msg): sys.exit(f'restore-after-download: {msg}') def hidden(path): return any(n.startswith('.') or n in VCS or n == 'error_log' for n in path.split('/')) def bad_name(name): parts = name.split('/') return name.startswith('/') or any(p in ('', '.', '..') for p in parts) def link_on_the_way(path): parts = path.split('/') return any(os.path.islink('/'.join(parts[:i])) for i in range(1, len(parts))) def mode_of(path): return stat.S_IMODE(os.lstat(path).st_mode) def main(): args = sys.argv[1:] if args not in ([], ['--check']): die('usage: python3 restore-after-download.py [--check]') check = bool(args) if os.name != 'posix': die('this needs macOS or Linux') os.chdir(os.path.dirname(os.path.abspath(__file__))) for f in (BUNDLE, LISTING): if not os.path.isfile(f): die(f'{f} is missing: download it from the archive too') with open(LISTING, encoding='utf-8', errors='replace') as f: want = re.search(r'^' + re.escape(BUNDLE) + r'\s+SHA-256\s+([0-9a-f]{64})\s*$', f.read(), re.M) if not want: die(f'{LISTING} does not give the SHA-256 of {BUNDLE}') h = hashlib.sha256() with open(BUNDLE, 'rb') as f: for chunk in iter(lambda: f.read(1 << 20), b''): h.update(chunk) if h.hexdigest() != want.group(1): die(f'{BUNDLE} is damaged or incomplete: download it again') print('PsionLX: ' + ('checking for' if check else 'putting back') + ' what the archive does not keep') print(f' {BUNDLE}: SHA-256 matches') put = collections.Counter() # put back (or, with --check, missing) already = 0 # in place before we started differs = [] # something else is there; left alone dirmodes = [] # applied last, deepest first made = set() # folders made here perms = 0 # permissions corrected manifest = None with tarfile.open(BUNDLE, 'r|gz') as tar: for ti in tar: name = ti.name if name == MANIFEST: manifest = tar.extractfile(ti).read().decode('utf-8', 'surrogateescape').split('\n') continue if bad_name(name): die(f'{BUNDLE} holds a name it must not: {name!r}') what = 'hidden' if hidden(name) else 'link' if ti.issym() else 'folder' if ti.isdir() else 'other' if link_on_the_way(name): differs.append(f'{name}: a link stands where a folder should be') continue if os.path.lexists(name): st = os.lstat(name) same = (ti.isdir() and stat.S_ISDIR(st.st_mode) or ti.issym() and stat.S_ISLNK(st.st_mode) and os.readlink(name) == ti.linkname or ti.isfile() and stat.S_ISREG(st.st_mode) and st.st_size == ti.size) if not same: differs.append(f'{name}: not what the release has') continue already += 1 if ti.isdir(): dirmodes.append((name, ti.mode)) elif ti.isfile() and stat.S_IMODE(st.st_mode) != ti.mode: perms += 1 if not check: os.chmod(name, ti.mode) continue put[what] += 1 if check: continue parent = os.path.dirname(name) if parent and not os.path.isdir(parent): os.makedirs(parent) if ti.isdir(): os.mkdir(name, 0o700) made.add(name) dirmodes.append((name, ti.mode)) elif ti.issym(): os.symlink(ti.linkname, name) elif ti.islnk(): os.link(ti.linkname, name) elif ti.isfile(): fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600) with os.fdopen(fd, 'wb') as out: shutil.copyfileobj(tar.extractfile(ti), out) os.chmod(name, ti.mode) os.utime(name, (ti.mtime, ti.mtime)) else: put[what] -= 1 differs.append(f'{name}: a kind of entry this cannot make') if not manifest or manifest[0] != 'PSIONLX-RESTORE 1': die(f'{BUNDLE} has no manifest this understands') files = 0 absent, short = [], [] for line in manifest[1:]: if line.startswith('f\t'): _, mode, size, name = line.split('\t', 3) files += 1 try: st = os.lstat(name) except FileNotFoundError: absent.append(name) continue if not stat.S_ISREG(st.st_mode): differs.append(f'{name}: not a file') continue if st.st_size != int(size): short.append(name) if stat.S_IMODE(st.st_mode) != int(mode, 8): perms += 1 if not check: os.chmod(name, int(mode, 8)) elif line.startswith('d\t'): _, mode, name = line.split('\t', 2) if os.path.isdir(name) and not os.path.islink(name): dirmodes.append((name, int(mode, 8))) for name in LATER: if os.path.isfile(name) and not os.path.islink(name) and mode_of(name) != 0o644: perms += 1 if not check: os.chmod(name, 0o644) for name, mode in sorted(dirmodes, key=lambda x: -x[0].count('/')): if mode_of(name) != mode: if name not in made: perms += 1 if not check: os.chmod(name, mode) verb = 'missing' if check else 'put back' print(f' links: {put["link"]:,} {verb}') print(f' folders: {put["folder"]:,} {verb}') print(f' hidden files and folders: {put["hidden"]:,} {verb}') print(f' permissions: {perms:,} ' + ('wrong' if check else 'corrected')) if already: print(f' {already:,} were in place already') if absent: print(f' files: {len(absent):,} of the {files:,} the archive keeps are missing:') for top, n in collections.Counter(a.split('/')[0] for a in absent).most_common(): print(f' {top}: {n:,}') print(' download them again (if you took only part of the release, that part is fine)') if short: print(f' files: {len(short):,} are not at full size -- download them again:') for name in short[:10]: print(f' {name}') if differs: print(f' {len(differs):,} left alone because something else is there:') for d in differs[:10]: print(f' {d}') if len(differs) > 10 or len(short) > 10: print(' ...') if not absent and not short: print(f' files: all {files:,} the archive keeps are present at full size') todo = sum(put.values()) + perms if check else 0 if absent or short or differs or todo: if check and todo: print('Run it without --check to put them back.') sys.exit(1) print('This copy matches the release.' if check or not (sum(put.values()) + perms) else 'Done: this copy now matches the release.') if __name__ == '__main__': main()