shellless-ops 0.1.0__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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zhangs-cedar
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,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: shellless-ops
3
+ Version: 0.1.0
4
+ Summary: Repeatable file and process operations without shell command strings
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/zhangs-cedar/shellless-ops
7
+ Project-URL: Issues, https://github.com/zhangs-cedar/shellless-ops/issues
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Operating System :: MacOS
10
+ Classifier: Operating System :: Microsoft :: Windows
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # shellless-ops
21
+
22
+ Repeatable file and process operations without maintaining separate Bash and PowerShell scripts. Built for Python 3.11+ with no runtime dependencies. Use the Python API for scripts, or pass an argument array to the CLI from task runners.
23
+
24
+ ## Install
25
+
26
+ Before the first PyPI release, install from a local checkout:
27
+
28
+ ```text
29
+ python -m pip install .
30
+ ```
31
+
32
+ ## Example
33
+
34
+ ```python
35
+ import sys
36
+
37
+ from shellless_ops import find_files, mkdir, run, write_text
38
+
39
+ out = mkdir("build reports")
40
+ write_text(out / "summary.txt", "ready\n")
41
+ files = find_files(out, "*.txt")
42
+ result = run([sys.executable, "--version"], cwd=out, timeout=10)
43
+ print(files, result.stdout.strip())
44
+ ```
45
+
46
+ ```text
47
+ shellless-ops mkdir "build reports"
48
+ shellless-ops write "build reports/summary.txt" "ready"
49
+ shellless-ops copy "build reports/summary.txt" "build reports/backup.txt"
50
+ shellless-ops find "build reports" --pattern "*.txt"
51
+ shellless-ops read "build reports/summary.txt"
52
+ shellless-ops run --timeout 10 -- python --version
53
+ ```
54
+
55
+ `python -m shellless_ops` also works. A task runner with an argument-array API can use `["python", "-m", "shellless_ops", "find", "build reports", "--pattern", "*.txt"]`. A command typed into a terminal is still parsed by that terminal's shell; quote paths with spaces and wildcard patterns at that boundary.
56
+
57
+ ## Behavior
58
+
59
+ | API | Contract |
60
+ | --- | --- |
61
+ | `mkdir(path)` | Create missing parents, accept an existing directory and return its `Path`. |
62
+ | `read_text(path)` / `write_text(path, text)` | Default to UTF-8 and preserve line endings. Writing replaces existing contents, requires an existing parent directory and returns the `Path`. CLI `read` emits UTF-8 bytes. |
63
+ | `copy_file(source, target)` | Copy the contents to an exact destination and return its `Path`. Reject an existing destination. Metadata is not copied. An interrupted copy can leave a partial destination. |
64
+ | `find_files(root, pattern="*")` | Recursively match file basenames, including dotfiles, with case-sensitive glob matching. Return paths sorted by their `/`-separated relative names. Skip file symlinks and do not descend into directory symlinks or nested Windows directory reparse points. CLI `find` emits a JSON array of paths with `/` separators. |
65
+ | `run(argv, *, cwd=None, timeout=None, check=True, capture=True, encoding="utf-8")` | Pass the executable and each argument separately in a non-empty list or tuple. Return `subprocess.CompletedProcess`. By default, capture output as UTF-8 text and raise `CalledProcessError` on a nonzero exit. Set `encoding=None` for bytes or `capture=False` to inherit output. CLI `run` inherits output and propagates exit status; it uses 124 on timeout and `128 + signal` for signal exits on POSIX. |
66
+
67
+ `run` does not expand variables, implement pipelines or redirection, or support Windows `.bat` and `.cmd` entry points. It uses the operating system's executable lookup rules; pass an absolute executable path to select a specific installation. A timeout targets the directly launched process, not its entire process tree. Choose the executable and its options as trusted configuration: shell-free launching is not a sandbox for the program being run.
68
+
69
+ Run tests from the checkout after installing: `python -m unittest discover -s tests -v`.
@@ -0,0 +1,50 @@
1
+ # shellless-ops
2
+
3
+ Repeatable file and process operations without maintaining separate Bash and PowerShell scripts. Built for Python 3.11+ with no runtime dependencies. Use the Python API for scripts, or pass an argument array to the CLI from task runners.
4
+
5
+ ## Install
6
+
7
+ Before the first PyPI release, install from a local checkout:
8
+
9
+ ```text
10
+ python -m pip install .
11
+ ```
12
+
13
+ ## Example
14
+
15
+ ```python
16
+ import sys
17
+
18
+ from shellless_ops import find_files, mkdir, run, write_text
19
+
20
+ out = mkdir("build reports")
21
+ write_text(out / "summary.txt", "ready\n")
22
+ files = find_files(out, "*.txt")
23
+ result = run([sys.executable, "--version"], cwd=out, timeout=10)
24
+ print(files, result.stdout.strip())
25
+ ```
26
+
27
+ ```text
28
+ shellless-ops mkdir "build reports"
29
+ shellless-ops write "build reports/summary.txt" "ready"
30
+ shellless-ops copy "build reports/summary.txt" "build reports/backup.txt"
31
+ shellless-ops find "build reports" --pattern "*.txt"
32
+ shellless-ops read "build reports/summary.txt"
33
+ shellless-ops run --timeout 10 -- python --version
34
+ ```
35
+
36
+ `python -m shellless_ops` also works. A task runner with an argument-array API can use `["python", "-m", "shellless_ops", "find", "build reports", "--pattern", "*.txt"]`. A command typed into a terminal is still parsed by that terminal's shell; quote paths with spaces and wildcard patterns at that boundary.
37
+
38
+ ## Behavior
39
+
40
+ | API | Contract |
41
+ | --- | --- |
42
+ | `mkdir(path)` | Create missing parents, accept an existing directory and return its `Path`. |
43
+ | `read_text(path)` / `write_text(path, text)` | Default to UTF-8 and preserve line endings. Writing replaces existing contents, requires an existing parent directory and returns the `Path`. CLI `read` emits UTF-8 bytes. |
44
+ | `copy_file(source, target)` | Copy the contents to an exact destination and return its `Path`. Reject an existing destination. Metadata is not copied. An interrupted copy can leave a partial destination. |
45
+ | `find_files(root, pattern="*")` | Recursively match file basenames, including dotfiles, with case-sensitive glob matching. Return paths sorted by their `/`-separated relative names. Skip file symlinks and do not descend into directory symlinks or nested Windows directory reparse points. CLI `find` emits a JSON array of paths with `/` separators. |
46
+ | `run(argv, *, cwd=None, timeout=None, check=True, capture=True, encoding="utf-8")` | Pass the executable and each argument separately in a non-empty list or tuple. Return `subprocess.CompletedProcess`. By default, capture output as UTF-8 text and raise `CalledProcessError` on a nonzero exit. Set `encoding=None` for bytes or `capture=False` to inherit output. CLI `run` inherits output and propagates exit status; it uses 124 on timeout and `128 + signal` for signal exits on POSIX. |
47
+
48
+ `run` does not expand variables, implement pipelines or redirection, or support Windows `.bat` and `.cmd` entry points. It uses the operating system's executable lookup rules; pass an absolute executable path to select a specific installation. A timeout targets the directly launched process, not its entire process tree. Choose the executable and its options as trusted configuration: shell-free launching is not a sandbox for the program being run.
49
+
50
+ Run tests from the checkout after installing: `python -m unittest discover -s tests -v`.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "shellless-ops"
7
+ version = "0.1.0"
8
+ description = "Repeatable file and process operations without shell command strings"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Operating System :: MacOS",
16
+ "Operating System :: Microsoft :: Windows",
17
+ "Operating System :: POSIX :: Linux",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ "Topic :: Utilities",
21
+ ]
22
+
23
+ [project.urls]
24
+ Repository = "https://github.com/zhangs-cedar/shellless-ops"
25
+ Issues = "https://github.com/zhangs-cedar/shellless-ops/issues"
26
+
27
+ [project.scripts]
28
+ shellless-ops = "shellless_ops.__main__:main"
29
+
30
+ [tool.setuptools.packages.find]
31
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,73 @@
1
+ import os
2
+ import shutil
3
+ import stat
4
+ import subprocess
5
+ from fnmatch import fnmatchcase
6
+ from pathlib import Path
7
+
8
+ __all__ = ["copy_file", "find_files", "mkdir", "read_text", "run", "write_text"]
9
+
10
+
11
+ def mkdir(path):
12
+ path = Path(path)
13
+ path.mkdir(parents=True, exist_ok=True)
14
+ return path
15
+
16
+
17
+ def read_text(path, *, encoding="utf-8"):
18
+ with Path(path).open(encoding=encoding, newline="") as stream:
19
+ return stream.read()
20
+
21
+
22
+ def write_text(path, text, *, encoding="utf-8"):
23
+ path = Path(path)
24
+ with path.open("w", encoding=encoding, newline="") as stream:
25
+ stream.write(text)
26
+ return path
27
+
28
+
29
+ def copy_file(source, target):
30
+ """Copy file contents to a new path without overwriting."""
31
+ target = Path(target)
32
+ with Path(source).open("rb") as reader, target.open("xb") as writer:
33
+ shutil.copyfileobj(reader, writer)
34
+ return target
35
+
36
+
37
+ def find_files(root, pattern="*"):
38
+ """Match file basenames recursively without following directory links."""
39
+ root = Path(root)
40
+ files = []
41
+ pending = [root]
42
+ while pending:
43
+ with os.scandir(pending.pop()) as entries:
44
+ for entry in entries:
45
+ if entry.is_dir(follow_symlinks=False):
46
+ # Windows junctions are not always reported as symlinks.
47
+ if os.name == "nt" and (
48
+ entry.stat(follow_symlinks=False).st_file_attributes
49
+ & stat.FILE_ATTRIBUTE_REPARSE_POINT
50
+ ):
51
+ continue
52
+ pending.append(Path(entry.path))
53
+ elif fnmatchcase(entry.name, pattern) and entry.is_file(follow_symlinks=False):
54
+ files.append(Path(entry.path))
55
+ return sorted(files, key=lambda path: path.relative_to(root).as_posix())
56
+
57
+
58
+ def run(argv, *, cwd=None, timeout=None, check=True, capture=True, encoding="utf-8"):
59
+ if not isinstance(argv, (list, tuple)) or not argv:
60
+ raise TypeError("argv must be a non-empty list or tuple")
61
+ if os.name == "nt":
62
+ executable = os.fsdecode(argv[0]).rstrip(" .").lower()
63
+ if executable.endswith((".bat", ".cmd")):
64
+ raise ValueError("Windows batch files are not supported")
65
+ return subprocess.run(
66
+ argv,
67
+ cwd=cwd,
68
+ timeout=timeout,
69
+ check=check,
70
+ capture_output=capture,
71
+ encoding=encoding,
72
+ shell=False,
73
+ )
@@ -0,0 +1,60 @@
1
+ import argparse
2
+ import json
3
+ import subprocess
4
+ import sys
5
+
6
+ from . import copy_file, find_files, mkdir, read_text, run, write_text
7
+
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser(
11
+ prog="shellless-ops", description="Common file and process operations"
12
+ )
13
+ commands = parser.add_subparsers(dest="command", required=True)
14
+ commands.add_parser("mkdir", help="create a directory and its parents").add_argument("path")
15
+ commands.add_parser("read", help="read UTF-8 text").add_argument("path")
16
+ write = commands.add_parser("write", help="write UTF-8 text")
17
+ write.add_argument("path")
18
+ write.add_argument("text", help="use -- before the path if text starts with a dash")
19
+ copy = commands.add_parser("copy", help="copy a file without overwriting")
20
+ copy.add_argument("source")
21
+ copy.add_argument("target")
22
+ find = commands.add_parser("find", help="return matching file paths as JSON")
23
+ find.add_argument("root")
24
+ find.add_argument("--pattern", default="*")
25
+ execute = commands.add_parser("run", help="invoke an executable with separate arguments")
26
+ execute.add_argument("--cwd")
27
+ execute.add_argument("--timeout", type=float)
28
+ execute.add_argument("argv", nargs=argparse.REMAINDER)
29
+ args = parser.parse_args()
30
+ if args.command == "run":
31
+ if args.argv[:1] == ["--"]:
32
+ args.argv.pop(0)
33
+ if not args.argv:
34
+ execute.error("an executable is required")
35
+ try:
36
+ if args.command == "mkdir":
37
+ mkdir(args.path)
38
+ elif args.command == "read":
39
+ sys.stdout.buffer.write(read_text(args.path).encode("utf-8"))
40
+ elif args.command == "write":
41
+ write_text(args.path, args.text)
42
+ elif args.command == "copy":
43
+ copy_file(args.source, args.target)
44
+ elif args.command == "find":
45
+ print(json.dumps([path.as_posix() for path in find_files(args.root, args.pattern)]))
46
+ else:
47
+ result = run(
48
+ args.argv, cwd=args.cwd, timeout=args.timeout, check=False, capture=False
49
+ )
50
+ code = result.returncode
51
+ return 128 - code if code < 0 else code
52
+ except subprocess.TimeoutExpired as error:
53
+ parser.exit(124, f"{parser.prog}: {error}\n")
54
+ except (OSError, ValueError) as error:
55
+ parser.exit(1, f"{parser.prog}: {error}\n")
56
+ return 0
57
+
58
+
59
+ if __name__ == "__main__":
60
+ raise SystemExit(main())
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: shellless-ops
3
+ Version: 0.1.0
4
+ Summary: Repeatable file and process operations without shell command strings
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/zhangs-cedar/shellless-ops
7
+ Project-URL: Issues, https://github.com/zhangs-cedar/shellless-ops/issues
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Operating System :: MacOS
10
+ Classifier: Operating System :: Microsoft :: Windows
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # shellless-ops
21
+
22
+ Repeatable file and process operations without maintaining separate Bash and PowerShell scripts. Built for Python 3.11+ with no runtime dependencies. Use the Python API for scripts, or pass an argument array to the CLI from task runners.
23
+
24
+ ## Install
25
+
26
+ Before the first PyPI release, install from a local checkout:
27
+
28
+ ```text
29
+ python -m pip install .
30
+ ```
31
+
32
+ ## Example
33
+
34
+ ```python
35
+ import sys
36
+
37
+ from shellless_ops import find_files, mkdir, run, write_text
38
+
39
+ out = mkdir("build reports")
40
+ write_text(out / "summary.txt", "ready\n")
41
+ files = find_files(out, "*.txt")
42
+ result = run([sys.executable, "--version"], cwd=out, timeout=10)
43
+ print(files, result.stdout.strip())
44
+ ```
45
+
46
+ ```text
47
+ shellless-ops mkdir "build reports"
48
+ shellless-ops write "build reports/summary.txt" "ready"
49
+ shellless-ops copy "build reports/summary.txt" "build reports/backup.txt"
50
+ shellless-ops find "build reports" --pattern "*.txt"
51
+ shellless-ops read "build reports/summary.txt"
52
+ shellless-ops run --timeout 10 -- python --version
53
+ ```
54
+
55
+ `python -m shellless_ops` also works. A task runner with an argument-array API can use `["python", "-m", "shellless_ops", "find", "build reports", "--pattern", "*.txt"]`. A command typed into a terminal is still parsed by that terminal's shell; quote paths with spaces and wildcard patterns at that boundary.
56
+
57
+ ## Behavior
58
+
59
+ | API | Contract |
60
+ | --- | --- |
61
+ | `mkdir(path)` | Create missing parents, accept an existing directory and return its `Path`. |
62
+ | `read_text(path)` / `write_text(path, text)` | Default to UTF-8 and preserve line endings. Writing replaces existing contents, requires an existing parent directory and returns the `Path`. CLI `read` emits UTF-8 bytes. |
63
+ | `copy_file(source, target)` | Copy the contents to an exact destination and return its `Path`. Reject an existing destination. Metadata is not copied. An interrupted copy can leave a partial destination. |
64
+ | `find_files(root, pattern="*")` | Recursively match file basenames, including dotfiles, with case-sensitive glob matching. Return paths sorted by their `/`-separated relative names. Skip file symlinks and do not descend into directory symlinks or nested Windows directory reparse points. CLI `find` emits a JSON array of paths with `/` separators. |
65
+ | `run(argv, *, cwd=None, timeout=None, check=True, capture=True, encoding="utf-8")` | Pass the executable and each argument separately in a non-empty list or tuple. Return `subprocess.CompletedProcess`. By default, capture output as UTF-8 text and raise `CalledProcessError` on a nonzero exit. Set `encoding=None` for bytes or `capture=False` to inherit output. CLI `run` inherits output and propagates exit status; it uses 124 on timeout and `128 + signal` for signal exits on POSIX. |
66
+
67
+ `run` does not expand variables, implement pipelines or redirection, or support Windows `.bat` and `.cmd` entry points. It uses the operating system's executable lookup rules; pass an absolute executable path to select a specific installation. A timeout targets the directly launched process, not its entire process tree. Choose the executable and its options as trusted configuration: shell-free launching is not a sandbox for the program being run.
68
+
69
+ Run tests from the checkout after installing: `python -m unittest discover -s tests -v`.
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/shellless_ops/__init__.py
5
+ src/shellless_ops/__main__.py
6
+ src/shellless_ops.egg-info/PKG-INFO
7
+ src/shellless_ops.egg-info/SOURCES.txt
8
+ src/shellless_ops.egg-info/dependency_links.txt
9
+ src/shellless_ops.egg-info/entry_points.txt
10
+ src/shellless_ops.egg-info/top_level.txt
11
+ tests/test_shellless_ops.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ shellless-ops = shellless_ops.__main__:main
@@ -0,0 +1 @@
1
+ shellless_ops
@@ -0,0 +1,121 @@
1
+ import json
2
+ import os
3
+ import subprocess
4
+ import sys
5
+ import tempfile
6
+ import unittest
7
+ from pathlib import Path
8
+
9
+ from shellless_ops import copy_file, find_files, mkdir, read_text, run, write_text
10
+
11
+
12
+ class ShelllessOpsTests(unittest.TestCase):
13
+ def setUp(self):
14
+ directory = tempfile.TemporaryDirectory()
15
+ self.addCleanup(directory.cleanup)
16
+ self.root = Path(directory.name) / "测试 空格"
17
+
18
+ def cli(self, *args):
19
+ return subprocess.run(
20
+ [sys.executable, "-m", "shellless_ops", *args], capture_output=True, check=False
21
+ )
22
+
23
+ def test_cli_file_workflow(self):
24
+ source = self.root / "源 文档.txt"
25
+ target = self.root / "副本.txt"
26
+ text = "第一行\r\n第二行\n"
27
+ for args in [("mkdir", self.root), ("write", source, text), ("copy", source, target)]:
28
+ result = self.cli(*args)
29
+ self.assertEqual(result.returncode, 0, result.stderr)
30
+ result = self.cli("find", self.root, "--pattern", "*.txt")
31
+ self.assertEqual(result.returncode, 0, result.stderr)
32
+ self.assertEqual(json.loads(result.stdout), [target.as_posix(), source.as_posix()])
33
+ result = self.cli("read", target)
34
+ self.assertEqual(result.returncode, 0, result.stderr)
35
+ self.assertEqual(result.stdout, text.encode("utf-8"))
36
+
37
+ def test_search_distinguishes_missing_and_empty(self):
38
+ with self.assertRaises(FileNotFoundError):
39
+ find_files(self.root)
40
+ self.assertEqual(find_files(mkdir(self.root)), [])
41
+ lower = write_text(mkdir(self.root / "a") / "a.txt", "")
42
+ write_text(self.root / "b.TXT", "")
43
+ self.assertEqual(find_files(self.root, "*.txt"), [lower])
44
+
45
+ @unittest.skipIf(os.name == "nt", "symlink creation can require privileges on Windows")
46
+ def test_find_skips_symbolic_links(self):
47
+ mkdir(self.root)
48
+ file = write_text(self.root / "real.txt", "")
49
+ (self.root / "alias.txt").symlink_to(file)
50
+ (self.root / "loop").symlink_to(self.root, target_is_directory=True)
51
+ self.assertEqual(find_files(self.root, "*.txt"), [file])
52
+
53
+ @unittest.skipUnless(os.name == "nt", "Windows directory junction handling")
54
+ def test_find_skips_windows_directory_junction(self):
55
+ file = write_text(mkdir(self.root) / "real.txt", "")
56
+ target = mkdir(self.root.parent / "junction-target")
57
+ write_text(target / "outside.txt", "outside")
58
+ junction = self.root / "junction"
59
+ # Use fixed relative names so cmd never parses the temporary directory path.
60
+ result = subprocess.run(
61
+ ["cmd.exe", "/d", "/c", "mklink", "/j", "junction", r"..\junction-target"],
62
+ cwd=self.root,
63
+ capture_output=True,
64
+ check=False,
65
+ )
66
+ self.assertEqual(result.returncode, 0, (result.stdout, result.stderr))
67
+ self.addCleanup(junction.rmdir)
68
+ self.assertEqual(read_text(junction / "outside.txt"), "outside")
69
+ self.assertEqual(find_files(self.root, "*.txt"), [file])
70
+
71
+ def test_copy_does_not_overwrite(self):
72
+ mkdir(self.root)
73
+ source = write_text(self.root / "source", "abc\r\ndef\n")
74
+ target = write_text(self.root / "target", "keep")
75
+ self.assertEqual(read_text(source), "abc\r\ndef\n")
76
+ with self.assertRaises(FileExistsError):
77
+ copy_file(source, target)
78
+ self.assertEqual(read_text(target), "keep")
79
+
80
+ def test_run_passes_literal_args_and_cwd(self):
81
+ mkdir(self.root)
82
+ arguments = ['测试 空格 & | "quoted"', "", "ends with space and backslash \\", "--"]
83
+ code = (
84
+ "import json, pathlib, sys; "
85
+ "print(json.dumps([pathlib.Path.cwd().name, sys.argv[1:]]))"
86
+ )
87
+ command = [sys.executable, "-c", code, *arguments]
88
+ expected = [self.root.name, arguments]
89
+ self.assertEqual(json.loads(run(command, cwd=self.root).stdout), expected)
90
+ result = self.cli("run", "--cwd", self.root, "--", *command)
91
+ self.assertEqual(result.returncode, 0, result.stderr)
92
+ self.assertEqual(json.loads(result.stdout), expected)
93
+
94
+ def test_run_preserves_failure_and_cli_exit_code(self):
95
+ code = "import sys; print('output'); sys.stderr.write('diagnostic'); sys.exit(7)"
96
+ command = [sys.executable, "-c", code]
97
+ with self.assertRaises(subprocess.CalledProcessError) as failure:
98
+ run(command)
99
+ self.assertEqual(failure.exception.returncode, 7)
100
+ self.assertEqual(failure.exception.stdout, "output\n")
101
+ self.assertEqual(failure.exception.stderr, "diagnostic")
102
+ result = self.cli("run", "--", *command)
103
+ self.assertEqual(result.returncode, 7, result.stderr)
104
+ self.assertEqual(result.stdout.splitlines(), [b"output"])
105
+ self.assertEqual(result.stderr, b"diagnostic")
106
+
107
+ def test_run_timeout(self):
108
+ command = [sys.executable, "-c", "import time; time.sleep(10)"]
109
+ with self.assertRaises(subprocess.TimeoutExpired):
110
+ run(command, timeout=0.1)
111
+ result = self.cli("run", "--timeout", "0.1", "--", *command)
112
+ self.assertEqual(result.returncode, 124, result.stderr)
113
+
114
+ def test_run_rejects_command_strings(self):
115
+ with self.assertRaises(TypeError):
116
+ run("python -V")
117
+
118
+ @unittest.skipUnless(os.name == "nt", "Windows batch handling")
119
+ def test_run_rejects_windows_batch_files(self):
120
+ with self.assertRaises(ValueError):
121
+ run(["build.CMD", "argument"])