#!/usr/bin/env python3 """Archive macOS extended attributes beside a NAS backup, without applying them. Attribute values may contain private user information. Output stays on the NAS. """ import base64 import collections import json import os from pathlib import Path import sys def main(): config = json.loads(Path(sys.argv[1]).read_text()) uid, gid = config.get('uid', 1000), config.get('gid', 1001) source = Path(config['mount']) / config['source_root'] destination = Path(sys.argv[2]) destination.mkdir(mode=0o700) os.chown(destination, uid, gid) count = collections.Counter() entries = 0 output = destination / 'extended-attributes.jsonl' fd = os.open(output, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) with os.fdopen(fd, 'w') as stream: for name in config['directories']: folder = source / name paths = [folder] for base, dirs, files in os.walk(folder, followlinks=False, onerror=lambda e: (_ for _ in ()).throw(e)): paths.extend(Path(base) / item for item in dirs + files) for path in paths: attributes = {} for key in os.listxattr(path, follow_symlinks=False): value = os.getxattr(path, key, follow_symlinks=False) attributes[key] = base64.b64encode(value).decode('ascii') count[key] += 1 if attributes: stream.write(json.dumps({'path': str(path.relative_to(source)), 'attributes_base64': attributes}, ensure_ascii=False) + '\n') entries += 1 stream.flush() os.fsync(stream.fileno()) os.chown(output, uid, gid) summary = {'entries': entries, 'attribute_names': dict(count), 'bytes': output.stat().st_size, 'resource_fork_attributes': count['com.apple.ResourceFork']} (destination / 'README.txt').write_text( '这是 APFS 源目录的 macOS 扩展属性原始存档,不包含普通文件的数据内容。\n' 'extended-attributes.jsonl 每行记录相对路径与 Base64 编码的原始属性。\n' '包含用户标签、Finder 信息和机器相关安全元数据,请随剪辑备份私下保管,不上传源码仓库。\n' '普通文件已由 rsync 复制;还原至 Mac 时应按需使用这些属性,不要盲目重放机器相关属性。\n') os.chown(destination / 'README.txt', uid, gid) print(json.dumps(summary, ensure_ascii=False)) if __name__ == '__main__': main()