ctxc 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ctxc/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Compile explicitly selected filesystem content into deterministic context blocks."""
ctxc/cli.py ADDED
@@ -0,0 +1,120 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import tomllib
5
+ import unicodedata
6
+ from pathlib import Path
7
+
8
+
9
+ def load_named_config(path: Path, name: str) -> dict:
10
+ """Load one named configuration. Input/output paths remain CWD-relative."""
11
+ with path.open("rb") as file:
12
+ return tomllib.load(file)["configs"][name]
13
+
14
+
15
+ def _has_symlink(path: Path) -> bool:
16
+ return any(part.is_symlink() for part in (path, *path.parents))
17
+
18
+
19
+ def files_under(directory: Path, suffixes: set[str]) -> list[Path]:
20
+ """Recursively select files, skipping symlinked paths."""
21
+ if _has_symlink(directory):
22
+ return []
23
+ if not directory.is_dir():
24
+ raise NotADirectoryError(f"Not a directory: {directory}")
25
+
26
+ files: list[Path] = []
27
+ for path in directory.iterdir():
28
+ if _has_symlink(path):
29
+ continue
30
+ if path.is_dir():
31
+ files.extend(files_under(path, suffixes))
32
+ elif path.is_file() and path.suffix.lower() in suffixes:
33
+ files.append(path)
34
+ return files # One canonical sort happens after all selections are combined.
35
+
36
+
37
+ def normalize_suffixes(extensions: list[str]) -> set[str]:
38
+ """Normalize extensions to lowercase suffixes with leading dots."""
39
+ return {
40
+ (extension if extension.startswith(".") else f".{extension}").lower()
41
+ for extension in extensions
42
+ }
43
+
44
+
45
+ def _serialize_block(block_id: str, data: bytes) -> bytes:
46
+ if (
47
+ not block_id
48
+ or block_id != block_id.strip()
49
+ or len(block_id.splitlines()) != 1
50
+ or any(unicodedata.category(char) == "Cc" for char in block_id)
51
+ ):
52
+ raise ValueError(f"Invalid block identifier: {block_id!r}")
53
+ identifier = block_id.encode("utf-8", errors="strict")
54
+ data.decode("utf-8", errors="strict")
55
+ closing = b"@@ctx.end " + identifier
56
+ if closing in data.split(b"\n"):
57
+ raise ValueError(f"Closing delimiter collision in {block_id!r}")
58
+ # The extra LF before closing is framing, not part of the payload.
59
+ return b"@@ctx " + identifier + b"\n" + data + b"\n" + closing + b"\n"
60
+
61
+
62
+ def build_code_bundle(config: dict) -> None:
63
+ """Compile configured files into out_code. The current directory is the root.
64
+
65
+ Overlapping selections of the same canonical file are included once.
66
+ All inputs are read and validated before opening the output for writing.
67
+ Output replacement is not atomic in this initial release.
68
+ """
69
+ out_code = Path(config["out_code"])
70
+ if not config.get("extensions"):
71
+ raise ValueError("Config 'extensions' must contain at least one extension.")
72
+ suffixes = normalize_suffixes(config["extensions"])
73
+ root = Path.cwd().resolve()
74
+ out_resolved = out_code.resolve()
75
+ if _has_symlink(out_code):
76
+ raise ValueError("Output must not be a symlink or use a symlinked parent.")
77
+
78
+ files: list[Path] = []
79
+ for directory in config.get("dirs", []):
80
+ files.extend(files_under(Path(directory), suffixes))
81
+ for file in config.get("files", []):
82
+ path = Path(file)
83
+ if _has_symlink(path):
84
+ continue
85
+ if not path.is_file():
86
+ raise FileNotFoundError(f"Not a file: {path}")
87
+ files.append(path)
88
+
89
+ by_id: dict[str, Path] = {}
90
+ for file in files:
91
+ canonical = file.resolve(strict=True)
92
+ if canonical == out_resolved:
93
+ continue
94
+ if not canonical.is_relative_to(root):
95
+ raise ValueError(f"Input is outside the current-directory root: {file}")
96
+ # Different spellings of the same path cannot emit duplicate block IDs.
97
+ by_id[canonical.relative_to(root).as_posix()] = canonical
98
+
99
+ artifact = b"".join(
100
+ _serialize_block(block_id, by_id[block_id].read_bytes())
101
+ for block_id in sorted(by_id, key=lambda value: value.encode("utf-8"))
102
+ )
103
+ out_code.parent.mkdir(parents=True, exist_ok=True)
104
+ out_code.write_bytes(artifact)
105
+ print(f"Generated {out_code} from {len(by_id)} file(s)")
106
+
107
+
108
+ def main() -> None:
109
+ parser = argparse.ArgumentParser(description=__doc__)
110
+ parser.add_argument("--config", type=Path, required=True)
111
+ parser.add_argument("--name", required=True)
112
+ args = parser.parse_args()
113
+ try:
114
+ build_code_bundle(load_named_config(args.config, args.name))
115
+ except (OSError, ValueError, KeyError) as error:
116
+ parser.exit(1, f"ctxc: {error}\n")
117
+
118
+
119
+ if __name__ == "__main__":
120
+ main()
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.5
2
+ Name: ctxc
3
+ Version: 0.0.1
4
+ Summary: A minimal filesystem-to-context compiler.
5
+ Project-URL: Repository, https://github.com/jeremylimqe/ctxc
6
+ Project-URL: Issues, https://github.com/jeremylimqe/ctxc/issues
7
+ Author: jeremylimqe
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Requires-Python: >=3.14
15
+ Description-Content-Type: text/markdown
16
+
17
+ # ctxc
18
+
19
+ A small deterministic compiler that turns explicitly selected UTF-8 files into a reproducible Context Blocks artifact.
20
+
21
+ Requires Python 3.14+.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install ctxc
27
+ ```
@@ -0,0 +1,7 @@
1
+ ctxc/__init__.py,sha256=pft6orZd9G2rQx31FZkgsAsqDbYyblyz_AaN3TArMNo,87
2
+ ctxc/cli.py,sha256=kv0NPIgC3gw7VwHp0ry9qc7hjEWecAMml4jM9u9fKj8,4404
3
+ ctxc-0.0.1.dist-info/METADATA,sha256=psdlnYVvb5HdT0f9Fk1drsaxOv8Fyb421fh_se0XUX0,746
4
+ ctxc-0.0.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
5
+ ctxc-0.0.1.dist-info/entry_points.txt,sha256=jFC7M7U4Z6xLdZLI1aBxVuIkxAY1eilmh1vm1VqCRi0,39
6
+ ctxc-0.0.1.dist-info/licenses/LICENSE,sha256=FzRVWpxKLlgFv_jhXdvbJZ_G4-EiP1eIJsg7BmRxbtM,1068
7
+ ctxc-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ctxc = ctxc.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jeremylimqe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.