02 / FILES, ACCOUNTS AND SERVICES · LESSON 06

Copy and verify a configuration backup

Copy virtual configuration files and verify their saved bytes before reporting success.

18 min · learn at your pace

A successful copy is only the start

A backup should preserve bytes, including line endings and non-text data. Build a manifest from the source files, copy them, then read the destination files and verify their lengths and SHA-256 digests. Hashing the source twice would not verify the copy.

Use relative paths in the manifest and retain nested directories. Two files with the same name in different directories remain separate entries. The manifest itself is generated metadata, so reserve the destination's root manifest.json name rather than overwriting a source file with that name.

Choose a new destination

This function requires a destination that does not already exist and is outside the source tree. Copying a tree into itself can cause recursive growth; merging into an old backup can leave stale files that were absent from the new source. Choose another destination name for a later backup.

Write the manifest only after verification succeeds. If verification fails, raise ValueError and leave the unverified copy available for inspection without a success manifest. Never alter the original source files to make the check pass.

The exercise works entirely inside the browser's virtual filesystem. It teaches copy verification, not an enterprise backup strategy: scheduling, separate storage, recovery objectives and restore drills need additional operational planning. The checks include binary bytes and a deliberately corrupted copy so verification is more than a printed success message.

Try an example.py
from pathlib import Path
from hashlib import sha256
data = Path("configs/app.ini").read_bytes()
print(len(data), sha256(data).hexdigest())
YOUR TURN

Put it into practice.

Define backup_configs(source, destination). Source must be an existing directory (FileNotFoundError). Destination must be outside source (ValueError) and not exist (FileExistsError). Reserve root manifest.json: reject a source containing it. Copy all nested files byte-for-byte, then verify destination size and SHA-256 against a source manifest. On mismatch raise ValueError without writing a success manifest. Return and save manifest.json as a path-sorted list of relative POSIX path,size,sha256 rows. Preserve source files. No symlinks are supplied; choose a new destination for each backup.

See an explained solution
One way to solve it.py
import json, shutil
from pathlib import Path
from hashlib import sha256

def backup_configs(source, destination):
    source, destination = Path(source), Path(destination)
    if not source.is_dir():
        raise FileNotFoundError(source)
    if destination.resolve().is_relative_to(source.resolve()):
        raise ValueError("Backup must be outside the source")
    if destination.exists():
        raise FileExistsError(destination)
    if (source / "manifest.json").exists():
        raise ValueError("manifest.json is reserved for the backup manifest")
    expected = []
    for path in sorted(source.rglob("*"), key=lambda item: item.relative_to(source).as_posix()):
        if path.is_file():
            data = path.read_bytes()
            expected.append({"path":path.relative_to(source).as_posix(), "size":len(data), "sha256":sha256(data).hexdigest()})
    shutil.copytree(source, destination)
    for row in expected:
        data = (destination / row["path"]).read_bytes()
        if len(data) != row["size"] or sha256(data).hexdigest() != row["sha256"]:
            raise ValueError("Backup verification failed")
    (destination / "manifest.json").write_text(json.dumps(expected, ensure_ascii=False, indent=2)+"\n", encoding="utf-8")
    return expected

if __name__ == "__main__":
    print(backup_configs("configs", "backup-01"))

The manifest describes original bytes, while verification reads the saved copy. A corrupt destination cannot gain a success manifest, and source files stay untouched.