my-codes01 0.1.1__tar.gz

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.
@@ -0,0 +1,20 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ build/
8
+ dist/
9
+ *.egg-info/
10
+ .eggs/
11
+
12
+ # Virtual environments
13
+ .venv/
14
+ venv/
15
+ ENV/
16
+
17
+ # Tool caches
18
+ .pytest_cache/
19
+ .ruff_cache/
20
+ .mypy_cache/
@@ -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.
@@ -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,72 @@
1
+ # my-codes
2
+
3
+ Indexed Python code snippets packaged for `pip install` and automated PyPI publishing via GitHub Actions.
4
+
5
+ ## Installation
6
+
7
+ Install from PyPI:
8
+
9
+ ```bash
10
+ pip install my-codes01
11
+ ```
12
+
13
+ Or install directly from GitHub:
14
+
15
+ ```bash
16
+ pip install git+https://github.com/yashuus2817/my-codes.git
17
+ ```
18
+
19
+ ## Retrieving Codes in Python / Jupyter Notebook
20
+
21
+ ### Live from GitHub (recommended in Jupyter / Colab)
22
+
23
+ ```python
24
+ from mycodes import configure, get_code, list_codes
25
+
26
+ configure(username="yashuus2817", repository="my-codes")
27
+ list_codes()
28
+ code = get_code(1)
29
+ print(code)
30
+ ```
31
+
32
+ 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).
33
+
34
+ ### Offline / Bundled Mode
35
+
36
+ If you skip `configure(...)`, `mycodes` reads the `index.json` and `codes/` bundled inside the installed package:
37
+
38
+ ```python
39
+ from mycodes import export_codes, get_code, list_codes
40
+
41
+ list_codes()
42
+ code = get_code(1)
43
+ print(code)
44
+
45
+ # Export all bundled files into a folder
46
+ export_codes("./retrieved_codes")
47
+ ```
48
+
49
+ ## CLI Usage
50
+
51
+ ```bash
52
+ mycodes list
53
+ mycodes search addition
54
+ mycodes get 1
55
+ mycodes get 1 --out my_snippet.py
56
+ mycodes export --dir ./retrieved_codes
57
+
58
+ # Or fetch live from a GitHub repo via CLI
59
+ mycodes --user yashuus2817 --repo my-codes list
60
+ mycodes --user yashuus2817 --repo my-codes get 1
61
+ ```
62
+
63
+ ## Connecting GitHub & PyPI (Trusted Publishing)
64
+
65
+ 1. Sign in at <https://pypi.org> → **Your Account → Publishing → Add a new pending publisher**:
66
+ - **PyPI Project Name**: `my-codes01` (must match `name` in `pyproject.toml`)
67
+ - **Owner**: `yashuus2817`
68
+ - **Repository name**: `my-codes`
69
+ - **Workflow name**: `publish.yml`
70
+ - **Environment name**: `pypi`
71
+ 2. In GitHub repo **Settings → Environments**, create an environment named `pypi`.
72
+ 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,3 @@
1
+ import pandas as pd
2
+ df=pd.read_csv(r"C:\Users\HP\Downloads\ML Lab Exp's\Exp-1\student_performance_100_samples.csv")
3
+ df.head(5)
@@ -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
+ }
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "my-codes01"
7
+ version = "0.1.1"
8
+ description = "Retrieve indexed Python code snippets from the my-codes repository."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [
13
+ { name = "yashuus2817" },
14
+ ]
15
+ keywords = ["snippets", "python", "codes", "cli"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Topic :: Utilities",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/yashuus2817/my-codes"
27
+ Repository = "https://github.com/yashuus2817/my-codes"
28
+ Issues = "https://github.com/yashuus2817/my-codes/issues"
29
+
30
+ [project.scripts]
31
+ mycodes = "mycodes.cli:main"
32
+ my-codes = "mycodes.cli:main"
33
+
34
+ [tool.hatch.build.targets.sdist]
35
+ include = [
36
+ "/src",
37
+ "/codes",
38
+ "/index.json",
39
+ "/tests",
40
+ "/pyproject.toml",
41
+ "/README.md",
42
+ "/LICENSE",
43
+ ]
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["src/mycodes"]
47
+
48
+ [tool.hatch.build.targets.wheel.force-include]
49
+ "index.json" = "mycodes/_bundled/index.json"
50
+ "codes" = "mycodes/_bundled/codes"
@@ -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
+ ]
@@ -0,0 +1,8 @@
1
+ """Allow running ``python -m mycodes``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from mycodes.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(main())
@@ -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())
@@ -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}
@@ -0,0 +1,193 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import json
5
+ import tempfile
6
+ import unittest
7
+ import urllib.error
8
+ from contextlib import redirect_stderr, redirect_stdout
9
+ from pathlib import Path
10
+ from unittest.mock import patch
11
+
12
+ from mycodes import (
13
+ code_exists,
14
+ configure,
15
+ export_codes,
16
+ get_code,
17
+ get_config,
18
+ get_data_root,
19
+ list_codes,
20
+ load_index,
21
+ reset_config,
22
+ search_codes,
23
+ )
24
+ from mycodes.cli import main
25
+
26
+
27
+ class _FakeResponse:
28
+ def __init__(self, text: str) -> None:
29
+ self._data = text.encode("utf-8")
30
+
31
+ def read(self) -> bytes:
32
+ return self._data
33
+
34
+ def __enter__(self) -> _FakeResponse:
35
+ return self
36
+
37
+ def __exit__(self, *args: object) -> None:
38
+ return None
39
+
40
+
41
+ class MyCodesTests(unittest.TestCase):
42
+ def tearDown(self) -> None:
43
+ reset_config()
44
+
45
+ def test_repo_index_and_get_code_int_or_str(self) -> None:
46
+ root = get_data_root()
47
+ self.assertTrue((root / "index.json").is_file())
48
+
49
+ index = load_index()
50
+ self.assertIn("1", index)
51
+ self.assertTrue(code_exists(1))
52
+ self.assertFalse(code_exists(2))
53
+
54
+ self.assertEqual(get_code(1), get_code("1"))
55
+ self.assertIn("import pandas as pd", get_code(1))
56
+
57
+ with self.assertRaises(FileNotFoundError):
58
+ get_code(2)
59
+
60
+ with self.assertRaises(KeyError):
61
+ get_code(999)
62
+
63
+ def test_list_codes_prints_and_returns_dict(self) -> None:
64
+ stdout = io.StringIO()
65
+ with redirect_stdout(stdout):
66
+ all_items = list_codes()
67
+ self.assertEqual(set(all_items.keys()), {"1", "2"})
68
+ self.assertTrue(all_items["1"]["available"])
69
+ self.assertFalse(all_items["2"]["available"])
70
+ self.assertIn("[1] Addition", stdout.getvalue())
71
+
72
+ by_tag = list_codes(tag="basics", quiet=True)
73
+ self.assertEqual(list(by_tag.keys()), ["1"])
74
+
75
+ by_category = list_codes(category="basic python", quiet=True)
76
+ self.assertEqual(set(by_category.keys()), {"1", "2"})
77
+
78
+ matches = search_codes("even")
79
+ self.assertEqual(list(matches.keys()), ["2"])
80
+
81
+ def test_configure_remote_github_and_master_fallback(self) -> None:
82
+ remote_index = {
83
+ "1": {
84
+ "name": "Demo",
85
+ "description": "Remote snippet",
86
+ "category": "Demo",
87
+ "file": "codes/demo 1.py",
88
+ }
89
+ }
90
+ seen_urls: list[str] = []
91
+
92
+ def fake_urlopen(request, timeout=15.0):
93
+ url = request.full_url
94
+ seen_urls.append(url)
95
+ if "/main/index.json" in url:
96
+ raise urllib.error.HTTPError(url, 404, "Not Found", {}, None)
97
+ if "/master/index.json" in url:
98
+ return _FakeResponse(json.dumps(remote_index))
99
+ if "/master/codes/demo%201.py" in url:
100
+ return _FakeResponse("print('from github')\n")
101
+ raise urllib.error.HTTPError(url, 404, "Not Found", {}, None)
102
+
103
+ cfg = configure(username="Yuvaaaa02", repository="my-code-library")
104
+ self.assertEqual(cfg["username"], "Yuvaaaa02")
105
+ self.assertEqual(cfg["repository"], "my-code-library")
106
+
107
+ with patch("urllib.request.urlopen", side_effect=fake_urlopen):
108
+ stdout = io.StringIO()
109
+ with redirect_stdout(stdout):
110
+ entries = list_codes()
111
+ self.assertIn("[1] Demo", stdout.getvalue())
112
+ self.assertEqual(list(entries.keys()), ["1"])
113
+ self.assertEqual(get_config()["branch"], "master")
114
+
115
+ code = get_code(1)
116
+ self.assertEqual(code, "print('from github')\n")
117
+
118
+ with tempfile.TemporaryDirectory() as tmp:
119
+ exported = export_codes(tmp)
120
+ self.assertIn("index.json", exported["exported"])
121
+ self.assertIn("codes/demo 1.py", exported["exported"])
122
+ self.assertEqual(
123
+ (Path(tmp) / "codes" / "demo 1.py").read_text(encoding="utf-8"),
124
+ "print('from github')\n",
125
+ )
126
+
127
+ self.assertEqual(
128
+ seen_urls[0],
129
+ "https://raw.githubusercontent.com/Yuvaaaa02/my-code-library/main/index.json",
130
+ )
131
+
132
+ def test_configure_validation(self) -> None:
133
+ with self.assertRaises(ValueError):
134
+ configure(username="bad/user", repository="repo")
135
+ with self.assertRaises(ValueError):
136
+ configure(username="user", repository="")
137
+
138
+ def test_path_traversal_rejected(self) -> None:
139
+ with tempfile.TemporaryDirectory() as tmp:
140
+ tmp_path = Path(tmp)
141
+ (tmp_path / "index.json").write_text(
142
+ json.dumps({"bad": {"name": "Bad", "file": "../outside.py"}}),
143
+ encoding="utf-8",
144
+ )
145
+ with self.assertRaises(ValueError):
146
+ get_code("bad", data_root=tmp_path)
147
+
148
+ def test_export_codes_local(self) -> None:
149
+ with tempfile.TemporaryDirectory() as tmp:
150
+ dest = Path(tmp) / "out"
151
+ first = export_codes(dest)
152
+ self.assertIn("index.json", first["exported"])
153
+ self.assertIn("codes/1.py", first["exported"])
154
+ self.assertIn("codes/2.py", first["missing"])
155
+ self.assertTrue((dest / "codes" / "1.py").is_file())
156
+
157
+ second = export_codes(dest, overwrite=False)
158
+ self.assertEqual(second["exported"], [])
159
+ self.assertIn("codes/1.py", second["skipped"])
160
+
161
+ third = export_codes(dest, overwrite=True)
162
+ self.assertIn("codes/1.py", third["exported"])
163
+
164
+ def test_cli_commands(self) -> None:
165
+ stdout = io.StringIO()
166
+ with redirect_stdout(stdout):
167
+ rc = main(["list"])
168
+ self.assertEqual(rc, 0)
169
+ self.assertIn("[1] Addition", stdout.getvalue())
170
+
171
+ stdout = io.StringIO()
172
+ with redirect_stdout(stdout):
173
+ rc = main(["get", "1"])
174
+ self.assertEqual(rc, 0)
175
+ self.assertIn("import pandas as pd", stdout.getvalue())
176
+
177
+ with tempfile.TemporaryDirectory() as tmp:
178
+ out_file = Path(tmp) / "saved.py"
179
+ stdout = io.StringIO()
180
+ with redirect_stdout(stdout):
181
+ rc = main(["get", "1", "--out", str(out_file)])
182
+ self.assertEqual(rc, 0)
183
+ self.assertTrue(out_file.is_file())
184
+
185
+ stderr = io.StringIO()
186
+ with redirect_stderr(stderr):
187
+ rc = main(["get", "999"])
188
+ self.assertEqual(rc, 1)
189
+ self.assertIn("Error:", stderr.getvalue())
190
+
191
+
192
+ if __name__ == "__main__":
193
+ unittest.main()