depyore 0.1.0__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.
depyore/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Depyore historical environment recovery."""
depyore/__main__.py ADDED
@@ -0,0 +1,2 @@
1
+ from .cli import main
2
+ raise SystemExit(main())
depyore/cli.py ADDED
@@ -0,0 +1,217 @@
1
+ import argparse
2
+ import ast
3
+ from datetime import date
4
+ from importlib import metadata
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import tomllib
14
+ from urllib.request import Request, urlopen
15
+ from urllib.error import URLError
16
+ from packaging.requirements import Requirement
17
+ from packaging.utils import canonicalize_name
18
+
19
+ SKIP = {".git", ".depyore", ".venv", "venv", "node_modules", "__pycache__", "dist", "build"}
20
+ MAP = {"PIL":"Pillow","sklearn":"scikit-learn","cv2":"opencv-python","yaml":"PyYAML"}
21
+
22
+
23
+ def run(args, cwd, capture=False):
24
+ exe = shutil.which(str(args[0]))
25
+ if not exe:
26
+ raise ValueError(f"Install {args[0]} and add it to PATH.")
27
+ return subprocess.run([exe,*map(str,args[1:])], cwd=cwd, check=True, text=True,
28
+ stdout=subprocess.PIPE if capture else None, timeout=300).stdout
29
+
30
+
31
+ def read_json(path):
32
+ return json.loads(path.read_text(encoding="utf8")) if path.exists() else {}
33
+
34
+
35
+ def scan(root, cutoff=None):
36
+ info = tomllib.loads((root/"pyproject.toml").read_text(encoding="utf8")) if (root/"pyproject.toml").exists() else {}
37
+ py = info.get("project", {})
38
+ node = read_json(root/"package.json")
39
+ req = list(py.get("dependencies", []))
40
+ if (root/"requirements.txt").exists():
41
+ req += [s.split(" #")[0].strip() for s in (root/"requirements.txt").read_text().splitlines() if s.strip() and not s.lstrip().startswith("#")]
42
+ evidence = "explicit date"
43
+ if not cutoff:
44
+ evidence = "latest Git commit touching this project"
45
+ result = subprocess.run(["git","log","-1","--format=%cs","--","."],cwd=root,capture_output=True,text=True) if shutil.which("git") else None
46
+ cutoff = result.stdout.strip() if result and result.returncode==0 else None
47
+ if cutoff:
48
+ date.fromisoformat(cutoff)
49
+ imports, local, node_imports = set(), set(), set()
50
+ py_files = False
51
+ for folder, dirs, files in os.walk(root):
52
+ dirs[:] = [d for d in dirs if d not in SKIP and not d.startswith(".")]
53
+ for name in files:
54
+ p = Path(folder)/name
55
+ if p.suffix==".py":
56
+ py_files = True
57
+ local.add(p.stem)
58
+ if name=="__init__.py":
59
+ local.add(p.parent.name)
60
+ try:
61
+ tree = ast.parse(p.read_bytes())
62
+ except (SyntaxError, ValueError):
63
+ continue
64
+ for n in ast.walk(tree):
65
+ if isinstance(n,ast.Import):
66
+ imports.update(a.name.split(".")[0] for a in n.names)
67
+ elif isinstance(n,ast.ImportFrom) and not n.level and n.module:
68
+ imports.add(n.module.split(".")[0])
69
+ elif p.suffix in {".js",".mjs",".cjs",".ts"}:
70
+ for spec in re.findall(r"""(?:\brequire\(\s*|\bfrom\s+|\bimport\s+)["']([^"']+)""",p.read_text(encoding="utf8",errors="replace")):
71
+ if spec[0].isalnum() or spec.startswith("@"):
72
+ node_imports.add("/".join(spec.split("/")[:2]) if spec.startswith("@") else spec.split("/")[0])
73
+ declared = {canonicalize_name(Requirement(s).name) for s in req}
74
+ candidates = sorted(n for n in imports-local-sys.stdlib_module_names if canonicalize_name(MAP.get(n,n)) not in declared)
75
+ if node_imports and shutil.which("node"):
76
+ builtins = json.loads(run(["node","-p","JSON.stringify(require('module').builtinModules)"],root,True))
77
+ node_imports.difference_update(builtins)
78
+ def hint(file, fallback):
79
+ return (root/file).read_text().strip() if (root/file).is_file() else fallback
80
+ return dict(date=cutoff,date_source=evidence if cutoff else "unknown",python_project=py_files or bool(req) or bool(info),
81
+ node_project=(root/"package.json").is_file(),python=hint(".python-version",py.get("requires-python")),
82
+ node=hint(".nvmrc",node.get("engines",{}).get("node")),requirements=req,
83
+ missing_import_candidates=candidates,node_import_candidates=sorted(n for n in node_imports if not n.startswith("node:") and n not in {**node.get("dependencies",{}),**node.get("devDependencies",{}),**node.get("peerDependencies",{}),**node.get("optionalDependencies",{})}))
84
+
85
+
86
+ def restore(root, info, target, verify=None):
87
+ if not info["date"]:
88
+ raise ValueError("No Git date available. Supply --date YYYY-MM-DD.")
89
+ if not (info["python_project"] or info["node_project"]):
90
+ raise ValueError("No supported Python or Node project found.")
91
+ script = root/verify if verify else None
92
+ if script and (not script.is_file() or script.suffix not in {".py",".js",".cjs",".mjs"}):
93
+ raise ValueError("--verify needs an existing Python or JavaScript test script.")
94
+ target.mkdir(parents=True,exist_ok=False)
95
+ packages = []
96
+ node_exe = shutil.which("node")
97
+ if info["python_project"]:
98
+ env = target/"venv"
99
+ run(["uv","venv","--python",info["python"] or sys.executable,env],root)
100
+ python = env/("Scripts/python.exe" if os.name=="nt" else "bin/python")
101
+ info = dict(info, python_before=sys.version.split()[0],
102
+ python_recovered=run([python,"-c","import platform;print(platform.python_version())"],root,True).strip())
103
+ req = target/"requirements.in"
104
+ req.write_text("\n".join(info["requirements"])+"\n")
105
+ lock = target/"requirements.txt"
106
+ run(["uv","pip","compile","--python",python,"--only-binary",":all:","--exclude-newer",info["date"]+"T23:59:59Z",req,"-o",lock],root)
107
+ run(["uv","pip","sync","--python",python,"--only-binary",":all:",lock],root)
108
+ for line in lock.read_text().splitlines():
109
+ m = re.match(r"^([\w.-]+)==([^\s;]+)",line)
110
+ if m:
111
+ name,version=m.groups()
112
+ try: installed=metadata.version(name)
113
+ except metadata.PackageNotFoundError: installed=None
114
+ packages.append(dict(ecosystem="PyPI",name=name,before=installed,recovered=version))
115
+ if info["node_project"]:
116
+ work = target/"node"
117
+ work.mkdir()
118
+ for name in ("package.json","package-lock.json"):
119
+ if (root/name).is_file(): shutil.copyfile(root/name,work/name)
120
+ requested = info["node"]
121
+ current = run(["node","-p","process.versions.node"],root,True).strip()
122
+ recovered_node = current
123
+ if requested and re.fullmatch(r"v?[0-9]+(?:\.[0-9]+){0,2}", requested):
124
+ requested = requested.lstrip("v")
125
+ if current != requested and not current.startswith(requested + "."):
126
+ runtimes = target/"runtime"
127
+ runtimes.mkdir()
128
+ run(["npm","install","--prefix",runtimes,"--no-audit","--no-fund","--before",
129
+ info["date"]+"T23:59:59Z","node@"+requested],runtimes)
130
+ node_exe = runtimes/"node_modules/node/bin"/("node.exe" if os.name=="nt" else "node")
131
+ if not node_exe.exists() and os.name=="nt":
132
+ node_exe = runtimes/"node_modules/node/node.exe"
133
+ recovered_node = run([node_exe,"-p","process.versions.node"],root,True).strip()
134
+ info = dict(info, node_before=current, node_recovered=recovered_node)
135
+ locked=(work/"package-lock.json").exists()
136
+ run(["npm","ci" if locked else "install","--ignore-scripts","--no-audit","--no-fund","--engine-strict","--node-version="+recovered_node,*([] if locked else ["--before",info["date"]+"T23:59:59Z"])],work)
137
+ lock=read_json(work/"package-lock.json")
138
+ for key,pkg in lock.get("packages",{}).items():
139
+ if key.startswith("node_modules/") and "version" in pkg:
140
+ name=key.rsplit("node_modules/",1)[1]
141
+ old=read_json(root/key/"package.json").get("version")
142
+ packages.append(dict(ecosystem="npm",name=name,before=old,recovered=pkg["version"]))
143
+ if script:
144
+ if script.suffix==".py" and info["python_project"]:
145
+ run([python,script],root)
146
+ elif script.suffix!=".py" and info["node_project"]:
147
+ shutil.copytree(root,work,dirs_exist_ok=True,ignore=shutil.ignore_patterns(*SKIP,"package*.json"))
148
+ run([node_exe,work/script.relative_to(root)],work)
149
+ else:
150
+ raise ValueError("Test script language does not match the recovered project.")
151
+ return dict(**info,packages=packages,verification="passed" if script else "not run",
152
+ warning="Historical dependencies can contain known vulnerabilities. Review before deployment.")
153
+
154
+
155
+ def audit(packages):
156
+ findings=[]
157
+ for start in range(0,len(packages),100):
158
+ batch=packages[start:start+100]
159
+ queries=[{"package":{"name":p["name"],"ecosystem":p["ecosystem"]},"version":p["recovered"]} for p in batch]
160
+ req=Request("https://api.osv.dev/v1/querybatch",json.dumps({"queries":queries}).encode(),{"Content-Type":"application/json"})
161
+ with urlopen(req,timeout=30) as response: results=json.load(response)["results"]
162
+ for p,result in zip(batch,results,strict=True):
163
+ findings.extend({"package":p["name"],"advisory":v["id"]} for v in result.get("vulns",[]))
164
+ return findings
165
+
166
+
167
+ def main(argv=None):
168
+ parser=argparse.ArgumentParser(prog="depyore")
169
+ sub=parser.add_subparsers(dest="cmd",required=True)
170
+ for cmd in ("scan","restore","investigate"):
171
+ p=sub.add_parser(cmd)
172
+ p.add_argument("path",nargs="?",default=".")
173
+ p.add_argument("--date")
174
+ if cmd!="scan":
175
+ p.add_argument("--verify",required=cmd=="investigate")
176
+ p.add_argument("--audit",action="store_true")
177
+ if cmd=="investigate":
178
+ p.add_argument("--try-pin",action="append",required=True,help="Python candidate, e.g. click==8.1.7")
179
+ a=parser.parse_args(argv)
180
+ try:
181
+ root=Path(a.path).resolve()
182
+ if not root.is_dir(): raise ValueError("Choose an existing project directory.")
183
+ info=scan(root,a.date)
184
+ if a.cmd=="scan":
185
+ print(json.dumps(info,indent=2))
186
+ return 0
187
+ base=root/".depyore"
188
+ base.mkdir(exist_ok=True)
189
+ out=Path(tempfile.mkdtemp(prefix="run",dir=base))
190
+ report=restore(root,info,out/"environment",a.verify)
191
+ if a.cmd=="investigate":
192
+ if Path(a.verify).suffix!=".py": raise ValueError("Pin investigation currently supports Python tests.")
193
+ findings=[]
194
+ for pin in a.try_pin:
195
+ if not re.fullmatch(r"[\w.-]+==[\w.+!-]+",pin): raise ValueError("Supply an exact name==version.")
196
+ with tempfile.TemporaryDirectory() as tmp:
197
+ trial=Path(tmp)/"venv"
198
+ baseline=out/"environment/venv"/("Scripts/python.exe" if os.name=="nt" else "bin/python")
199
+ run(["uv","venv","--python",baseline,trial],root)
200
+ exe=trial/("Scripts/python.exe" if os.name=="nt" else "bin/python")
201
+ run(["uv","pip","sync","--python",exe,"--only-binary",":all:",out/"environment/requirements.txt"],root)
202
+ run(["uv","pip","install","--python",exe,"--only-binary",":all:","--no-deps",pin],root)
203
+ try: run([exe,root/a.verify],root)
204
+ except subprocess.CalledProcessError: status="test failed after changing pin"
205
+ else: status="passed"
206
+ findings.append({"pin":pin,"result":status})
207
+ report["investigation"]=findings
208
+ if a.audit: report["advisories"]=audit(report["packages"])
209
+ (out/"report.json").write_text(json.dumps(report,indent=2))
210
+ for pkg in report["packages"]:
211
+ print(f"{pkg['name']:24} {pkg['before'] or 'absent':14} -> {pkg['recovered']}")
212
+ print(f"Verification: {report['verification']}\n{report['warning']}\nReport: {out/'report.json'}")
213
+ for finding in report.get("investigation",[]): print(finding["pin"],finding["result"])
214
+ return 0
215
+ except (OSError,ValueError,subprocess.SubprocessError,URLError) as e:
216
+ print(f"Depyore: {e}",file=sys.stderr)
217
+ return 1
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.4
2
+ Name: depyore
3
+ Version: 0.1.0
4
+ Summary: Recover historical Python and Node dependency environments
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/Unique50101/depyore
7
+ Project-URL: Homepage, https://uniqueoss.com
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: packaging>=24
12
+ Dynamic: license-file
13
+
14
+ # Depyore
15
+
16
+ Bring old code back to life. Depyore reads a checkout, finds clues about its original runtime, and asks uv or npm to rebuild its dependencies. It writes a separate environment and a JSON report. Free under MIT. No AI key.
17
+
18
+ ## Try a recovery
19
+
20
+ Install Python 3.11+ and uv. For Node projects, also install Node.js and npm.
21
+
22
+ ```sh
23
+ pip install depyore
24
+ depyore scan .
25
+ depyore restore . --date 2021-12-31 --verify check.py
26
+ ```
27
+
28
+ From a checkout of this repository, try either included example:
29
+
30
+ ```sh
31
+ depyore restore examples/python --date 2021-12-31 --verify check.py
32
+ depyore restore examples/node --date 2021-12-31 --verify check.cjs
33
+ ```
34
+
35
+ | Stage | What you get |
36
+ | --- | --- |
37
+ | Scan | Latest Git commit date affecting the directory, runtime hints from .python-version, pyproject.toml, .nvmrc or package.json, and undeclared import candidates. Use --date for a known working date. |
38
+ | Restore | uv resolves wheels uploaded by the end of that UTC date. npm uses the existing lockfile when present, otherwise resolves by date. Every run gets its own .depyore directory. |
39
+ | Verify | A test script you select runs against the recovered dependencies. The report records whether it ran and passed. Run only trusted projects and tests. These environments share your account permissions. |
40
+ | Investigate | Run a passing Python baseline, then replace one direct or transitive pin per trial and rerun the same test. A failure identifies a candidate regression for that test. |
41
+ | Audit | Add --audit to query OSV for the recovered package names and versions. The advisory IDs are stored in report.json. An empty response only covers known advisories. |
42
+
43
+ ```sh
44
+ depyore investigate examples/python --date 2021-12-31 --verify check.py --try-pin colorama==0.4.6
45
+ ```
46
+
47
+ The report compares the versions visible to the scanning Python interpreter or installed in the source project's node_modules with recovered versions. Missing import candidates require review before adding them to a manifest. Python module names can differ from package names. Python projects need PEP 508 dependencies in requirements.txt or project.dependencies. Editable installs, requirements-file options, source-only Python releases, npm workspaces and native install scripts are outside this release. A failed check exits nonzero and retains its run directory for inspection. Repeated runs leave earlier results available.
48
+
49
+ Python recovery requests the declared interpreter from uv, or uses the current interpreter if no hint exists. Node recovery reads numeric major, minor or patch hints from .nvmrc or engines.node. If the installed runtime differs, it requests a dated Node binary from npm and runs the verification script with it. Complex engine ranges use the installed Node and npm engine validation. A Git date is a clue, and later maintenance commits can make an explicit date more accurate.
50
+
51
+ ## Node CLI
52
+
53
+ With uv installed, `npx depyore scan .` launches the same version of the Python engine via uvx. The npm package is a lightweight launcher.
54
+
55
+ ## GitHub Action
56
+
57
+ ```yaml
58
+ steps:
59
+ - uses: actions/checkout@v4
60
+ with:
61
+ fetch-depth: 0
62
+ - uses: Unique50101/depyore@v0.1.0
63
+ with:
64
+ path: .
65
+ ```
66
+
67
+ The action scans the checkout without running project code. Run the restore and investigate commands on trusted projects in your own environment.
@@ -0,0 +1,9 @@
1
+ depyore/__init__.py,sha256=YMkfWwBoDDVWz4iAxni8Dk_FKLO86280jfQMlgF7-2A,47
2
+ depyore/__main__.py,sha256=ee5vE0xcUZM3fPmxicvcw-IJXkm6nOwxARREHBWpF8Q,47
3
+ depyore/cli.py,sha256=x8dKR4qIxNKrijxeazxwRhs89IpCJxnrMiB7PjERMYs,12149
4
+ depyore-0.1.0.dist-info/licenses/LICENSE,sha256=au2YvUfol0NHzvc_KdwNBPNRsSAjM_ujdNqURZx-VLA,1067
5
+ depyore-0.1.0.dist-info/METADATA,sha256=HnVyKZTsK3DWR2evZD4w62awH_0f3gUncmd53fSljFU,3716
6
+ depyore-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ depyore-0.1.0.dist-info/entry_points.txt,sha256=jbE4gdO1q6cMUUM5MvxCH71pfhNuolWt0TrWe3Yxhds,45
8
+ depyore-0.1.0.dist-info/top_level.txt,sha256=orAKBLrJde80NCosiEUPbPsKhkxwf3eBcfb3cNlDdhA,8
9
+ depyore-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ depyore = depyore.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Unique OSS
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
7
+ deal in the Software without restriction, including without limitation the
8
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9
+ sell 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
13
+ all 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
20
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21
+ IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ depyore