Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! The entry points that Python manifests declare: a script or the module of a command that the
//! repository contains is read; a script that is not Python, a missing module or a computed value
//! leaves a site on commands, flags and the environment.
use std::path::PathBuf;
use rust_anything::obligations::{self, Family, Ledger};
/// A throwaway repository containing `files`, removed at the end of the test.
struct Repo(PathBuf);
impl Repo {
fn new(tag: &str, files: &[(&str, &str)]) -> Self {
let dir = std::env::temp_dir().join(format!(
"rust-anything-py-entries-{}-{tag}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
for (path, text) in files {
let full = dir.join(path);
std::fs::create_dir_all(full.parent().unwrap()).unwrap();
std::fs::write(full, text).unwrap();
}
Self(dir)
}
fn ledger(&self) -> Ledger {
obligations::ledger(&self.0, None).unwrap()
}
}
impl Drop for Repo {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn ids(ledger: &Ledger, family: Family) -> Vec<&str> {
let mut ids: Vec<&str> = ledger
.obligations
.iter()
.filter(|o| o.family == family)
.map(|o| o.id.as_str())
.collect();
ids.sort_unstable();
ids
}
/// The sites of a family whose reason contains `needle`.
fn sites<'l>(ledger: &'l Ledger, family: Family, needle: &str) -> Vec<(&'l str, &'l str)> {
ledger
.unresolved
.iter()
.filter(|u| u.family == family && u.reason.contains(needle))
.map(|u| (u.site.as_str(), u.reason.as_str()))
.collect()
}
const XTOOL: &str = "#!/usr/bin/env python3\nimport sys, os\nif sys.argv[1] == \"run\":\n print(os.environ[\"XTOOL_HOME\"])\n";
/// A script outside the repository: reading it would put `--leaked` and `OUTSIDE_HOME` into the
/// registry.
const LEAKY: &str = "#!/usr/bin/env python3\nimport argparse, os\np = argparse.ArgumentParser()\np.add_argument(\"--leaked\")\np.parse_args()\nos.environ[\"OUTSIDE_HOME\"]\n";
/// No obligation comes from a file outside the repository.
fn nothing_leaked(ledger: &Ledger) {
assert!(
ledger
.obligations
.iter()
.all(|o| !o.id.contains("leaked") && !o.id.contains("OUTSIDE_HOME")),
"{:#?}",
ledger.obligations
);
}
#[test]
fn a_script_path_in_a_sub_package_is_judged_as_written() {
// `sub/usr/bin/fake` exists: prefixed with the package folder, `/usr/bin/fake` would point to
// it.
let repo = Repo::new(
"sub-package",
&[
(
"sub/setup.py",
"from setuptools import setup\nsetup(name=\"sub\",\n scripts=[\"/usr/bin/fake\", \"../sibling/tool.py\", \"../../gone/tool\", \"bin/ok.py\"])\n",
),
("sub/usr/bin/fake", "import os\nos.environ[\"FAKE_HOME\"]\n"),
("sub/bin/ok.py", "import os\nos.environ[\"OK_HOME\"]\n"),
(
"sibling/tool.py",
"import os\nos.environ[\"SIBLING_HOME\"]\n",
),
],
);
let ledger = repo.ledger();
assert_eq!(
ids(&ledger, Family::Env),
["env:OK_HOME", "env:SIBLING_HOME"]
);
assert!(
ledger
.obligations
.iter()
.all(|o| !o.id.contains("//") && !o.site.contains("//")),
"{:#?}",
ledger.obligations
);
for family in [Family::Command, Family::Flag, Family::Env] {
assert_eq!(
sites(&ledger, family, "setup()"),
[
(
"sub/setup.py:3",
"setup() `scripts` lists `../../gone/tool`, which is outside the repository: it is not read"
),
(
"sub/setup.py:3",
"setup() `scripts` lists `/usr/bin/fake`, which is outside the repository: it is not read"
),
],
"{family:?}"
);
}
}
#[cfg(unix)]
#[test]
fn a_link_that_leaves_the_repository_is_never_followed() {
use std::os::unix::fs::symlink;
let outside = Repo::new(
"links-outside",
&[
("pkgdir/__init__.py", ""),
("pkgdir/cli.py", LEAKY),
("leaf.py", LEAKY),
("m.py", LEAKY),
("tool", LEAKY),
],
);
let repo = Repo::new(
"links",
&[
(
"setup.py",
"from setuptools import setup\nsetup(\n name=\"l\",\n scripts=[\"bin/linkout\", \"bin/linkin\"],\n entry_points={\"console_scripts\": [\n \"a = lnpkg.cli:main\",\n \"b = pkg.lnfile:main\",\n \"c = pkg.ok:main\",\n ]},\n)\n",
),
("pkg/__init__.py", ""),
(
"pkg/ok.py",
"import os\n\ndef main():\n return os.environ[\"OK_HOME\"]\n",
),
(
"inner/tool.py",
"#!/usr/bin/env python3\nimport os\nos.environ[\"INNER_HOME\"]\n",
),
(
"main.py",
"import os\nimport lnmod\n\nos.environ[\"MAIN_HOME\"]\n",
),
("bin/keep", ""),
],
);
let out = &outside.0;
symlink(out.join("pkgdir"), repo.0.join("lnpkg")).unwrap();
symlink(out.join("leaf.py"), repo.0.join("pkg/lnfile.py")).unwrap();
symlink(out.join("m.py"), repo.0.join("lnmod.py")).unwrap();
symlink(out.join("tool"), repo.0.join("bin/linkout")).unwrap();
// A link that stays inside the repository is read.
symlink(repo.0.join("inner/tool.py"), repo.0.join("bin/linkin")).unwrap();
let ledger = repo.ledger();
nothing_leaked(&ledger);
assert_eq!(
ids(&ledger, Family::Env),
["env:INNER_HOME", "env:MAIN_HOME", "env:OK_HOME"]
);
assert_eq!(
sites(&ledger, Family::Command, "setup()"),
[
(
"setup.py:4",
"setup() `scripts` lists `bin/linkout`, which is outside the repository: it is not read"
),
// An entry is located at the line of `entry_points`, like the other sites of the
// manifest.
(
"setup.py:5",
"setup() `entry_points` `console_scripts` entry `a` points at `lnpkg.cli:main`, whose module `lnpkg.cli` is not in the repository"
),
(
"setup.py:5",
"setup() `entry_points` `console_scripts` entry `b` points at `pkg.lnfile:main`, whose module `pkg.lnfile` is not in the repository"
),
]
);
// The import in `main.py` points to the link: the file is not opened, and it says so.
for family in [Family::Export, Family::Flag, Family::Env] {
assert_eq!(
sites(&ledger, family, "leaves the repository"),
[(
"lnmod.py:1",
"the file is a link that leaves the repository; it is not read"
)],
"{family:?}"
);
}
}
#[cfg(unix)]
#[test]
fn a_manifest_that_is_a_link_out_of_the_repository_is_not_opened() {
use std::os::unix::fs::symlink;
// Read, these manifests would leave sites that name `bin/pygone`, `bin/cfggone`,
// `bin/tomlgone` and `leak.cli`.
let outside = Repo::new(
"manifests-outside",
&[
(
"setup.py",
"from setuptools import setup\nsetup(name=\"o\", scripts=[\"bin/pygone\"])\n",
),
("setup.cfg", "[options]\nscripts = bin/cfggone\n"),
(
"pyproject.toml",
"[project]\nname = \"o\"\n\n[project.scripts]\nleak = \"leak.cli:main\"\n\n[tool.setuptools]\nscript-files = [\"bin/tomlgone\"]\n",
),
],
);
let repo = Repo::new(
"manifest-links",
&[("main.py", "import os\n\nos.environ[\"MAIN_HOME\"]\n")],
);
for name in ["setup.py", "setup.cfg", "pyproject.toml"] {
symlink(outside.0.join(name), repo.0.join(name)).unwrap();
}
let ledger = repo.ledger();
assert_eq!(ids(&ledger, Family::Env), ["env:MAIN_HOME"]);
assert!(
!ledger
.unresolved
.iter()
.any(|u| u.reason.contains("gone") || u.reason.contains("leak")),
"{:#?}",
ledger.unresolved
);
for family in [Family::Command, Family::Flag, Family::Env] {
let mut found = sites(&ledger, family, "leaves the repository");
found.sort_unstable();
assert_eq!(
found,
[
(
"pyproject.toml:1",
"`pyproject.toml` is a link that leaves the repository: the commands it declares are not read"
),
(
"setup.cfg:1",
"`setup.cfg` is a link that leaves the repository: the commands it declares are not read"
),
(
"setup.py:1",
"`setup.py` is a link that leaves the repository: the commands it declares are not read"
),
],
"{family:?}"
);
}
}
#[test]
fn setup_py_scripts_are_read_when_python_and_sites_otherwise() {
let repo = Repo::new(
"setup-scripts",
&[
(
"setup.py",
"from setuptools import setup\nsetup(name=\"x\", packages=[\"x\"],\n scripts=[\"bin/xtool\", \"bin/run.sh\", \"bin/gone\"])\n",
),
("bin/xtool", XTOOL),
("bin/run.sh", "#!/bin/sh\necho \"$HOME\"\n"),
("x/__init__.py", "def lib():\n return 1\n"),
],
);
let ledger = repo.ledger();
assert_eq!(ledger.shape, "library");
assert_eq!(ids(&ledger, Family::Env), ["env:XTOOL_HOME"]);
for family in [Family::Command, Family::Flag, Family::Env] {
assert_eq!(
sites(&ledger, family, "setup()"),
[
(
"setup.py:3",
"setup() `scripts` lists `bin/gone`, which is not in the repository: the command it installs is not read"
),
(
"setup.py:3",
"setup() `scripts` lists `bin/run.sh`, which is not Python: the commands, flags and environment variables it reads are not read"
),
],
"{family:?}"
);
}
}
#[test]
fn a_script_path_that_leaves_the_repository_is_a_site_and_is_never_read() {
// The neighbouring script exists and reads `OUTSIDE_HOME`: it must not be opened.
let outside = Repo::new("outside-neighbour", &[("bin/pytool", LEAKY)]);
let neighbour = outside.0.file_name().unwrap().to_str().unwrap().to_string();
let setup = format!(
"from setuptools import setup\nsetup(name=\"x\", packages=[\"x\"],\n scripts=[\"/usr/bin/env\", \"../{neighbour}/bin/pytool\", \"bin/xtool\"])\n"
);
let repo = Repo::new(
"outside",
&[
("setup.py", setup.as_str()),
("bin/xtool", XTOOL),
("x/__init__.py", "def lib():\n return 1\n"),
],
);
let ledger = repo.ledger();
nothing_leaked(&ledger);
assert_eq!(ids(&ledger, Family::Env), ["env:XTOOL_HOME"]);
assert!(
ledger.obligations.iter().all(|o| !o.id.contains("..")
&& !o.id.contains("/usr/")
&& !o.site.starts_with('/')
&& !o.site.starts_with("..")),
"{:#?}",
ledger.obligations
);
let escaped = format!(
"setup() `scripts` lists `../{neighbour}/bin/pytool`, which is outside the repository: it is not read"
);
for family in [Family::Command, Family::Flag, Family::Env] {
assert_eq!(
sites(&ledger, family, "outside the repository"),
[
("setup.py:3", escaped.as_str()),
(
"setup.py:3",
"setup() `scripts` lists `/usr/bin/env`, which is outside the repository: it is not read"
),
],
"{family:?}"
);
}
}
#[test]
fn setup_py_entry_points_name_a_missing_module_or_a_computed_value() {
let repo = Repo::new(
"setup-entry-points",
&[
(
"setup.py",
"from setuptools import setup\nSCRIPTS = []\nsetup(\n name=\"y\",\n entry_points={\n \"console_scripts\": [\"ytool=y.gone:main\", \"yok = y.cli:main\"],\n \"gui_scripts\": SCRIPTS,\n \"pytest11\": [\"plug = y.plugin\"],\n },\n)\n",
),
("y/__init__.py", "def lib():\n return 1\n"),
(
"y/cli.py",
"import os\n\ndef main():\n return os.getenv(\"Y_HOME\")\n",
),
],
);
let ledger = repo.ledger();
assert_eq!(ids(&ledger, Family::Env), ["env:Y_HOME"]);
assert_eq!(
sites(&ledger, Family::Command, "setup()"),
[
(
"setup.py:6",
"setup() `entry_points` `console_scripts` entry `ytool` points at `y.gone:main`, whose module `y.gone` is not in the repository"
),
(
"setup.py:7",
"setup() `entry_points` `gui_scripts` is not a list of string literals: the commands it declares are not known"
),
]
);
// A plugin's group does not install a command.
assert!(sites(&ledger, Family::Command, "plug").is_empty());
}
#[test]
fn setup_cfg_scripts_and_entry_points_are_read() {
let repo = Repo::new(
"setup-cfg",
&[
(
"setup.cfg",
"[metadata]\nname = z\n\n[options]\npackages = z\nscripts =\n bin/xtool\n bin/tool.sh\n\n[options.entry_points]\nconsole_scripts =\n zz = z.missing:main\n",
),
("bin/xtool", XTOOL),
("bin/tool.sh", "#!/bin/sh\n"),
("z/__init__.py", ""),
],
);
let ledger = repo.ledger();
assert_eq!(ids(&ledger, Family::Env), ["env:XTOOL_HOME"]);
assert_eq!(
sites(&ledger, Family::Flag, "setup.cfg"),
[
(
"setup.cfg:8",
"setup.cfg `[options] scripts` lists `bin/tool.sh`, which is not Python: the commands, flags and environment variables it reads are not read"
),
(
"setup.cfg:12",
"setup.cfg `[options.entry_points] console_scripts` entry `zz` points at `z.missing:main`, whose module `z.missing` is not in the repository"
),
]
);
}
#[test]
fn pyproject_entry_points_name_missing_modules_and_read_present_ones() {
let repo = Repo::new(
"pyproject",
&[
(
"pyproject.toml",
"[project]\nname = \"ep\"\nversion = \"1\"\n[project.scripts]\nep = \"ep.missing_cli:main\"\n[project.entry-points.console_scripts]\nep2 = \"ep.cli2:main\"\n[project.gui-scripts]\ndemo = \"examples.demo:main\"\n[tool.setuptools]\nscript-files = [\"bin/run.sh\"]\n",
),
("ep/__init__.py", "def lib():\n return 1\n"),
// `examples/` is left out by discovery: only the command makes it read.
(
"examples/demo.py",
"import os\n\ndef main():\n return os.environ[\"DEMO_TOKEN\"]\n",
),
("bin/run.sh", "#!/bin/sh\n"),
],
);
let ledger = repo.ledger();
assert_eq!(ledger.shape, "cli");
assert_eq!(ids(&ledger, Family::Env), ["env:DEMO_TOKEN"]);
assert_eq!(
sites(&ledger, Family::Env, "`["),
[
(
"pyproject.toml:5",
"`[project.scripts]` entry `ep` points at `ep.missing_cli:main`, whose module `ep.missing_cli` is not in the repository"
),
(
"pyproject.toml:7",
"`[project.entry-points.console_scripts]` entry `ep2` points at `ep.cli2:main`, whose module `ep.cli2` is not in the repository"
),
(
"pyproject.toml:11",
"`[tool.setuptools] script-files` lists `bin/run.sh`, which is not Python: the commands, flags and environment variables it reads are not read"
),
]
);
}
#[test]
fn an_extensionless_script_with_a_python_shebang_is_read() {
let repo = Repo::new(
"shebang",
&[
("lib.py", "def a():\n return 1\n"),
(
"tool",
"#!/usr/bin/env python3\nimport argparse\np = argparse.ArgumentParser()\np.add_argument(\"--zz\")\np.parse_args()\n",
),
(
"tests/helper",
"#!/usr/bin/env python3\nimport os\nos.environ[\"TEST_ONLY\"]\n",
),
("notes", "#!/bin/sh\n"),
],
);
let ledger = repo.ledger();
assert_eq!(ids(&ledger, Family::Flag), ["flag:tool#--zz"]);
assert!(ids(&ledger, Family::Env).is_empty());
}