File size: 26,260 Bytes
196f3aa
cc02077
196f3aa
cc02077
eb1f478
 
 
 
cc02077
 
eb1f478
196f3aa
 
 
cc02077
 
196f3aa
 
 
 
 
 
 
 
 
cc02077
 
 
196f3aa
 
 
 
 
 
 
 
eb1f478
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec5da4b
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc02077
 
 
 
 
 
196f3aa
 
 
cc02077
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc02077
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
"""Lay out a batch fetched with fetch.py as a task pool: one folder per domain and source, the unit files under
their paths, a README.md and a LICENSE per source, and _meta/ with manifest.jsonl, sizes.tsv and delivery.json.

fetch.py itself writes the files in its own layout (<domain>/<source>/<unit folder>/..., _meta/manifest.jsonl
and _meta/sizes.tsv) and writes each unit as recorded: a unit stored inside another file (transform steps such as
unzip:<member>) is made out of the downloaded file and checked against the unit's recorded sha256 there. So most
selections need no second step. This script does only what fetch.py does not: it unpacks units marked expand into
folders, measures the decompressed size of single-file compressed units, checks that every source has its README.md
and LICENSE, writes _meta/delivery.json and the pool layout (files at their pool paths, as the pool builder does),
and extracts units (transform) from the output of fetch.py versions that delivered them as
fetched. It needs unpack.py, archive_formats.py, archive_formats.tsv and transform.py from tools/ next to it.

Input is the --out folder of a fetch.py run over a collection tag (campaign:<name>): its _meta/fetch_manifest.jsonl
and _meta/fetch_run.json (fetch_manifest.jsonl and fetch_run.json at the top of the folder for output of fetch.py
before the layout). The rows of such a collection carry their place in the pool (pool_domain, pool_path,
unit_group, pool_fields and the others fetch.py copies into the manifest). Every row must have been
fetched (status ok); otherwise nothing is written.

Layout of <out>/<name>/:

  <domain>/<source>/<path>                 a unit file (the path as given by the selection)
  <domain>/<source>/<package folder>/...   files written for a package (such as its README.md or a run
                                           script), listed with their full text in authored_files on the
                                           first manifest line of the package
  <domain>/<source>/README.md, LICENSE     one each per source
  _meta/manifest.jsonl                     one line per unit file (a row with pool_fields): source, path, url,
                                           sha256, bytes, spdx, licence_url, publisher, origin_kind, retrieved,
                                           and the other fields recorded for the unit (agency for works of a
                                           government agency, need, package, ...)
  _meta/sizes.tsv                          one line per source, no header: leaf, source, origin, bytes of the
                                           source folder, license, license tier
  _meta/delivery.json                      repository, revision, fetch.py arguments and row count of the run;
                                           local paths in the arguments are written as placeholders (<data>,
                                           <out>, <temp-dir>, <path>), so the file is the same on any machine

A unit with transform steps (unzip:<member>, untar:<member>, bunzip2, gunzip, unxz, unxxd, uudecode, uncompress,
gzip) is extracted by fetch.py (its fetch manifest line says extracted) and is copied here, checked against the
sha256 of that line. Output of an older fetch.py holds the upstream original instead; it is extracted here with
transform.py (only the named member, at most
256,000,000 bytes out of unxz, untar, unxxd, uudecode and uncompress) and checked against the index: its sha256, or
when the last step is gzip (whose bytes depend on the zlib build) the sha256 of the bytes before that step
(content_sha256).
Its manifest line keeps transform, upstream_sha256, upstream_bytes and content_sha256, so the unit can be checked
again by downloading the upstream original and extracting it the same way. A row marked
rolling may differ from the index; the manifest then keeps the bytes, sha256 and date actually downloaded and
sets differs_from_index.

A unit that is one compressed file (.gz, .bz2, .xz, .zst around a single file; not .tar.gz and the like) is
delivered as it is; its manifest line gets compression and decompressed_bytes, measured by decompressing it as a
stream and counting the bytes, without writing the decompressed file. If that measurement fails (damaged data, a
different format, a tar inside, no zstd decoder before Python 3.14), the build stops and names the unit and the
reason.

The result counts the units by how fetch.py obtained them (obtained: reused or staged from a local file whose
sha256 matched, fetched, already_present); the pool manifest does not carry this.

A unit marked expand is also unpacked into <domain>/<source>/_expanded/<unit path>/, and its manifest line gets
expanded: "_expanded/<unit path>" and expand_rule, the rule that marked it. The rule and the unpacking live in
unpack.py, shared with the pool builder: a unit is marked when the format table (archive_formats.tsv)
classes it as a multi-member archive meant to be used as a folder (zip, tar and its compressed forms, 7z, rar);
single-file compression and zip-based containers (xlsx, npz, docx and the like) are files. The pool format's limits
apply and are counted while unpacking, which stops at the first excess: every file and every unpacked folder is at
most 20,000,000 bytes, and a source holds at most 400,000 files across all its archives. An archive that cannot be
unpacked (unsafe member path, link or special member, nested archive, a format unpack.py cannot unpack, over a
limit) is not unpacked: its manifest line gets expand_failed with the reason, the result lists it, and the archive
itself stays in the pool as a file unit.

Uses the Python standard library only (measuring a .zst unit needs Python 3.14 or later).

Example:

  python tools/fetch.py --tag campaign:<name> --all --revision <commit> --out ./fetched
  python tools/to_pool.py ./fetched --out ./pools --name <name>

Deletes: a unit copied from the fetch output whose sha256 differs from its fetch manifest line (place): a
  byte-identical copy exists, the fetched file under the fetch folder it was copied from.
Deletes: a unit extracted with transform.py whose sha256 differs from the index (place): recomputable, by
  transform.apply from the fetched upstream file under the fetch folder.
"""

