Python lesson

Build a folder report that includes hidden files

Use Python to list folder contents, including hidden files. Save each file’s size and SHA-256 fingerprint in a new JSON report.

1. Create an empty product folder

You will build a folder-report app that leaves input files unchanged. The report will contain paths, byte sizes and SHA-256 fingerprints. SHA-256 computes a 64-character fingerprint from bytes; it is not encryption or proof of authorship.

You need Python 3 and a plain-text editor. Check installation with python3 --version. If unavailable, install Python 3 and reopen the terminal. Actual checks used Python 3.14.4 on macOS. No extra packages or accounts are required.

Create qovluq-izi-v1. Save the three files in the tree as UTF-8 without hidden .txt extensions. Do not save the tree itself. Do not create demo or manifest.json yet: the programs below will create them.

Text
qovluq-izi-v1/
  seed.py
  app.py
  test_app.py

2. Create your own sample files with seed.py

Copy the complete code into seed.py. It creates three invented text files in a new folder, including the dot-prefixed .note.txt. That file contains demo text, not a private user note.

Open a terminal in the product folder and run python3 seed.py demo. Expect Created 3 files followed by the folder’s absolute path. .note.txt and lesson.txt each contain 12 bytes; sub/step.txt contains 10. Reusing demo causes an error; use another folder name for a fresh sample.

Pythonseed.py
"""Create a NEW folder with three synthetic UTF-8 lesson files."""
from pathlib import Path
import sys

try:
    if len(sys.argv) != 2:
        raise ValueError("Usage: python3 seed.py NEW_FOLDER")
    root = Path(sys.argv[1])
    root.mkdir()
    (root / "sub").mkdir()
    for name, text in ((".note.txt", "demo hidden\n"),
                       ("lesson.txt", "demo lesson\n"),
                       ("sub/step.txt", "demo step\n")):
        with (root / name).open("x", encoding="utf-8", newline="\n") as stream:
            stream.write(text)
    print(f"Created 3 files -> {root.resolve()}")
except (OSError, ValueError) as error:
    print(f"Error: {error}", file=sys.stderr)
    sys.exit(1)

3. List all files with app.py

Save the complete code as app.py. build walks subfolders, reads regular files and computes fingerprints. Hidden names are not excluded, so they appear too. JSON is a text format with named fields.

After validating all input, the app creates output using x mode, which refuses to replace an existing file. Output must sit outside the input folder so the report cannot become part of its own input. The tool only reads the source files and does not upload them.

Pythonapp.py
"""Read a small folder, including dotfiles, and create a NEW JSON manifest."""
import hashlib
import json
import os
from pathlib import Path
import stat
import sys

MAX_ENTRIES = 500
MAX_FILE = 1024 * 1024
MAX_TOTAL = 10 * MAX_FILE


def build(source, output):
    source = Path(source)
    if source.is_symlink():
        raise ValueError("Input must not be a symlink")
    root = source.resolve(strict=True)
    if not root.is_dir():
        raise ValueError("Input must be a folder")
    output = Path(output)
    if output.exists() or output.is_symlink():
        raise ValueError("Output already exists")
    output = output.resolve()
    if output == root or root in output.parents:
        raise ValueError("Output must be outside the input folder")

    files = []
    entries = total = 0

    def visit(folder):
        nonlocal entries, total
        with os.scandir(folder) as children:
            for child in children:
                entries += 1
                if entries > MAX_ENTRIES:
                    raise ValueError("More than 500 entries (files + folders)")
                path = Path(child.path)
                info = child.stat(follow_symlinks=False)
                mode = info.st_mode
                if stat.S_ISDIR(mode):
                    visit(path)
                elif stat.S_ISREG(mode):
                    if info.st_size > MAX_FILE:
                        raise ValueError("File exceeds 1 MiB")
                    with path.open("rb") as stream:
                        data = stream.read(MAX_FILE + 1)
                    if len(data) > MAX_FILE:
                        raise ValueError("File exceeds 1 MiB")
                    total += len(data)
                    if total > MAX_TOTAL:
                        raise ValueError("Total exceeds 10 MiB")
                    files.append({"path": path.relative_to(root).as_posix(),
                                  "bytes": len(data),
                                  "sha256": hashlib.sha256(data).hexdigest()})
                else:
                    raise ValueError("Symlinks and nonregular files are refused")

    visit(root)
    result = {"count": len(files), "files": sorted(files, key=lambda f: f["path"])}
    payload = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
    with output.open("x", encoding="utf-8", newline="\n") as stream:
        stream.write(payload)
    return output, result["count"]


def main():
    try:
        if len(sys.argv) != 3:
            raise ValueError("Usage: python3 app.py INPUT_FOLDER NEW_MANIFEST.json")
        output, count = build(*sys.argv[1:])
        print(f"Wrote {count} files -> {output}")
    except (OSError, ValueError, RecursionError) as error:
        print(f"Error: {error}", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())

