my-codes01 0.1.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.
- my_codes01-0.1.1.dist-info/METADATA +92 -0
- my_codes01-0.1.1.dist-info/RECORD +11 -0
- my_codes01-0.1.1.dist-info/WHEEL +4 -0
- my_codes01-0.1.1.dist-info/entry_points.txt +3 -0
- my_codes01-0.1.1.dist-info/licenses/LICENSE +21 -0
- mycodes/__init__.py +36 -0
- mycodes/__main__.py +8 -0
- mycodes/_bundled/codes/1.py +3 -0
- mycodes/_bundled/index.json +18 -0
- mycodes/cli.py +153 -0
- mycodes/retriever.py +395 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: my-codes01
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Retrieve indexed Python code snippets from the my-codes repository.
|
|
5
|
+
Project-URL: Homepage, https://github.com/yashuus2817/my-codes
|
|
6
|
+
Project-URL: Repository, https://github.com/yashuus2817/my-codes
|
|
7
|
+
Project-URL: Issues, https://github.com/yashuus2817/my-codes/issues
|
|
8
|
+
Author: yashuus2817
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: cli,codes,python,snippets
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Topic :: Utilities
|
|
18
|
+
Requires-Python: >=3.9
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# my-codes
|
|
22
|
+
|
|
23
|
+
Indexed Python code snippets packaged for `pip install` and automated PyPI publishing via GitHub Actions.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
Install from PyPI:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install my-codes01
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Or install directly from GitHub:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install git+https://github.com/yashuus2817/my-codes.git
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Retrieving Codes in Python / Jupyter Notebook
|
|
40
|
+
|
|
41
|
+
### Live from GitHub (recommended in Jupyter / Colab)
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from mycodes import configure, get_code, list_codes
|
|
45
|
+
|
|
46
|
+
configure(username="yashuus2817", repository="my-codes")
|
|
47
|
+
list_codes()
|
|
48
|
+
code = get_code(1)
|
|
49
|
+
print(code)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
You can also point `configure(...)` at any public GitHub repo that has `index.json` and `codes/` (pass `branch="main"` if needed, or `token="..."` for private repos).
|
|
53
|
+
|
|
54
|
+
### Offline / Bundled Mode
|
|
55
|
+
|
|
56
|
+
If you skip `configure(...)`, `mycodes` reads the `index.json` and `codes/` bundled inside the installed package:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from mycodes import export_codes, get_code, list_codes
|
|
60
|
+
|
|
61
|
+
list_codes()
|
|
62
|
+
code = get_code(1)
|
|
63
|
+
print(code)
|
|
64
|
+
|
|
65
|
+
# Export all bundled files into a folder
|
|
66
|
+
export_codes("./retrieved_codes")
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## CLI Usage
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
mycodes list
|
|
73
|
+
mycodes search addition
|
|
74
|
+
mycodes get 1
|
|
75
|
+
mycodes get 1 --out my_snippet.py
|
|
76
|
+
mycodes export --dir ./retrieved_codes
|
|
77
|
+
|
|
78
|
+
# Or fetch live from a GitHub repo via CLI
|
|
79
|
+
mycodes --user yashuus2817 --repo my-codes list
|
|
80
|
+
mycodes --user yashuus2817 --repo my-codes get 1
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Connecting GitHub & PyPI (Trusted Publishing)
|
|
84
|
+
|
|
85
|
+
1. Sign in at <https://pypi.org> → **Your Account → Publishing → Add a new pending publisher**:
|
|
86
|
+
- **PyPI Project Name**: `my-codes01` (must match `name` in `pyproject.toml`)
|
|
87
|
+
- **Owner**: `yashuus2817`
|
|
88
|
+
- **Repository name**: `my-codes`
|
|
89
|
+
- **Workflow name**: `publish.yml`
|
|
90
|
+
- **Environment name**: `pypi`
|
|
91
|
+
2. In GitHub repo **Settings → Environments**, create an environment named `pypi`.
|
|
92
|
+
3. Bump `version` in `pyproject.toml` (and `src/mycodes/__init__.py`), push to `main`, and push a matching `v*` tag (e.g., `git tag v0.1.1 && git push origin v0.1.1`).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
mycodes/__init__.py,sha256=rbVtdlHPzidL3_wNA2uZ84LklI7vO9q1ytjckdzakMg,646
|
|
2
|
+
mycodes/__main__.py,sha256=sLOcnLERpOlhw5W4I91TZH1IMsOyDlKOnFb-4zegKZY,166
|
|
3
|
+
mycodes/cli.py,sha256=7DWl5yCSfLIZyoDS2aO48f39xYvyoW88uUACwN2PGS0,5285
|
|
4
|
+
mycodes/retriever.py,sha256=8Fl4DEfkHvopI3f5GtkEKuunb_lOTY4j0MKC5B6yqlA,13896
|
|
5
|
+
mycodes/_bundled/codes/1.py,sha256=0DdirPmqZ4VLEVd2TlTjRTQAjnSLpfw6QM754JF3uJI,127
|
|
6
|
+
mycodes/_bundled/index.json,sha256=CNKqmo0ueDpxLKOTzV0JR-g8HW6RAakpX89G8z1cWrM,399
|
|
7
|
+
my_codes01-0.1.1.dist-info/METADATA,sha256=siGvJPdH0nYTqdJygMdgw7sTCJSD7xtw_204h8a-K7s,2759
|
|
8
|
+
my_codes01-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
my_codes01-0.1.1.dist-info/entry_points.txt,sha256=g8VnKaNNERXyMb2gnxIp3YN1qbsGxtnyKOChLI9MgPk,73
|
|
10
|
+
my_codes01-0.1.1.dist-info/licenses/LICENSE,sha256=K2vmGR1MKrQ_KYGjP27UpVM8xelcNUWck_CDRgwGup0,1068
|
|
11
|
+
my_codes01-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 yashuus2817
|
|
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.
|
mycodes/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Retrieve indexed code snippets from bundled data or any configured GitHub repository."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from mycodes.retriever import (
|
|
6
|
+
code_exists,
|
|
7
|
+
configure,
|
|
8
|
+
export_codes,
|
|
9
|
+
get_code,
|
|
10
|
+
get_code_path,
|
|
11
|
+
get_config,
|
|
12
|
+
get_data_root,
|
|
13
|
+
get_entry,
|
|
14
|
+
list_codes,
|
|
15
|
+
load_index,
|
|
16
|
+
reset_config,
|
|
17
|
+
search_codes,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__version__ = "0.1.1"
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"__version__",
|
|
24
|
+
"code_exists",
|
|
25
|
+
"configure",
|
|
26
|
+
"export_codes",
|
|
27
|
+
"get_code",
|
|
28
|
+
"get_code_path",
|
|
29
|
+
"get_config",
|
|
30
|
+
"get_data_root",
|
|
31
|
+
"get_entry",
|
|
32
|
+
"list_codes",
|
|
33
|
+
"load_index",
|
|
34
|
+
"reset_config",
|
|
35
|
+
"search_codes",
|
|
36
|
+
]
|
mycodes/__main__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"1": {
|
|
3
|
+
"name": "Addition",
|
|
4
|
+
"description": "Addition of two numbers",
|
|
5
|
+
"category": "Basic Python",
|
|
6
|
+
"language": "python",
|
|
7
|
+
"tags": ["addition", "basics"],
|
|
8
|
+
"file": "codes/1.py"
|
|
9
|
+
},
|
|
10
|
+
"2": {
|
|
11
|
+
"name": "Even or Odd",
|
|
12
|
+
"description": "Check even or odd",
|
|
13
|
+
"category": "Basic Python",
|
|
14
|
+
"language": "python",
|
|
15
|
+
"tags": ["even", "odd"],
|
|
16
|
+
"file": "codes/2.py"
|
|
17
|
+
}
|
|
18
|
+
}
|
mycodes/cli.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Command-line interface for retrieving bundled or GitHub-hosted code snippets."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Sequence
|
|
9
|
+
|
|
10
|
+
from mycodes import __version__
|
|
11
|
+
from mycodes.retriever import (
|
|
12
|
+
configure,
|
|
13
|
+
export_codes,
|
|
14
|
+
get_code,
|
|
15
|
+
get_data_root,
|
|
16
|
+
list_codes,
|
|
17
|
+
search_codes,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _print_entries(entries: dict[str, dict]) -> None:
|
|
22
|
+
if not entries:
|
|
23
|
+
print("No matching codes found.")
|
|
24
|
+
return
|
|
25
|
+
|
|
26
|
+
for code_id, meta in entries.items():
|
|
27
|
+
status = meta.get("available")
|
|
28
|
+
status_label = "" if status is None else (" [available]" if status else " [missing file]")
|
|
29
|
+
name = meta.get("name", "")
|
|
30
|
+
category = meta.get("category", "")
|
|
31
|
+
file_rel = meta.get("file", "")
|
|
32
|
+
desc = meta.get("description", "")
|
|
33
|
+
tags = ", ".join(str(t) for t in meta.get("tags", []))
|
|
34
|
+
print(f"[{code_id}] {name} ({category}) - {file_rel}{status_label}")
|
|
35
|
+
if desc:
|
|
36
|
+
print(f" {desc}")
|
|
37
|
+
if tags:
|
|
38
|
+
print(f" tags: {tags}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
42
|
+
parser = argparse.ArgumentParser(
|
|
43
|
+
prog="mycodes",
|
|
44
|
+
description="Retrieve indexed code snippets from bundled data or GitHub.",
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
"--version",
|
|
48
|
+
action="version",
|
|
49
|
+
version=f"%(prog)s {__version__}",
|
|
50
|
+
)
|
|
51
|
+
parser.add_argument("--user", help="GitHub username to fetch snippets from.")
|
|
52
|
+
parser.add_argument("--repo", help="GitHub repository name to fetch snippets from.")
|
|
53
|
+
parser.add_argument("--branch", help="GitHub branch name (default: main).")
|
|
54
|
+
|
|
55
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
56
|
+
|
|
57
|
+
list_parser = subparsers.add_parser("list", help="List indexed code snippets.")
|
|
58
|
+
list_parser.add_argument("--category", help="Filter by category name.")
|
|
59
|
+
list_parser.add_argument("--tag", help="Filter by tag.")
|
|
60
|
+
|
|
61
|
+
search_parser = subparsers.add_parser("search", help="Search snippets by keyword.")
|
|
62
|
+
search_parser.add_argument("query", help="Search text.")
|
|
63
|
+
|
|
64
|
+
get_parser = subparsers.add_parser("get", help="Print or save a snippet by ID.")
|
|
65
|
+
get_parser.add_argument("id", help="Snippet ID from index.json.")
|
|
66
|
+
get_parser.add_argument(
|
|
67
|
+
"--out",
|
|
68
|
+
type=Path,
|
|
69
|
+
help="Optional output file path instead of printing to stdout.",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
export_parser = subparsers.add_parser(
|
|
73
|
+
"export",
|
|
74
|
+
help="Export bundled or remote codes and index.json to a directory.",
|
|
75
|
+
)
|
|
76
|
+
export_parser.add_argument(
|
|
77
|
+
"--dir",
|
|
78
|
+
dest="directory",
|
|
79
|
+
default="./retrieved_codes",
|
|
80
|
+
help="Target directory (default: ./retrieved_codes).",
|
|
81
|
+
)
|
|
82
|
+
export_parser.add_argument(
|
|
83
|
+
"--id",
|
|
84
|
+
dest="ids",
|
|
85
|
+
action="append",
|
|
86
|
+
help="Specific snippet ID to export (repeatable). Defaults to all.",
|
|
87
|
+
)
|
|
88
|
+
export_parser.add_argument(
|
|
89
|
+
"--overwrite",
|
|
90
|
+
action="store_true",
|
|
91
|
+
help="Overwrite existing files in the target directory.",
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
subparsers.add_parser("path", help="Print the local directory of bundled codes.")
|
|
95
|
+
return parser
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
99
|
+
"""Entry point for the ``mycodes`` / ``my-codes`` CLI."""
|
|
100
|
+
parser = _build_parser()
|
|
101
|
+
args = parser.parse_args(argv)
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
if args.user or args.repo:
|
|
105
|
+
if not (args.user and args.repo):
|
|
106
|
+
parser.error("Both --user and --repo must be provided together.")
|
|
107
|
+
configure(username=args.user, repository=args.repo, branch=args.branch)
|
|
108
|
+
|
|
109
|
+
if args.command == "list":
|
|
110
|
+
_print_entries(list_codes(category=args.category, tag=args.tag, quiet=True))
|
|
111
|
+
return 0
|
|
112
|
+
|
|
113
|
+
if args.command == "search":
|
|
114
|
+
_print_entries(search_codes(args.query, quiet=True))
|
|
115
|
+
return 0
|
|
116
|
+
|
|
117
|
+
if args.command == "get":
|
|
118
|
+
content = get_code(args.id)
|
|
119
|
+
if args.out is not None:
|
|
120
|
+
args.out.parent.mkdir(parents=True, exist_ok=True)
|
|
121
|
+
args.out.write_text(content, encoding="utf-8")
|
|
122
|
+
print(f"Saved snippet {args.id} to {args.out}")
|
|
123
|
+
else:
|
|
124
|
+
sys.stdout.write(content)
|
|
125
|
+
if content and not content.endswith("\n"):
|
|
126
|
+
sys.stdout.write("\n")
|
|
127
|
+
return 0
|
|
128
|
+
|
|
129
|
+
if args.command == "export":
|
|
130
|
+
result = export_codes(
|
|
131
|
+
destination=args.directory,
|
|
132
|
+
ids=args.ids,
|
|
133
|
+
overwrite=args.overwrite,
|
|
134
|
+
)
|
|
135
|
+
print(f"Exported ({len(result['exported'])}): {', '.join(result['exported']) or 'none'}")
|
|
136
|
+
if result["skipped"]:
|
|
137
|
+
print(f"Skipped existing ({len(result['skipped'])}): {', '.join(result['skipped'])}")
|
|
138
|
+
if result["missing"]:
|
|
139
|
+
print(f"Missing in repo ({len(result['missing'])}): {', '.join(result['missing'])}")
|
|
140
|
+
return 0
|
|
141
|
+
|
|
142
|
+
if args.command == "path":
|
|
143
|
+
print(get_data_root())
|
|
144
|
+
return 0
|
|
145
|
+
except (ConnectionError, FileNotFoundError, KeyError, RuntimeError, ValueError) as exc:
|
|
146
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
147
|
+
return 1
|
|
148
|
+
|
|
149
|
+
return 1
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
if __name__ == "__main__":
|
|
153
|
+
raise SystemExit(main())
|
mycodes/retriever.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""Core utilities for retrieving code snippets from bundled data or GitHub."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import shutil
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path, PurePosixPath
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
CodeId = int | str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class _GitHubConfig:
|
|
19
|
+
username: str
|
|
20
|
+
repository: str
|
|
21
|
+
branch: str = "main"
|
|
22
|
+
branch_explicit: bool = False
|
|
23
|
+
token: str | None = None
|
|
24
|
+
timeout: float = 15.0
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
_active_config: _GitHubConfig | None = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def configure(
|
|
31
|
+
username: str,
|
|
32
|
+
repository: str,
|
|
33
|
+
branch: str | None = None,
|
|
34
|
+
token: str | None = None,
|
|
35
|
+
timeout: float = 15.0,
|
|
36
|
+
) -> dict[str, Any]:
|
|
37
|
+
"""Configure a GitHub repository to retrieve ``index.json`` and code files from.
|
|
38
|
+
|
|
39
|
+
Example:
|
|
40
|
+
>>> from mycodes import configure, list_codes, get_code
|
|
41
|
+
>>> configure(username="yashuus2817", repository="my-codes")
|
|
42
|
+
>>> list_codes()
|
|
43
|
+
>>> code = get_code(1)
|
|
44
|
+
"""
|
|
45
|
+
global _active_config
|
|
46
|
+
|
|
47
|
+
clean_user = username.strip().strip("/")
|
|
48
|
+
clean_repo = repository.strip().strip("/")
|
|
49
|
+
if not clean_user or "/" in clean_user:
|
|
50
|
+
raise ValueError(f"Invalid GitHub username: {username!r}")
|
|
51
|
+
if not clean_repo or "/" in clean_repo:
|
|
52
|
+
raise ValueError(f"Invalid GitHub repository name: {repository!r}")
|
|
53
|
+
|
|
54
|
+
explicit = branch is not None
|
|
55
|
+
clean_branch = branch.strip().strip("/") if branch is not None else "main"
|
|
56
|
+
if not clean_branch:
|
|
57
|
+
raise ValueError("Branch name cannot be empty.")
|
|
58
|
+
|
|
59
|
+
_active_config = _GitHubConfig(
|
|
60
|
+
username=clean_user,
|
|
61
|
+
repository=clean_repo,
|
|
62
|
+
branch=clean_branch,
|
|
63
|
+
branch_explicit=explicit,
|
|
64
|
+
token=token,
|
|
65
|
+
timeout=timeout,
|
|
66
|
+
)
|
|
67
|
+
return get_config() or {}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def reset_config() -> None:
|
|
71
|
+
"""Clear any GitHub configuration and revert to bundled local snippets."""
|
|
72
|
+
global _active_config
|
|
73
|
+
_active_config = None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_config() -> dict[str, Any] | None:
|
|
77
|
+
"""Return the active GitHub configuration, or ``None`` if using bundled files."""
|
|
78
|
+
if _active_config is None:
|
|
79
|
+
return None
|
|
80
|
+
return {
|
|
81
|
+
"username": _active_config.username,
|
|
82
|
+
"repository": _active_config.repository,
|
|
83
|
+
"branch": _active_config.branch,
|
|
84
|
+
"timeout": _active_config.timeout,
|
|
85
|
+
"has_token": bool(_active_config.token),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def get_data_root() -> Path:
|
|
90
|
+
"""Return the local root directory containing ``index.json`` and ``codes/``."""
|
|
91
|
+
package_dir = Path(__file__).resolve().parent
|
|
92
|
+
bundled = package_dir / "_bundled"
|
|
93
|
+
if (bundled / "index.json").is_file():
|
|
94
|
+
return bundled
|
|
95
|
+
|
|
96
|
+
repo_root = package_dir.parents[1]
|
|
97
|
+
if (repo_root / "index.json").is_file():
|
|
98
|
+
return repo_root
|
|
99
|
+
|
|
100
|
+
raise FileNotFoundError(
|
|
101
|
+
"Could not locate bundled index.json. Reinstall the package or call configure(username=..., repository=...)."
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _resolve_safe_local_path(data_root: Path, relative_path: str) -> Path:
|
|
106
|
+
"""Resolve *relative_path* inside *data_root* while preventing traversal."""
|
|
107
|
+
root_resolved = data_root.resolve()
|
|
108
|
+
candidate = (root_resolved / relative_path).resolve()
|
|
109
|
+
if not candidate.is_relative_to(root_resolved):
|
|
110
|
+
raise ValueError(f"Refusing path outside data root: {relative_path!r}")
|
|
111
|
+
return candidate
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _normalize_remote_path(relative_path: str) -> str:
|
|
115
|
+
"""Validate and normalize a repository-relative POSIX path."""
|
|
116
|
+
cleaned = relative_path.replace("\\", "/").strip()
|
|
117
|
+
if not cleaned or cleaned.startswith("/"):
|
|
118
|
+
raise ValueError(f"Refusing invalid repository path: {relative_path!r}")
|
|
119
|
+
parts = PurePosixPath(cleaned).parts
|
|
120
|
+
if any(part in ("..", "") for part in parts):
|
|
121
|
+
raise ValueError(f"Refusing path outside repository root: {relative_path!r}")
|
|
122
|
+
return "/".join(parts)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _build_raw_url(cfg: _GitHubConfig, relative_path: str, branch: str | None = None) -> str:
|
|
126
|
+
norm = _normalize_remote_path(relative_path)
|
|
127
|
+
encoded_path = "/".join(urllib.parse.quote(segment, safe="") for segment in norm.split("/"))
|
|
128
|
+
target_branch = urllib.parse.quote(branch or cfg.branch, safe="/")
|
|
129
|
+
user = urllib.parse.quote(cfg.username, safe="")
|
|
130
|
+
repo = urllib.parse.quote(cfg.repository, safe="")
|
|
131
|
+
return f"https://raw.githubusercontent.com/{user}/{repo}/{target_branch}/{encoded_path}"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _fetch_remote_text(url: str, cfg: _GitHubConfig) -> str:
|
|
135
|
+
headers = {"User-Agent": "mycodes/0.1.1"}
|
|
136
|
+
if cfg.token:
|
|
137
|
+
headers["Authorization"] = f"Bearer {cfg.token}"
|
|
138
|
+
|
|
139
|
+
request = urllib.request.Request(url, headers=headers)
|
|
140
|
+
try:
|
|
141
|
+
with urllib.request.urlopen(request, timeout=cfg.timeout) as response:
|
|
142
|
+
return response.read().decode("utf-8")
|
|
143
|
+
except urllib.error.HTTPError as exc:
|
|
144
|
+
status_code = exc.code
|
|
145
|
+
exc.close()
|
|
146
|
+
if status_code == 404:
|
|
147
|
+
raise FileNotFoundError(f"Not found on GitHub: {url}") from exc
|
|
148
|
+
raise RuntimeError(f"GitHub request failed with HTTP {status_code} for {url}") from exc
|
|
149
|
+
except urllib.error.URLError as exc:
|
|
150
|
+
raise ConnectionError(f"Could not connect to GitHub ({url}): {exc.reason}") from exc
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _load_remote_index(cfg: _GitHubConfig) -> dict[str, dict[str, Any]]:
|
|
154
|
+
try:
|
|
155
|
+
raw_text = _fetch_remote_text(_build_raw_url(cfg, "index.json"), cfg)
|
|
156
|
+
except FileNotFoundError:
|
|
157
|
+
if not cfg.branch_explicit and cfg.branch == "main":
|
|
158
|
+
fallback_url = _build_raw_url(cfg, "index.json", branch="master")
|
|
159
|
+
raw_text = _fetch_remote_text(fallback_url, cfg)
|
|
160
|
+
cfg.branch = "master"
|
|
161
|
+
else:
|
|
162
|
+
raise
|
|
163
|
+
|
|
164
|
+
data = json.loads(raw_text)
|
|
165
|
+
if not isinstance(data, dict):
|
|
166
|
+
raise ValueError("Remote index.json must contain a JSON object keyed by snippet ID.")
|
|
167
|
+
return data
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _use_remote(data_root: Path | None) -> bool:
|
|
171
|
+
return data_root is None and _active_config is not None
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def load_index(data_root: Path | None = None) -> dict[str, dict[str, Any]]:
|
|
175
|
+
"""Load and return the snippet index dictionary from ``index.json``."""
|
|
176
|
+
if _use_remote(data_root):
|
|
177
|
+
assert _active_config is not None
|
|
178
|
+
return _load_remote_index(_active_config)
|
|
179
|
+
|
|
180
|
+
root = data_root or get_data_root()
|
|
181
|
+
index_path = root / "index.json"
|
|
182
|
+
with index_path.open("r", encoding="utf-8") as handle:
|
|
183
|
+
data = json.load(handle)
|
|
184
|
+
if not isinstance(data, dict):
|
|
185
|
+
raise ValueError("index.json must contain a JSON object keyed by snippet ID.")
|
|
186
|
+
return data
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def get_entry(code_id: CodeId, data_root: Path | None = None) -> dict[str, Any]:
|
|
190
|
+
"""Return the metadata entry for *code_id* (int or str)."""
|
|
191
|
+
key = str(code_id)
|
|
192
|
+
index = load_index(data_root=data_root)
|
|
193
|
+
if key not in index:
|
|
194
|
+
available = ", ".join(index.keys()) or "(none)"
|
|
195
|
+
raise KeyError(f"Code ID {key!r} not found in index.json. Available IDs: {available}")
|
|
196
|
+
return dict(index[key])
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def get_code_path(code_id: CodeId, data_root: Path | None = None) -> Path:
|
|
200
|
+
"""Return the resolved local filesystem path for snippet *code_id*."""
|
|
201
|
+
root = data_root or get_data_root()
|
|
202
|
+
entry = get_entry(code_id, data_root=root)
|
|
203
|
+
rel_file = entry.get("file")
|
|
204
|
+
if not isinstance(rel_file, str) or not rel_file:
|
|
205
|
+
raise ValueError(f"Entry {str(code_id)!r} in index.json has no valid 'file' field.")
|
|
206
|
+
return _resolve_safe_local_path(root, rel_file)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def code_exists(code_id: CodeId, data_root: Path | None = None) -> bool:
|
|
210
|
+
"""Return True when the target file for *code_id* is available."""
|
|
211
|
+
if _use_remote(data_root):
|
|
212
|
+
try:
|
|
213
|
+
get_code(code_id)
|
|
214
|
+
return True
|
|
215
|
+
except (FileNotFoundError, KeyError, ValueError):
|
|
216
|
+
return False
|
|
217
|
+
|
|
218
|
+
try:
|
|
219
|
+
return get_code_path(code_id, data_root=data_root).is_file()
|
|
220
|
+
except (KeyError, ValueError):
|
|
221
|
+
return False
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def get_code(code_id: CodeId, data_root: Path | None = None) -> str:
|
|
225
|
+
"""Read and return the source code text for snippet *code_id*."""
|
|
226
|
+
if _use_remote(data_root):
|
|
227
|
+
assert _active_config is not None
|
|
228
|
+
entry = get_entry(code_id)
|
|
229
|
+
rel_file = entry.get("file")
|
|
230
|
+
if not isinstance(rel_file, str) or not rel_file:
|
|
231
|
+
raise ValueError(f"Entry {str(code_id)!r} in index.json has no valid 'file' field.")
|
|
232
|
+
url = _build_raw_url(_active_config, rel_file)
|
|
233
|
+
return _fetch_remote_text(url, _active_config)
|
|
234
|
+
|
|
235
|
+
path = get_code_path(code_id, data_root=data_root)
|
|
236
|
+
if not path.is_file():
|
|
237
|
+
raise FileNotFoundError(
|
|
238
|
+
f"Snippet file for ID {str(code_id)!r} does not exist at {path}"
|
|
239
|
+
)
|
|
240
|
+
return path.read_text(encoding="utf-8")
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _print_entries(entries: dict[str, dict[str, Any]]) -> None:
|
|
244
|
+
if not entries:
|
|
245
|
+
print("No matching codes found.")
|
|
246
|
+
return
|
|
247
|
+
|
|
248
|
+
for code_id, meta in entries.items():
|
|
249
|
+
name = meta.get("name", "")
|
|
250
|
+
category = meta.get("category", "")
|
|
251
|
+
file_rel = meta.get("file", "")
|
|
252
|
+
desc = meta.get("description", "")
|
|
253
|
+
status = meta.get("available")
|
|
254
|
+
suffix = "" if status is None else (" [available]" if status else " [missing file]")
|
|
255
|
+
header = f"[{code_id}] {name}"
|
|
256
|
+
if category:
|
|
257
|
+
header += f" ({category})"
|
|
258
|
+
if file_rel:
|
|
259
|
+
header += f" - {file_rel}"
|
|
260
|
+
print(f"{header}{suffix}")
|
|
261
|
+
if desc:
|
|
262
|
+
print(f" {desc}")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def list_codes(
|
|
266
|
+
category: str | None = None,
|
|
267
|
+
tag: str | None = None,
|
|
268
|
+
quiet: bool = False,
|
|
269
|
+
data_root: Path | None = None,
|
|
270
|
+
) -> dict[str, dict[str, Any]]:
|
|
271
|
+
"""List indexed snippets (prints a formatted summary unless ``quiet=True``)."""
|
|
272
|
+
remote = _use_remote(data_root)
|
|
273
|
+
root = None if remote else (data_root or get_data_root())
|
|
274
|
+
index = load_index(data_root=root)
|
|
275
|
+
results: dict[str, dict[str, Any]] = {}
|
|
276
|
+
|
|
277
|
+
cat_norm = category.casefold() if category else None
|
|
278
|
+
tag_norm = tag.casefold() if tag else None
|
|
279
|
+
|
|
280
|
+
for code_id, meta in index.items():
|
|
281
|
+
if cat_norm is not None:
|
|
282
|
+
entry_cat = str(meta.get("category", "")).casefold()
|
|
283
|
+
if entry_cat != cat_norm:
|
|
284
|
+
continue
|
|
285
|
+
if tag_norm is not None:
|
|
286
|
+
entry_tags = [str(t).casefold() for t in meta.get("tags", [])]
|
|
287
|
+
if tag_norm not in entry_tags:
|
|
288
|
+
continue
|
|
289
|
+
|
|
290
|
+
enriched = dict(meta)
|
|
291
|
+
if not remote:
|
|
292
|
+
enriched["available"] = code_exists(code_id, data_root=root)
|
|
293
|
+
results[code_id] = enriched
|
|
294
|
+
|
|
295
|
+
if not quiet:
|
|
296
|
+
_print_entries(results)
|
|
297
|
+
|
|
298
|
+
return results
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def search_codes(
|
|
302
|
+
query: str,
|
|
303
|
+
quiet: bool = True,
|
|
304
|
+
data_root: Path | None = None,
|
|
305
|
+
) -> dict[str, dict[str, Any]]:
|
|
306
|
+
"""Search snippets by ID, name, description, category, or tags."""
|
|
307
|
+
needle = query.strip().casefold()
|
|
308
|
+
all_entries = list_codes(quiet=True, data_root=data_root)
|
|
309
|
+
if not needle:
|
|
310
|
+
matches = all_entries
|
|
311
|
+
else:
|
|
312
|
+
matches = {}
|
|
313
|
+
for code_id, meta in all_entries.items():
|
|
314
|
+
haystack_parts = [
|
|
315
|
+
code_id,
|
|
316
|
+
str(meta.get("name", "")),
|
|
317
|
+
str(meta.get("description", "")),
|
|
318
|
+
str(meta.get("category", "")),
|
|
319
|
+
" ".join(str(t) for t in meta.get("tags", [])),
|
|
320
|
+
]
|
|
321
|
+
if needle in " ".join(haystack_parts).casefold():
|
|
322
|
+
matches[code_id] = meta
|
|
323
|
+
|
|
324
|
+
if not quiet:
|
|
325
|
+
_print_entries(matches)
|
|
326
|
+
|
|
327
|
+
return matches
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def export_codes(
|
|
331
|
+
destination: str | Path = "./retrieved_codes",
|
|
332
|
+
ids: list[CodeId] | None = None,
|
|
333
|
+
overwrite: bool = False,
|
|
334
|
+
include_index: bool = True,
|
|
335
|
+
data_root: Path | None = None,
|
|
336
|
+
) -> dict[str, list[str]]:
|
|
337
|
+
"""Save snippets (and optionally ``index.json``) into *destination*."""
|
|
338
|
+
remote = _use_remote(data_root)
|
|
339
|
+
root = None if remote else (data_root or get_data_root())
|
|
340
|
+
index = load_index(data_root=root)
|
|
341
|
+
dest_root = Path(destination).resolve()
|
|
342
|
+
dest_root.mkdir(parents=True, exist_ok=True)
|
|
343
|
+
|
|
344
|
+
target_ids = [str(i) for i in ids] if ids is not None else list(index.keys())
|
|
345
|
+
exported: list[str] = []
|
|
346
|
+
skipped: list[str] = []
|
|
347
|
+
missing: list[str] = []
|
|
348
|
+
|
|
349
|
+
if include_index:
|
|
350
|
+
dest_index = dest_root / "index.json"
|
|
351
|
+
if dest_index.exists() and not overwrite:
|
|
352
|
+
skipped.append("index.json")
|
|
353
|
+
else:
|
|
354
|
+
if remote:
|
|
355
|
+
dest_index.write_text(json.dumps(index, indent=2) + "\n", encoding="utf-8")
|
|
356
|
+
else:
|
|
357
|
+
assert root is not None
|
|
358
|
+
shutil.copy2(root / "index.json", dest_index)
|
|
359
|
+
exported.append("index.json")
|
|
360
|
+
|
|
361
|
+
for code_id in target_ids:
|
|
362
|
+
entry = get_entry(code_id, data_root=root)
|
|
363
|
+
rel_file = str(entry.get("file", ""))
|
|
364
|
+
if remote:
|
|
365
|
+
norm_rel = _normalize_remote_path(rel_file)
|
|
366
|
+
dest_path = _resolve_safe_local_path(dest_root, norm_rel)
|
|
367
|
+
if dest_path.exists() and not overwrite:
|
|
368
|
+
skipped.append(norm_rel)
|
|
369
|
+
continue
|
|
370
|
+
try:
|
|
371
|
+
content = get_code(code_id)
|
|
372
|
+
except FileNotFoundError:
|
|
373
|
+
missing.append(norm_rel or code_id)
|
|
374
|
+
continue
|
|
375
|
+
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
|
376
|
+
dest_path.write_text(content, encoding="utf-8")
|
|
377
|
+
exported.append(norm_rel)
|
|
378
|
+
continue
|
|
379
|
+
|
|
380
|
+
assert root is not None
|
|
381
|
+
src_path = get_code_path(code_id, data_root=root)
|
|
382
|
+
if not src_path.is_file():
|
|
383
|
+
missing.append(rel_file or code_id)
|
|
384
|
+
continue
|
|
385
|
+
|
|
386
|
+
dest_path = _resolve_safe_local_path(dest_root, rel_file)
|
|
387
|
+
if dest_path.exists() and not overwrite:
|
|
388
|
+
skipped.append(rel_file)
|
|
389
|
+
continue
|
|
390
|
+
|
|
391
|
+
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
|
392
|
+
shutil.copy2(src_path, dest_path)
|
|
393
|
+
exported.append(rel_file)
|
|
394
|
+
|
|
395
|
+
return {"exported": exported, "skipped": skipped, "missing": missing}
|