from __future__ import annotations

import argparse
import bz2
import gzip
import hashlib
import importlib
import json
import lzma
import os
import posixpath
import re
import shutil
import sys
from pathlib import Path

try:
    from . import public_transform as transform
except ImportError:
    try:
        import transform
    except ImportError:
        import public_transform as transform

try:  # the shipped tools/ folder holds unpack.py, archive_formats.py and archive_formats.tsv next to this file
    from . import unpack
    from .facts import archive_formats as AF
except ImportError:
    import unpack
    import archive_formats as AF

MANIFEST = "fetch_manifest.jsonl"
RUN_FILE = "fetch_run.json"
META = "_meta"
NAME = re.compile(r"^[a-z0-9._-]+$")
TAG_PREFIX = "campaign:"
EXPANDED = "_expanded"
# the pool format's limits: a file or directory unit is at most 20,000,000 bytes
# (max_unit_bytes); a source holds at most 400,000 files
MAX_UNIT_BYTES = unpack.MAX_UNIT_BYTES
MAX_SOURCE_FILES = unpack.MAX_SOURCE_FILES


class PoolError(ValueError):
    pass


# fetch.py records its arguments as given, so --data and --out hold paths of the machine that ran it (its home
# folder, its working folders). delivery.json travels with the pool: kept as is, it would show the paths of the
# machine that built it, and on another machine the same field would record that machine's paths. Local paths are
# therefore written as fixed placeholders; what a reader needs (revision, tags, filters, which options were given) stays as it was.
PATH_OPTIONS = {"--data": "<data>", "--out": "<out>", "--temp-dir": "<temp-dir>"}
PATH_PLACEHOLDER = "<path>"
_URL = re.compile(r"^[a-z][a-z0-9+.-]*://", re.I)
_ABS = re.compile(r"^(/|~|\\\\|[a-z]:[\\/])", re.I)


def _homes() -> list:
    out = []
    for h in (os.path.expanduser("~"), os.environ.get("HOME"), os.environ.get("USERPROFILE")):
        if h and len(h) > 1 and h not in out:
            out.append(h)
    return out


def _local_path(value: str, homes: list) -> bool:
    if _URL.match(value):
        return False
    return bool(_ABS.match(value)) or any(h in value for h in homes)