4. Check the result and an error case

Run python3 app.py demo manifest.json. Expect Wrote 3 files followed by the output path. Open manifest.json: count is 3 and paths are .note.txt, lesson.txt and sub/step.txt. Each has bytes and sha256. The .note.txt fingerprint should be e81f615312549a37d8d0c23f8e18683aab7f6944143bfe06f67448b9cbf32319.

Create an empty folder named empty in your editor. Run python3 app.py empty empty-manifest.json. Expect count 0 and an empty files list. An empty folder is valid. Do not place its output inside that folder.

Run python3 app.py demo demo/bad.json. Expect Error: Output must be outside the input folder. Correct it by choosing an outside filename such as manifest-2.json. Reusing manifest.json is also rejected and preserves the previous report.

5. Check behavior with test_app.py

Save the complete tests as test_app.py and run python3 -m unittest -v test_app.py. The finished product passed 3 test methods, including error and limit cases. Expect Ran 3 tests and OK. Tests create their own temporary files.

Actual CLI runs check hidden files, empty folders, repeatable output and preservation of existing output. Symbolic links and special files are checked too. A symbolic link points to another path; this product rejects it rather than following it.

Pythontest_app.py
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest

HERE = Path(__file__).resolve().parent


class ManifestTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.base = Path(self.temp.name)
        self.src = self.base / "demo"
        self.out = self.base / "manifest.json"

    def cli(self, script, *args):
        return subprocess.run([sys.executable, str(HERE / script), *map(str, args)],
                              capture_output=True, text=True, timeout=10)

    def manifest(self):
        return self.cli("app.py", self.src, self.out)

    def reject(self):
        result = self.manifest()
        self.assertNotEqual(result.returncode, 0)
        self.assertIn("Error:", result.stderr)
        self.assertFalse(self.out.exists())

    def test_demo(self):
        self.assertEqual(self.cli("seed.py", self.src).returncode, 0)
        self.assertEqual(self.manifest().returncode, 0)
        data = json.loads(self.out.read_text())
        self.assertEqual(data["count"], 3)
        self.assertEqual([f["path"] for f in data["files"]],
                         [".note.txt", "lesson.txt", "sub/step.txt"])
        for f in data["files"]:
            raw = (self.src / f["path"]).read_bytes()
            self.assertEqual((f["bytes"], f["sha256"]),
                             (len(raw), hashlib.sha256(raw).hexdigest()))
        old = self.out.read_bytes()
        self.assertNotEqual(self.manifest().returncode, 0)
        self.assertEqual(old, self.out.read_bytes())
        self.assertNotEqual(self.cli("seed.py", self.src).returncode, 0)
        (self.src / ".extra.txt").write_bytes(b"new\n")
        self.out = self.base / "four.json"
        self.assertEqual(self.manifest().returncode, 0)
        self.assertEqual(json.loads(self.out.read_text())["count"], 4)

    def test_empty(self):
        self.src.mkdir()
        self.assertEqual(self.manifest().returncode, 0)
        self.assertEqual(json.loads(self.out.read_text()), {"count": 0, "files": []})

    def test_limits(self):
        for case in ("symlink", "fifo", "inside", "entries", "file", "total"):
            with self.subTest(case=case):
                self.src = self.base / case
                self.src.mkdir()
                self.out = self.base / (case + ".json")
                if case == "symlink":
                    (self.src / "link").symlink_to(HERE / "app.py")
                elif case == "fifo":
                    os.mkfifo(self.src / "pipe")
                elif case == "inside":
                    self.out = self.src / "bad.json"
                elif case == "entries":
                    for i in range(501):
                        (self.src / str(i)).mkdir()
                else:
                    for i in range(11 if case == "total" else 1):
                        (self.src / str(i)).write_bytes(b"x" * (1048576 + (case == "file")))
                self.reject()


if __name__ == "__main__":
    unittest.main(verbosity=2)

6. Add another hidden file

Exercise: create the new hidden file with python3 -c "with open('demo/.extra.txt','xb') as f: f.write(b'new\n')". This writes exactly 4 bytes, using UTF-8 without BOM and a one-byte LF ending. Then run python3 app.py demo manifest-four.json. Expect count 4 and bytes 4 for .extra.txt. The original three fingerprints should remain unchanged.

Limits are 500 entries counting files and subfolders, 1 MiB per file and 10 MiB in total. Symbolic links and nonregular files are rejected. Concurrent changes do not produce a guaranteed snapshot of one instant. A disk error may leave partial new output; existing files are not replaced.

The November 28 source release concerns hidden-name matching in file permissions. Our product creates an inventory only; it does not test the SDK’s permission rules. Work with your own demo folder and do not send private documents or contact details to AI services.

Author

IT Innovations Editorial

Published:

Original source: deepagents==0.7.43

Recommended reading

All articles