zipseal 0.3.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.
zipseal-0.3.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kgrizz-git
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.
zipseal-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: zipseal
3
+ Version: 0.3.0
4
+ Summary: Write files and folders into AES-256 zips, optionally split into self-contained parts under a size cap.
5
+ Author: kgrizz-git
6
+ Author-email: kgrizz-git <216068303+kgrizz-git@users.noreply.github.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: stream-zip>=0.0.84,<0.1
10
+ Requires-Dist: stream-unzip>=0.0.101,<0.1
11
+ Requires-Python: >=3.11
@@ -0,0 +1,54 @@
1
+ [project]
2
+ name = "zipseal"
3
+ version = "0.3.0"
4
+ description = "Write files and folders into AES-256 zips, optionally split into self-contained parts under a size cap."
5
+ requires-python = ">=3.11"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ dependencies = [
9
+ "stream-zip>=0.0.84,<0.1",
10
+ "stream-unzip>=0.0.101,<0.1",
11
+ ]
12
+
13
+ [[project.authors]]
14
+ name = "kgrizz-git"
15
+ email = "216068303+kgrizz-git@users.noreply.github.com"
16
+
17
+ [project.scripts]
18
+ zipseal = "zipseal.cli:main"
19
+ zipseal-gui = "zipseal.gui:main"
20
+
21
+ [dependency-groups]
22
+ dev = [
23
+ "pytest>=8",
24
+ "hypothesis>=6",
25
+ "basedpyright>=1.20",
26
+ "pyyaml>=6",
27
+ ]
28
+ build = [
29
+ "pyinstaller==6.22.3",
30
+ "pillow==13.0.0",
31
+ ]
32
+
33
+ [build-system]
34
+ requires = ["uv_build>=0.12.10,<0.14.0"]
35
+ build-backend = "uv_build"
36
+
37
+ [tool.pytest.ini_options]
38
+ testpaths = ["tests"]
39
+ pythonpath = ["tests"]
40
+ addopts = "-m 'not slow and not gui'"
41
+ markers = [
42
+ "slow: long-running tests (Zip64, huge entry counts). Run with -m slow.",
43
+ "sevenzip: needs the 7zz binary; skipped when it is missing.",
44
+ "gui: needs a real Tk display. Run with -m gui.",
45
+ ]
46
+
47
+ [tool.basedpyright]
48
+ typeCheckingMode = "standard"
49
+ include = [
50
+ "src",
51
+ "tests",
52
+ "packaging",
53
+ ]
54
+ pythonVersion = "3.11"
@@ -0,0 +1,49 @@
1
+ [project]
2
+ name = "zipseal"
3
+ version = "0.3.0"
4
+ description = "Write files and folders into AES-256 zips, optionally split into self-contained parts under a size cap."
5
+ authors = [
6
+ { name = "kgrizz-git", email = "216068303+kgrizz-git@users.noreply.github.com" }
7
+ ]
8
+ requires-python = ">=3.11"
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ dependencies = [
12
+ "stream-zip>=0.0.84,<0.1",
13
+ "stream-unzip>=0.0.101,<0.1",
14
+ ]
15
+
16
+ [project.scripts]
17
+ zipseal = "zipseal.cli:main"
18
+ zipseal-gui = "zipseal.gui:main"
19
+
20
+ [dependency-groups]
21
+ dev = [
22
+ "pytest>=8",
23
+ "hypothesis>=6",
24
+ "basedpyright>=1.20",
25
+ "pyyaml>=6",
26
+ ]
27
+ build = [
28
+ "pyinstaller==6.22.3",
29
+ "pillow==13.0.0",
30
+ ]
31
+
32
+ [build-system]
33
+ requires = ["uv_build>=0.12.10,<0.14.0"]
34
+ build-backend = "uv_build"
35
+
36
+ [tool.pytest.ini_options]
37
+ testpaths = ["tests"]
38
+ pythonpath = ["tests"]
39
+ addopts = "-m 'not slow and not gui'"
40
+ markers = [
41
+ "slow: long-running tests (Zip64, huge entry counts). Run with -m slow.",
42
+ "sevenzip: needs the 7zz binary; skipped when it is missing.",
43
+ "gui: needs a real Tk display. Run with -m gui.",
44
+ ]
45
+
46
+ [tool.basedpyright]
47
+ typeCheckingMode = "standard"
48
+ include = ["src", "tests", "packaging"]
49
+ pythonVersion = "3.11"
@@ -0,0 +1,3 @@
1
+ """zipseal: write files into AES-256 zips, optionally split under a size cap."""
2
+
3
+ __version__ = "0.3.0"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from zipseal.cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,251 @@
1
+ """Command-line entry point: argument parsing, password sources and exit codes.
2
+
3
+ This module is one front end on top of `job.run_job`, the core the CLI and the
4
+ GUI share. It turns argv into `Options` and points the core's `warn` sink at
5
+ stderr; it holds no archive logic.
6
+ """
7
+
8
+ import argparse
9
+ import sys
10
+ from collections.abc import Callable, Sequence
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import NoReturn, TextIO
14
+
15
+ from zipseal import __version__, passwords
16
+ from zipseal.errors import EXIT_INTERRUPT, EXIT_OK, UsageError, ZipsealError
17
+ from zipseal.job import run_job
18
+ from zipseal.options import DEFAULT_EXCLUDES, Options
19
+ from zipseal.passwords import Password
20
+ from zipseal.sizes import parse_size
21
+
22
+ EPILOG = """\
23
+ examples:
24
+ zipseal reports/ notes.txt -o bundle.zip --generate-password
25
+ zipseal reports/ -o bundle.zip --max-size 20MB # parts for email
26
+ zipseal reports/ -o bundle.zip --max-size 20MB --hide-names
27
+ zipseal reports/ -o bundle.zip --max-size 20MB --dry-run
28
+
29
+ passwords:
30
+ There is no option that takes the password itself, because it would end up
31
+ in shell history and the process list. Without a password option, zipseal
32
+ prompts twice. Send the password through a different channel than the zip.
33
+
34
+ output:
35
+ One part keeps the -o name. Several are named NAME-volumeNN-of-MM.zip, and
36
+ each one opens on its own. Existing files are never overwritten without
37
+ --force. Every part is verified before it gets its final name.
38
+
39
+ opening the archives:
40
+ Finder (macOS 11+), 7-Zip, Keka, or `tar -xf FILE` (prompts for the password).
41
+ macOS /usr/bin/unzip cannot open AES zips. With --hide-names, open the part
42
+ with the password, then open payload.zip inside it.
43
+
44
+ exit codes:
45
+ 0 success, 1 usage error, 2 input error (missing path, name collision,
46
+ file too large for --max-size), 3 write or verify failure, 130 interrupted.
47
+ """
48
+
49
+
50
+ class _Parser(argparse.ArgumentParser):
51
+ """Report usage errors with exit 1 (SPEC.md §4), not argparse's default 2."""
52
+
53
+ def error(self, message: str) -> NoReturn:
54
+ raise UsageError(message)
55
+
56
+
57
+ def _size(text: str) -> int:
58
+ try:
59
+ return parse_size(text)
60
+ except UsageError as exc:
61
+ raise argparse.ArgumentTypeError(str(exc)) from None
62
+
63
+
64
+ def build_parser() -> argparse.ArgumentParser:
65
+ parser = _Parser(
66
+ prog="zipseal",
67
+ description=(
68
+ "Write files and folders into AES-256 encrypted zips, optionally split "
69
+ "into self-contained parts that each stay under a size cap."
70
+ ),
71
+ epilog=EPILOG,
72
+ formatter_class=argparse.RawDescriptionHelpFormatter,
73
+ )
74
+ parser.add_argument("paths", metavar="PATH", nargs="+", type=Path, help="files or folders")
75
+ parser.add_argument(
76
+ "-o", "--output", required=True, type=Path, help="output name, such as bundle.zip"
77
+ )
78
+ parser.add_argument(
79
+ "--max-size",
80
+ type=_size,
81
+ metavar="SIZE",
82
+ help="cap per part: plain bytes, KB/MB/GB/TB (powers of 10) or KiB/MiB/GiB/TiB",
83
+ )
84
+
85
+ pw = parser.add_mutually_exclusive_group()
86
+ pw.add_argument(
87
+ "--password-prompt",
88
+ action="store_true",
89
+ help="prompt twice for the password (the default)",
90
+ )
91
+ pw.add_argument("--password-env", metavar="VAR", help="read the password from VAR")
92
+ pw.add_argument(
93
+ "--password-file", metavar="PATH", type=Path, help="read the first line of PATH"
94
+ )
95
+ pw.add_argument(
96
+ "--generate-password",
97
+ action="store_true",
98
+ help="generate a random password and print it once to stderr",
99
+ )
100
+
101
+ parser.add_argument(
102
+ "--level",
103
+ type=int,
104
+ choices=range(10),
105
+ default=6,
106
+ metavar="0-9",
107
+ help="deflate level (default 6; 0 = no compression)",
108
+ )
109
+ parser.add_argument(
110
+ "--exclude",
111
+ action="append",
112
+ default=[],
113
+ metavar="GLOB",
114
+ help="skip names matching GLOB (or archive paths, if GLOB has a /); repeatable",
115
+ )
116
+ parser.add_argument(
117
+ "--no-default-excludes",
118
+ action="store_true",
119
+ help=f"do not skip {', '.join(DEFAULT_EXCLUDES)}",
120
+ )
121
+ parser.add_argument(
122
+ "--follow-symlinks", action="store_true", help="follow symlinks instead of skipping them"
123
+ )
124
+ parser.add_argument(
125
+ "--order",
126
+ choices=("path", "size"),
127
+ default="path",
128
+ help="path keeps folders together (default); size packs into fewer parts",
129
+ )
130
+ parser.add_argument(
131
+ "--hide-names",
132
+ action="store_true",
133
+ help="hide file names, sizes and dates: each part holds one encrypted payload.zip",
134
+ )
135
+ parser.add_argument(
136
+ "--manifest", action="store_true", help="add MANIFEST.txt listing every part's files"
137
+ )
138
+ parser.add_argument(
139
+ "--no-verify",
140
+ action="store_true",
141
+ help="skip decrypting each part after writing (the size cap is still checked)",
142
+ )
143
+ parser.add_argument(
144
+ "--force",
145
+ action="store_true",
146
+ help="replace existing outputs; they are restored if the run fails",
147
+ )
148
+ parser.add_argument(
149
+ "--dry-run", action="store_true", help="show the planned parts and write nothing"
150
+ )
151
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
152
+ return parser
153
+
154
+
155
+ def get_password(args: argparse.Namespace) -> Password:
156
+ """Pick a password source (SPEC.md §4). Its strength is checked by the core."""
157
+ if args.generate_password:
158
+ return passwords.generate()
159
+ if args.password_env:
160
+ return passwords.from_env(args.password_env)
161
+ if args.password_file:
162
+ return passwords.from_file(args.password_file)
163
+ return passwords.from_prompt()
164
+
165
+
166
+ class _TtyProgress:
167
+ """The CLI's progress lines, as one `Progress` implementation.
168
+
169
+ `part_started` prints a line per part, and `verifying` prints one line before
170
+ decryption starts. The core skips `verifying` for a `--no-verify` run.
171
+ `bytes_written` is per chunk and would only add noise, so it is ignored.
172
+ """
173
+
174
+ def __init__(self, out: TextIO) -> None:
175
+ self.out = out
176
+
177
+ def part_started(self, number: int) -> None:
178
+ print(f"zipseal: writing part {number} ...", file=self.out, flush=True)
179
+
180
+ def bytes_written(self, written: int) -> None:
181
+ """The CLI reports finished parts, not bytes."""
182
+
183
+ def verifying(self, parts: int) -> None:
184
+ print(f"zipseal: verifying {parts} part(s) ...", file=self.out, flush=True)
185
+
186
+ def part_verified(self, number: int, size: int) -> None:
187
+ """The CLI announces verification once, before it starts."""
188
+
189
+
190
+ @dataclass(frozen=True)
191
+ class Command:
192
+ """One parsed command line: what to archive, and where the password comes from."""
193
+
194
+ options: Options
195
+ get_password: Callable[[Options], Password]
196
+
197
+
198
+ def options_from_args(args: argparse.Namespace) -> Options:
199
+ """Build the core's `Options` from argparse's namespace."""
200
+ return Options(
201
+ paths=list(args.paths),
202
+ output=args.output,
203
+ max_size=args.max_size,
204
+ level=args.level,
205
+ excludes=list(args.exclude),
206
+ default_excludes=not args.no_default_excludes,
207
+ follow_symlinks=args.follow_symlinks,
208
+ hide_names=args.hide_names,
209
+ order=args.order,
210
+ manifest=args.manifest,
211
+ no_verify=args.no_verify,
212
+ force=args.force,
213
+ dry_run=args.dry_run,
214
+ )
215
+
216
+
217
+ def parse_args(argv: Sequence[str] | None = None) -> Command:
218
+ """Parse argv into a `Command` for `run`."""
219
+ args = build_parser().parse_args(argv)
220
+ return Command(options_from_args(args), lambda _: get_password(args))
221
+
222
+
223
+ def run(command: Command) -> int:
224
+ """Run the parsed command line through the shared core, warnings to stderr."""
225
+ log = sys.stderr
226
+ progress = _TtyProgress(log) if log.isatty() else None
227
+ if progress is not None and not command.options.dry_run:
228
+ print(
229
+ "zipseal: press Ctrl-C to cancel. zipseal then removes its temporary files, "
230
+ "and warns about any it could not delete.",
231
+ file=log,
232
+ flush=True,
233
+ )
234
+ return run_job(
235
+ command.options,
236
+ command.get_password,
237
+ progress=progress,
238
+ warn=log,
239
+ password_out=log,
240
+ )
241
+
242
+
243
+ def main(argv: Sequence[str] | None = None) -> int:
244
+ try:
245
+ return run(parse_args(argv)) or EXIT_OK
246
+ except ZipsealError as exc:
247
+ print(f"zipseal: error: {exc}", file=sys.stderr)
248
+ return exc.exit_code
249
+ except KeyboardInterrupt:
250
+ print("zipseal: interrupted", file=sys.stderr)
251
+ return EXIT_INTERRUPT
@@ -0,0 +1,285 @@
1
+ """Walk the inputs into an ordered list of entries (SPEC.md §6.1, §6.5, §6.8).
2
+
3
+ Every input is opened through a descriptor for its parent folder, held for the
4
+ whole run. Each entry records the (device, inode) of every component between that
5
+ root and itself, so the writer can detect a file or folder swapped after collection.
6
+ """
7
+
8
+ import fnmatch
9
+ import os
10
+ import re
11
+ import stat
12
+ import sys
13
+ import unicodedata
14
+ from dataclasses import dataclass, field
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+ from typing import TextIO
18
+
19
+ from zipseal.errors import InputError
20
+ from zipseal.output import temp_name_re
21
+
22
+ DOS_MIN = datetime(1980, 1, 1, 0, 0, 0)
23
+ DOS_MAX = datetime(2107, 12, 31, 23, 59, 58)
24
+
25
+ Identity = tuple[int, int]
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class FileEntry:
30
+ root: int # index into Collection.roots
31
+ relparts: tuple[str, ...] # path from the root, as on disk
32
+ arcname: str # NFC, "/"-separated; directories end with "/"
33
+ size: int
34
+ mtime: datetime
35
+ mode: int # permission bits only
36
+ is_dir: bool
37
+ chain: tuple[Identity, ...] # identity of each component in relparts
38
+
39
+
40
+ @dataclass
41
+ class Collection:
42
+ roots: list[int] = field(default_factory=list) # open directory descriptors
43
+ entries: list[FileEntry] = field(default_factory=list)
44
+ follow_symlinks: bool = False
45
+
46
+ def close(self) -> None:
47
+ for fd in self.roots:
48
+ os.close(fd)
49
+ self.roots.clear()
50
+
51
+ def __enter__(self) -> "Collection":
52
+ return self
53
+
54
+ def __exit__(self, *exc: object) -> None:
55
+ self.close()
56
+
57
+
58
+ def _ident(st: os.stat_result) -> Identity:
59
+ return (st.st_dev, st.st_ino)
60
+
61
+
62
+ def _excluded(name: str, arcpath: str, patterns: list[str]) -> bool:
63
+ for pattern in patterns:
64
+ target = arcpath if "/" in pattern else name
65
+ if fnmatch.fnmatchcase(target, pattern):
66
+ return True
67
+ return False
68
+
69
+
70
+ def _clamp(st: os.stat_result, arcname: str, warn: TextIO) -> datetime:
71
+ try:
72
+ when = datetime.fromtimestamp(st.st_mtime)
73
+ except (OverflowError, OSError, ValueError):
74
+ when = DOS_MIN if st.st_mtime < 0 else DOS_MAX
75
+ if when < DOS_MIN or when > DOS_MAX:
76
+ clamped = DOS_MIN if when < DOS_MIN else DOS_MAX
77
+ print(
78
+ f"zipseal: warning: {arcname}: timestamp {when:%Y-%m-%d} is outside the zip "
79
+ f"range; stored as {clamped:%Y-%m-%d}",
80
+ file=warn,
81
+ )
82
+ return clamped
83
+ return when
84
+
85
+
86
+ class _OutputFilter:
87
+ """Recognise this run's own output files when the output sits inside an input."""
88
+
89
+ def __init__(self, output: Path) -> None:
90
+ out = Path(os.path.abspath(output))
91
+ self.name = out.name
92
+ stem, suffix = out.stem, out.suffix
93
+ self.part_re = re.compile(
94
+ re.escape(stem) + r"-(?:volume|part)\d+-of-\d+" + re.escape(suffix)
95
+ )
96
+ self.temp_re = temp_name_re(stem, suffix)
97
+ try:
98
+ self.dir_ident: Identity | None = _ident(os.stat(out.parent))
99
+ except OSError:
100
+ self.dir_ident = None
101
+
102
+ def skip(self, dir_ident: Identity, name: str) -> bool:
103
+ if dir_ident != self.dir_ident:
104
+ return False
105
+ return (
106
+ name == self.name
107
+ or self.part_re.fullmatch(name) is not None
108
+ or self.temp_re.fullmatch(name) is not None
109
+ )
110
+
111
+
112
+ class _Walker:
113
+ def __init__(self, excludes: list[str], follow: bool, output: Path, warn: TextIO) -> None:
114
+ self.excludes = excludes
115
+ self.follow = follow
116
+ self.output = _OutputFilter(output)
117
+ self.warn = warn
118
+ self.collection = Collection(follow_symlinks=follow)
119
+ self.undecodable: list[str] = []
120
+
121
+ def _warn(self, message: str) -> None:
122
+ print(f"zipseal: warning: {message}", file=self.warn)
123
+
124
+ def _arcname(self, parts: tuple[str, ...], is_dir: bool) -> str | None:
125
+ try:
126
+ for part in parts:
127
+ part.encode("utf-8")
128
+ except UnicodeEncodeError:
129
+ self.undecodable.append(os.fsencode("/".join(parts)).decode("utf-8", "replace"))
130
+ return None
131
+ name = unicodedata.normalize("NFC", "/".join(parts))
132
+ return name + "/" if is_dir else name
133
+
134
+ def _add(
135
+ self,
136
+ root: int,
137
+ parts: tuple[str, ...],
138
+ st: os.stat_result,
139
+ chain: tuple[Identity, ...],
140
+ ) -> None:
141
+ is_dir = stat.S_ISDIR(st.st_mode)
142
+ arcname = self._arcname(parts, is_dir)
143
+ if arcname is None:
144
+ return
145
+ self.collection.entries.append(
146
+ FileEntry(
147
+ root=root,
148
+ relparts=parts,
149
+ arcname=arcname,
150
+ size=0 if is_dir else st.st_size,
151
+ mtime=_clamp(st, arcname, self.warn),
152
+ mode=stat.S_IMODE(st.st_mode),
153
+ is_dir=is_dir,
154
+ chain=chain,
155
+ )
156
+ )
157
+
158
+ def _classify(self, st: os.stat_result, display: str) -> str | None:
159
+ """Return "dir", "file", or None (skipped with a warning)."""
160
+ if stat.S_ISLNK(st.st_mode):
161
+ self._warn(f"{display}: skipping symlink (use --follow-symlinks to follow)")
162
+ return None
163
+ if stat.S_ISDIR(st.st_mode):
164
+ return "dir"
165
+ if stat.S_ISREG(st.st_mode):
166
+ return "file"
167
+ self._warn(f"{display}: skipping special file (socket, FIFO or device)")
168
+ return None
169
+
170
+ def add_input(self, path: Path) -> None:
171
+ absolute = Path(os.path.abspath(path))
172
+ name = absolute.name
173
+ if not name:
174
+ raise InputError(f"{path}: cannot archive a filesystem root")
175
+ try:
176
+ parent_fd = os.open(absolute.parent, os.O_RDONLY | os.O_DIRECTORY)
177
+ except OSError as exc:
178
+ raise InputError(f"{path}: {exc.strerror}") from None
179
+ root = len(self.collection.roots)
180
+ self.collection.roots.append(parent_fd)
181
+ try:
182
+ st = os.stat(name, dir_fd=parent_fd, follow_symlinks=self.follow)
183
+ except FileNotFoundError:
184
+ raise InputError(f"{path}: no such file or folder") from None
185
+ except OSError as exc:
186
+ raise InputError(f"{path}: {exc.strerror}") from None
187
+ kind = self._classify(st, str(path))
188
+ if kind == "file":
189
+ if not _excluded(name, name, self.excludes):
190
+ self._add(root, (name,), st, (_ident(st),))
191
+ elif kind == "dir":
192
+ self._walk_dir(root, name, st)
193
+
194
+ def _walk_dir(self, root: int, top: str, top_st: os.stat_result) -> None:
195
+ parent_fd = self.collection.roots[root]
196
+ chains: dict[str, tuple[Identity, ...]] = {top: (_ident(top_st),)}
197
+ dir_stats: dict[str, os.stat_result] = {top: top_st}
198
+ has_children: set[str] = set()
199
+ walk = os.fwalk(top, dir_fd=parent_fd, follow_symlinks=self.follow)
200
+ for dirpath, dirnames, filenames, dirfd in walk:
201
+ chain = chains[dirpath]
202
+ here = _ident(os.fstat(dirfd))
203
+ keep_dirs: list[str] = []
204
+ for name in sorted(dirnames + filenames):
205
+ parts = (*dirpath.split("/"), name)
206
+ arcpath = "/".join(parts)
207
+ display = arcpath
208
+ if self.output.skip(here, name):
209
+ continue
210
+ if _excluded(name, arcpath, self.excludes):
211
+ continue
212
+ try:
213
+ st = os.stat(name, dir_fd=dirfd, follow_symlinks=self.follow)
214
+ except OSError as exc:
215
+ self._warn(f"{display}: skipping ({exc.strerror})")
216
+ continue
217
+ kind = self._classify(st, display)
218
+ if kind is None:
219
+ continue
220
+ child_chain = (*chain, _ident(st))
221
+ has_children.add(dirpath)
222
+ if kind == "dir":
223
+ if _ident(st) in chain:
224
+ raise InputError(f"{display}: symlink cycle back to a parent folder")
225
+ chains[arcpath] = child_chain
226
+ dir_stats[arcpath] = st
227
+ keep_dirs.append(name)
228
+ else:
229
+ self._add(root, parts, st, child_chain)
230
+ dirnames[:] = [d for d in dirnames if d in keep_dirs]
231
+ # Store folders with nothing collected under them as directory entries.
232
+ for dirpath, chain in chains.items():
233
+ if dirpath not in has_children:
234
+ self._add(root, tuple(dirpath.split("/")), dir_stats[dirpath], chain)
235
+
236
+
237
+ def _check_collisions(entries: list[FileEntry]) -> None:
238
+ """Fail on paths that would clash when extracted, including on case-insensitive disks:
239
+ the same path twice, paths differing only in case, and a file whose name is also a
240
+ folder on another entry's path."""
241
+ folded: dict[str, list[FileEntry]] = {}
242
+ for entry in entries:
243
+ folded.setdefault(entry.arcname.casefold(), []).append(entry)
244
+ lines = []
245
+ for group in folded.values():
246
+ if len(group) > 1:
247
+ names = sorted({e.arcname for e in group})
248
+ kind = "same path" if len(names) == 1 else "differ only in case"
249
+ lines.append(f" {', '.join(names)} ({kind}, {len(group)} sources)")
250
+ files = {e.arcname.casefold(): e.arcname for e in entries if not e.is_dir}
251
+ for entry in entries:
252
+ parts = entry.arcname.rstrip("/").split("/")
253
+ for depth in range(1, len(parts)):
254
+ ancestor = "/".join(parts[:depth]).casefold()
255
+ if ancestor in files:
256
+ lines.append(
257
+ f" {files[ancestor]}, {entry.arcname} (a file and a folder share a name)"
258
+ )
259
+ break
260
+ if lines:
261
+ raise InputError("archive path collisions:\n" + "\n".join(lines))
262
+
263
+
264
+ def collect(
265
+ paths: list[Path],
266
+ *,
267
+ excludes: list[str],
268
+ follow_symlinks: bool,
269
+ output: Path,
270
+ warn: TextIO | None = None,
271
+ ) -> Collection:
272
+ """Walk every input. The caller must close() the result (or use `with`)."""
273
+ walker = _Walker(excludes, follow_symlinks, output, warn or sys.stderr)
274
+ try:
275
+ for path in paths:
276
+ walker.add_input(path)
277
+ if walker.undecodable:
278
+ listing = "\n".join(f" {p}" for p in walker.undecodable)
279
+ raise InputError(f"file names that are not valid UTF-8:\n{listing}")
280
+ walker.collection.entries.sort(key=lambda e: e.arcname)
281
+ _check_collisions(walker.collection.entries)
282
+ except BaseException:
283
+ walker.collection.close()
284
+ raise
285
+ return walker.collection