def portable_fetch_args(args) -> list | None:
    """fetch.py arguments with every local path replaced by a fixed placeholder (URLs are kept)."""
    if args is None:
        return None
    homes, out, pending = _homes(), [], None
    for a in args:
        a = str(a)
        if pending is not None:
            out.append(a if _URL.match(a) else pending)
            pending = None
            continue
        opt, eq, val = a.partition("=")
        if opt in PATH_OPTIONS:
            if eq:
                out.append(f"{opt}={val if _URL.match(val) else PATH_OPTIONS[opt]}")
            else:
                out.append(a)
                pending = PATH_OPTIONS[opt]
            continue
        if eq and opt.startswith("--") and _local_path(val, homes):
            out.append(f"{opt}={PATH_PLACEHOLDER}")
        elif _local_path(a, homes):
            out.append(PATH_PLACEHOLDER)
        else:
            out.append(a)
    return out


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def safe_rel(rel) -> str:
    """A relative path inside the pool: no absolute path, no empty, '.' or '..' part, no backslash."""
    if not isinstance(rel, str) or not rel or rel.startswith("/") or "\\" in rel:
        raise PoolError(f"unsafe path: {rel!r}")
    parts = rel.split("/")
    if any(p in ("", ".", "..") for p in parts):
        raise PoolError(f"unsafe path: {rel!r}")
    return posixpath.join(*parts)


def safe_name(name, what: str) -> str:
    if not isinstance(name, str) or not name or "/" in name or "\\" in name or name in (".", ".."):
        raise PoolError(f"unsafe {what}: {name!r}")
    return name


def read_jsonl(path: Path) -> list:
    with open(path, encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def campaign_rows(lines: list, campaign: str | None) -> tuple:
    """-> (collection name, its manifest lines). Lines without a collection are ignored; more than one collection
    needs campaign."""
    names = sorted({x["campaign"] for x in lines if x.get("campaign")})
    if campaign is not None:
        if campaign.startswith(TAG_PREFIX):
            campaign = campaign[len(TAG_PREFIX):]
        if campaign not in names:
            raise PoolError(f"no row of collection {campaign!r} in the manifest (found: {', '.join(names) or 'none'})")
    elif len(names) == 1:
        campaign = names[0]
    elif not names:
        raise PoolError("no row of the manifest belongs to a collection (fetch with --tag campaign:<name>)")
    else:
        raise PoolError(f"the manifest holds several collections ({', '.join(names)}); choose one with --campaign")
    return campaign, [x for x in lines if x.get("campaign") == campaign]


def fetched_file(fetch_dir: Path, x: dict) -> Path:
    """The downloaded file of a manifest row, looked up under the fetch output folder only (never the current
    directory): an absolute path is used when it lies inside that folder; a relative path is tried as given under
    the folder and from its <source>/<collection> part on (fetch.py records the --out it was given, which may have
    been relative to another directory); last, <source>/<collection>/<pool_path> under the folder."""
    root = fetch_dir.resolve()
    source, coll = x.get("source"), x.get("collection") or x.get("campaign")
    cands = []
    if x.get("layout_path"):  # where fetch.py put it in its layout, relative to its --out
        cands.append(root.joinpath(*safe_rel(x["layout_path"]).split("/")))
    if x.get("path"):
        p = Path(x["path"])
        if p.is_absolute():
            if p.resolve().is_relative_to(root):
                cands.append(p)
        else:
            parts = [q for q in p.parts if q not in ("", ".")]
            if parts and ".." not in parts:
                cands.append(root.joinpath(*parts))
                cands += [root.joinpath(*parts[i:]) for i in range(1, len(parts) - 1)
                          if parts[i] == source and parts[i + 1] == coll]
    for c in cands:
        if c.is_file():
            return c
    c = root.joinpath(safe_name(source, "source"), safe_name(coll, "collection"),
                      *safe_rel(x.get("pool_path")).split("/"))
    if c.is_file():
        return c
    raise PoolError(f"{x.get('source')} {x.get('pool_path')}: downloaded file not found under {fetch_dir}")


def check_rows(rows: list) -> None:
    bad = [x for x in rows if x.get("status") != "ok"]
    if bad:
        shown = "; ".join(f"{x.get('source')} {x.get('pool_path')}: {x.get('status')} {x.get('reason') or ''}".strip()
                          for x in bad[:10])
        raise PoolError(f"{len(bad)} row(s) were not fetched, nothing written ({shown})")
    for x in rows:
        for k in ("pool_domain", "pool_path", "pool_source"):
            if x.get(k) in (None, ""):
                raise PoolError(f"{x.get('source')} {x.get('pool_path')}: field {k} missing")
    seen = set()
    for x in rows:
        key = (x["pool_domain"], x["source"], x["pool_path"])
        if key in seen:
            raise PoolError(f"two rows for {'/'.join(key)}")
        seen.add(key)


def place(fetch_dir: Path, x: dict, dest: Path) -> dict:
    """Copy (or extract) one fetched row to dest. -> {sha256, bytes}, plus content_sha256 for an extracted unit."""
    src = fetched_file(fetch_dir, x)
    dest.parent.mkdir(parents=True, exist_ok=True)
    if x.get("transform") is not None and x.get("extracted"):
        # fetch.py already made the unit and checked it against the index: copy it, checked against its line
        shutil.copyfile(src, dest)
        sha = sha256_file(dest)
        if sha != x.get("sha256"):
            dest.unlink(missing_ok=True)
            raise PoolError(f"{x['source']} {x['pool_path']}: sha256 {sha} differs from the fetch manifest "
                            f"({x.get('sha256')})")
        return {"sha256": sha, "bytes": dest.stat().st_size, "content_sha256": x.get("content_sha256") or sha}
    if x.get("transform") is not None:
        got = transform.apply(src, x["transform"], dest)
        want, want_c = x.get("unit_sha256"), x.get("content_sha256")
        # gzip output depends on the zlib build: the bytes before a final gzip step decide
        same = got["sha256"] == want or (want_c is not None and got["content_sha256"] == want_c)
        if (want or want_c) and not same:
            dest.unlink(missing_ok=True)
            raise PoolError(f"{x['source']} {x['pool_path']}: extracted sha256 {got['sha256']} differs from the "
                            f"index ({want})")
        return {"sha256": got["sha256"], "bytes": got["bytes"], "content_sha256": got["content_sha256"]}
    shutil.copyfile(src, dest)
    return {"sha256": sha256_file(dest), "bytes": dest.stat().st_size}


def unit_line(x: dict, got: dict, date: str) -> dict:
    """The manifest line of a unit: the recorded fields in their order, with sha256, bytes, retrieved and
    fetched_from from this run. An extracted unit also keeps its transform steps, the sha256 and size of the
    upstream original and content_sha256 (the bytes before a final gzip step), which a later check needs to
    download the original again and extract it the same way."""
    m = {}
    for k, v in x["pool_fields"]:
        m[k] = v
    m["sha256"], m["bytes"] = got["sha256"], got["bytes"]
    m["retrieved"] = x.get("retrieved") or date
    if x.get("url"):
        m["fetched_from"] = x["url"]
    else:
        m.pop("fetched_from", None)
    if x.get("transform") is not None:
        m["transform"] = list(x["transform"])
        for k in ("upstream_sha256", "upstream_bytes"):
            if x.get(k) is not None:
                m[k] = x[k]
        m["content_sha256"] = got["content_sha256"]
    if x.get("differs_from_index"):
        m["differs_from_index"] = True
        m["expected_bytes"] = x.get("expected_bytes")
        m["expected_sha256"] = x.get("expected_sha256")
    return m


# A unit that is one file stored compressed (gzip, bzip2, xz, zstd around a single file) is delivered as it is. Its
# manifest line gets compression and decompressed_bytes, measured here by decompressing it as a stream and counting
# the bytes (nothing is written), so the delivery notes can say how much space each needs once decompressed. A tar
# inside (.tar.gz and the like) is an archive of several files, not one file, and is not counted here.
# Which units are single-file compression is decided by the format table (archive_formats.tsv, class
# single_file_compression), read through archive_formats.place; the table's tar forms (.tar.gz and the like) are
# multi-member archives and are not counted here. DECODERS names the decoder per table format; a table format with
# no decoder here (lz4, Z) is not measured.
DECODERS = {"gz": "gzip", "bz2": "bzip2", "xz": "xz", "zst": "zstd"}
COMPRESSED_MAGIC = {DECODERS[f]: AF.FORMATS[f].magic for f in DECODERS}
_CHUNK = 1 << 20


class MeasureError(ValueError):
    pass


def single_file_compression(name: str) -> str | None:
    """The compression format of a unit that is one compressed file, judged by its name through the format table;
    None for anything else."""
    pl = AF.place(str(name))
    return DECODERS.get(pl.format) if pl.cls == AF.COMPRESSION else None


def _zstd_reader(f, zstd_opener=None):
    try:
        zstd = importlib.import_module("compression.zstd")  # in the standard library from Python 3.14
    except ImportError:
        if zstd_opener is None:
            raise MeasureError("no zstd decoder in this Python (the standard library has one from Python 3.14)") \
                from None
        return zstd_opener(f)
    return zstd.ZstdFile(f)


def decompressed_size(path, fmt: str, zstd_opener=None) -> int:
    """Decompress the file at path as a stream and count the bytes; nothing is written. Raises MeasureError with
    the reason when the file is not that format, is damaged or truncated, or holds a tar archive."""
    path = Path(path)
    try:
        with open(path, "rb") as raw:
            head = raw.read(len(COMPRESSED_MAGIC[fmt]))
            if head != COMPRESSED_MAGIC[fmt]:
                raise MeasureError(f"not a {fmt} file (it starts with {head.hex() or 'nothing'})")
            raw.seek(0)
            opener = {"gzip": gzip.GzipFile, "bzip2": bz2.BZ2File, "xz": lzma.LZMAFile}.get(fmt)
            f = opener(fileobj=raw) if fmt == "gzip" else opener(raw) if opener else _zstd_reader(raw, zstd_opener)
            n, first = 0, b""
            with f:
                while True:
                    b = f.read(_CHUNK)
                    if not b:
                        break
                    if len(first) < 512:
                        first += b[:512 - len(first)]
                    n += len(b)
    except MeasureError:
        raise
    except Exception as e:  # damaged or truncated data: zlib, lzma, bz2, zstd and EOF errors all end up here
        raise MeasureError(f"cannot decompress: {type(e).__name__}: {e}") from None
    if first[257:262] == b"ustar":
        raise MeasureError(f"the {fmt} file holds a tar archive, not a single file")
    return n


def measure_compressed(path, name: str, zstd_opener=None) -> dict | None:
    """-> {"compression", "decompressed_bytes"} for a unit that is one compressed file, None for any other unit.
    zstd_opener (a function from a binary file to a readable stream) is used for .zst when this Python has no zstd
    decoder of its own."""
    fmt = single_file_compression(name)
    if fmt is None:
        return None
    return {"compression": fmt, "decompressed_bytes": decompressed_size(path, fmt, zstd_opener)}


def is_unit_file(x: dict) -> bool:
    """#1633: a unit's own file, the row whose pool_fields hold its line of the pool manifest; the other rows are files
    the index wrote (a package's README.md, the source's README.md and LICENSE)."""
    return isinstance(x.get("pool_fields"), list)


def order_key(x: dict) -> tuple:
    src = (x.get("pool_source") or {}).get("order", 0)
    o = x.get("pool_order") or [src, -1]
    return (src, o[1] if x.get("unit_group") else 1 << 30, not is_unit_file(x), x["pool_path"])


def build(fetch_dir, out, name: str, *, campaign: str | None = None, max_unit_bytes: int = MAX_UNIT_BYTES,
          max_source_files: int = MAX_SOURCE_FILES) -> dict:
    fetch_dir = Path(fetch_dir)
    if not NAME.match(name or ""):
        raise PoolError(f"batch folder name may only use lowercase letters, digits and . _ -: {name!r}")
    run_p, man_p = fetch_dir / META / RUN_FILE, fetch_dir / META / MANIFEST
    if not run_p.is_file() or not man_p.is_file():
        run_p, man_p = fetch_dir / RUN_FILE, fetch_dir / MANIFEST
    if not run_p.is_file() or not man_p.is_file():
        raise PoolError(f"{fetch_dir} is not a fetch.py output folder ({META}/{RUN_FILE} and {META}/{MANIFEST} are "
                        f"needed)")
    run = json.loads(run_p.read_text(encoding="utf-8"))
    campaign, rows = campaign_rows(read_jsonl(man_p), campaign)
    check_rows(rows)
    root = Path(out) / name
    if root.exists() and any(root.iterdir()):
        raise PoolError(f"{root} exists and is not empty")
    date = run.get("date")
    rows = sorted(rows, key=order_key)
    manifest, sources, expands, obtained = [], {}, [], {}
    for x in rows:
        domain = safe_name(x["pool_domain"], "domain")
        source = safe_name(x["source"], "source")
        rel = safe_rel(x["pool_path"])
        dest = root.joinpath(domain, source, *rel.split("/"))
        got = place(fetch_dir, x, dest)
        sources.setdefault((domain, source), x["pool_source"])
        if is_unit_file(x):
            how = x.get("obtained") or ("already_present" if x.get("already_present") else "not_recorded")
            obtained[how] = obtained.get(how, 0) + 1
            line = unit_line(x, got, date)
            try:
                measured = measure_compressed(dest, rel)
            except MeasureError as e:
                raise PoolError(f"{source} {rel}: decompressed size not measured, the build stops for this unit: {e}")
            if measured:
                line.update(measured)
            manifest.append(line)
            if x.get("expand"):
                expands.append((domain, source, rel, dest, manifest[-1], x.get("expand_rule")))
    expand_failed, counts = [], {}
    for domain, source, rel, dest, m, rule in expands:
        sd = root / domain / source
        if (domain, source) not in counts:  # one count per source, shared by all its archives
            counts[(domain, source)] = unpack.SourceFiles.of_dir(sd, max_source_files)
        r = unpack.expand(dest, sd.joinpath(EXPANDED, *rel.split("/")), files=counts[(domain, source)],
                          max_bytes=max_unit_bytes)
        m["expand_rule"] = rule or unpack.EXPAND_RULE
        if r["status"] != "ok":
            m["expand_failed"] = r["reason"]
            expand_failed.append({"source": source, "path": rel, "reason": r["reason"]})
        else:
            m["expanded"] = f"{EXPANDED}/{rel}"
    sizes = []
    for (domain, source), ps in sorted(sources.items(), key=lambda kv: kv[1].get("order", 0)):
        sd = root / domain / source
        missing = [f for f in ("README.md", "LICENSE") if not (sd / f).is_file()]
        if missing:
            raise PoolError(f"{source}: {' and '.join(missing)} missing from the fetched rows")
        total = sum(p.stat().st_size for p in sd.rglob("*") if p.is_file())
        sizes.append([str(ps.get("leaf")), source, str(ps.get("origin")), str(total), str(ps.get("licence")),
                      str(ps.get("tier"))])
    meta = root / META
    meta.mkdir(parents=True, exist_ok=True)
    (meta / "sizes.tsv").write_bytes("".join("\t".join(r) + "\n" for r in sizes).encode("utf-8"))
    (meta / "manifest.jsonl").write_bytes("".join(json.dumps(m, ensure_ascii=False) + "\n" for m in manifest)
                                          .encode("utf-8"))
    delivery = {"repo": run.get("repo"), "revision": run.get("revision"),
                "fetch_args": portable_fetch_args(run.get("fetch_args")), "rows": len(rows)}
    if expands:
        delivery["expanded"] = len(expands) - len(expand_failed)
        delivery["expand_failed"] = expand_failed
    (meta / "delivery.json").write_bytes((json.dumps(delivery, ensure_ascii=False, indent=1) + "\n").encode("utf-8"))
    return {"pool": str(root), "campaign": campaign, "sources": len(sizes), "units": len(manifest), "rows": len(rows),
            "differs_from_index": sum(1 for m in manifest if m.get("differs_from_index")), "obtained": obtained,
            **({"expanded": len(expands) - len(expand_failed), "expand_failed": expand_failed} if expands else {})}


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description="Lay out a fetched collection (fetch.py --tag campaign:<name>) as a "
                                             "task pool.")
    ap.add_argument("fetched", help="the --out folder of the fetch.py run")
    ap.add_argument("--out", required=True, help="folder that receives the batch folder")
    ap.add_argument("--name", required=True, help="batch folder name (lowercase letters, digits and . _ -)")
    ap.add_argument("--campaign", help="collection to lay out when the fetch covered several (name or campaign:<name>)")
    args = ap.parse_args(argv)
    try:
        res = build(args.fetched, args.out, args.name, campaign=args.campaign)
    except (PoolError, ValueError, OSError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 1
    print(json.dumps(res, sort_keys=True))
    return 0


if __name__ == "__main__":
    sys.exit(main())