@preventive/deptree 1.0.0-alpha.9 → 1.0.0

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.
package/soldeer.d.ts CHANGED
@@ -1,5 +1,3 @@
1
- // Hand-written against soldeer.js; a change to either belongs with the other.
2
-
3
1
  import type { Client } from '@preventive/upstream/github.js'
4
2
  import type { NodeType, Vfs } from '@preventive/vfs'
5
3
 
@@ -8,7 +6,7 @@ export { LockfileError, TomlError } from '@preventive/lockfile/soldeer.js'
8
6
  // Where @preventive/upstream caches what it fetches, zips and GitHub's
9
7
  // tarballs among them. Both are fetched through it, and that is the one
10
8
  // place anything here touches a filesystem: from its cache, where one is
11
- // set, which is where it writes each it fetches — setCacheDir() sets the
9
+ // set, which is where it writes each it fetches -- setCacheDir() sets the
12
10
  // default one, and setCacheDir(false) unsets it; unset, which it is until
13
11
  // set, it has none, and writes nothing. Soldeer's own folders are never
14
12
  // read. The project is read only through the view given as `project`, and
@@ -17,7 +15,7 @@ export { setCacheDir } from '@preventive/upstream/npm.js'
17
15
 
18
16
  // The machine Soldeer would install on: `soldeer` is the version that
19
17
  // installs, on its own or as `forge soldeer`, and has to be 0.12.0, which
20
- // extracts zips otherwise than 0.11 and older; `os` as Node names it —
18
+ // extracts zips otherwise than 0.11 and older; `os` as Node names it --
21
19
  // `linux`, `darwin`. Windows is refused: Soldeer names folders and reads
22
20
  // paths in zips otherwise there.
23
21
  export interface SoldeerHost {
@@ -51,8 +49,9 @@ export interface SoldeerProject {
51
49
  // config's [soldeer] settings, a value of a type Soldeer fails on is
52
50
  // refused, and so is recursive_deps = true, which has Soldeer install what
53
51
  // each dependency depends on too; the others change nothing beneath
54
- // dependencies/, and any other key is passed over, as Soldeer passes it
55
- // over. A config whose `dependencies` is inline, which Soldeer reads none
52
+ // dependencies/. A setting Soldeer 0.12 does not have is refused, though
53
+ // Soldeer passes it over, as a later Soldeer may install otherwise by it.
54
+ // A config whose `dependencies` is inline, which Soldeer reads none
56
55
  // from, is refused.
57
56
  //
58
57
  // The two ways the files come, one or the other: given, with `lockfile`
@@ -60,7 +59,7 @@ export interface SoldeerProject {
60
59
  // and none of them.
61
60
  //
62
61
  // `vfs` is a Vfs to mount the tree into, at its root, which is taken to be
63
- // the project's — it may be `project` too; without one, a new Vfs holds
62
+ // the project's -- it may be `project` too; without one, a new Vfs holds
64
63
  // the tree alone. A Vfs that holds a `dependencies` at its root, or on
65
64
  // macOS a name that is one there, is refused before anything is fetched,
66
65
  // as Soldeer would keep or remove what is in it by what it holds. Nothing
@@ -107,12 +106,12 @@ export interface SoldeerTreeStats {
107
106
  }
108
107
 
109
108
  // A dependency in the tree, as an SBOM would list it: `path` is its
110
- // folder, from the project's root, which is `/` of the Vfs —
109
+ // folder, from the project's root, which is `/` of the Vfs --
111
110
  // dependencies/<name>-<version>; `name` and `version` the lockfile's, as
112
111
  // the registry has them, or for a git dependency, the config's. From the
113
112
  // registry, `checksum` is the hex sha256 its zip is held to; from git,
114
113
  // `git` is the repository's URL and `rev` the commit, as the lockfile has
115
- // them.
114
+ // them, and `commit` that commit again, as the other trees name one.
116
115
  export type SoldeerInstalled = SoldeerInstalledZip | SoldeerInstalledGit
117
116
 
118
117
  export interface SoldeerInstalledZip {
@@ -128,6 +127,7 @@ export interface SoldeerInstalledGit {
128
127
  version: string
129
128
  git: string
130
129
  rev: string
130
+ commit: string
131
131
  }
132
132
 
133
133
  // `vfs` is the one given, the tree mounted into it, or a new one.
@@ -142,7 +142,7 @@ export interface SoldeerTree {
142
142
  // host.soldeer, in a project with no dependencies folder yet: rooted at
143
143
  // the project's root, it holds `dependencies/<name>-<version>` for each
144
144
  // dependency, and nothing else of the project. What Soldeer writes beside
145
- // it — the lockfile again, remappings, foundry.toml's libs — is not
145
+ // it -- the lockfile again, remappings, foundry.toml's libs -- is not
146
146
  // written, and where writing it fails after the install, as Soldeer may on
147
147
  // a remappings.txt it does not read, that is not followed.
148
148
  //
@@ -152,12 +152,12 @@ export interface SoldeerTree {
152
152
  // Soldeer extracts it, with the zip crate, into a folder of its own: no
153
153
  // root folder taken off; of two entries of one name, the later alone,
154
154
  // where the first was; anything under a `.git` passed over, as Windows
155
- // reads the name — trailing dots and spaces dropped, ASCII letters in
155
+ // reads the name -- trailing dots and spaces dropped, ASCII letters in
156
156
  // either case; each symlink written as a file holding its target. Each
157
157
  // directory is 0o755; each file's mode is its Unix mode as the zip crate
158
- // reads it — from the upper half of its external attributes, by whatever
158
+ // reads it -- from the upper half of its external attributes, by whatever
159
159
  // system made it, or none at all for Unix where that is 0, else for MS-DOS
160
- // from its read-only bit — without the
160
+ // from its read-only bit -- without the
161
161
  // type, setuid, setgid, sticky and group and other write bits; or 0o644,
162
162
  // where the zip crate reads none, or for a symlink, or for a file written
163
163
  // again by a name the zip crate reads no mode of, the mode it had. Both
@@ -168,11 +168,11 @@ export interface SoldeerTree {
168
168
  // config: each dependency has its entry, which Soldeer installs it from,
169
169
  // and each entry a dependency. And to more than Soldeer holds it to: a zip
170
170
  // is read with @preventive/archive/zip.js, which refuses what it does not
171
- // read — a `..`, absolute or backslashed name, one starting with a drive
171
+ // read -- a `..`, absolute or backslashed name, one starting with a drive
172
172
  // letter, zip64, encryption, an entry inside one that is not a directory,
173
173
  // two entries of one name that differ, a directory by its name or its
174
174
  // attributes and not by the other, entries that come to more than 512
175
- // MiB — where Soldeer would take some of it;
175
+ // MiB -- where Soldeer would take some of it;
176
176
  // and what the zip crate reads otherwise than the archive reader is
177
177
  // refused: a name with a byte past ASCII that is not flagged UTF-8, which
178
178
  // it reads as CP437, and an AES or a Unicode comment extra field. What
@@ -186,25 +186,28 @@ export interface SoldeerTree {
186
186
  // A git dependency Soldeer clones, `git clone` of the lockfile's `git`,
187
187
  // then `git checkout` of its `rev`; here it is fetched from a GitHub
188
188
  // repository alone, by `github`, as GitHub's tarball of the tree of that
189
- // commit, which upstream holds to the tree GitHub names for the commit. It
190
- // is written as a checkout with no git config and a umask of 0o022 writes
191
- // it: each directory 0o755, each file 0o644, or 0o755 where git has it
192
- // executable; each symlink a symlink to its target, as git has it; a
193
- // submodule an empty directory, as Soldeer leaves it without
194
- // recursive_deps; a file the tree's .gitattributes mark `eol=crlf` with
195
- // CRLF, as upstream reads them. The .git a clone has is not written, so
196
- // nothing of the repository's history is there; nor is what git config on
197
- // the machine would change, `core.autocrlf` or a filter such as Git LFS's.
198
- // Its folder is the config's name and version, which Soldeer's
199
- // sanitize_filename has to leave as they are. The `git` is the
200
- // repository's URL over https or ssh, as git takes it —
201
- // `https://github.com/<owner>/<name>`,
189
+ // commit, which upstream holds to the tree GitHub names for the commit. A
190
+ // repository renamed or transferred since, which GitHub answers with a
191
+ // redirect that git's clone follows, is fetched by the name GitHub gives
192
+ // it now, as upstream's getRepo follows that redirect with
193
+ // `followRedirect`; any other redirect is refused. It is written as a
194
+ // checkout with no git config and a umask of 0o022 writes it: each
195
+ // directory 0o755, each file 0o644, or 0o755 where git has it executable;
196
+ // each symlink a symlink to its target, as git has it; a submodule an
197
+ // empty directory, as Soldeer leaves it without recursive_deps; a file the
198
+ // tree's .gitattributes mark `eol=crlf` with CRLF, as upstream reads them.
199
+ // The .git a clone has is not written, so nothing of the repository's
200
+ // history is there; nor is what git config on the machine would change,
201
+ // `core.autocrlf` or a filter such as Git LFS's. Its folder is the
202
+ // config's name and version, which Soldeer's sanitize_filename has to
203
+ // leave as they are. The `git` is the repository's URL over https or ssh,
204
+ // as git takes it -- `https://github.com/<owner>/<name>`,
202
205
  // `ssh://git@github.com/<owner>/<name>` or
203
206
  // `git@github.com:<owner>/<name>`, `.git` after or not; git's http and git
204
207
  // protocols, which Soldeer has git refuse, are refused. GitHub's tarball
205
- // is refused where upstream refuses it — a tree with files marked
208
+ // is refused where upstream refuses it -- a tree with files marked
206
209
  // `export-ignore`, `ident` or `working-tree-encoding`, from a repo set to
207
- // include Git LFS objects in archives — and where the tar reader of
210
+ // include Git LFS objects in archives -- and where the tar reader of
208
211
  // @preventive/archive/tar.js does, as for a symlink whose target climbs
209
212
  // out of the tarball; so is a path with a `.git` in it, in any case, which
210
213
  // git refuses to check out. That the repository's branches and tags still
@@ -218,14 +221,14 @@ export interface SoldeerTree {
218
221
  //
219
222
  // Nothing is left to a guess: a lockfile the lockfile reader refuses, a
220
223
  // config this does not read as Soldeer reads it, a dependency from
221
- // anywhere but the registry or GitHub, a check above that fails — each is
224
+ // anywhere but the registry or GitHub, a check above that fails -- each is
222
225
  // refused with a DeptreeError, a LockfileError or a TomlError that says
223
226
  // where. A TypeError is thrown for options of the wrong type, and for a
224
227
  // git dependency without `github`.
225
228
  export function buildSoldeerTree(options: SoldeerTreeOptions): Promise<SoldeerTree>
226
229
 
227
- // `where` is what a refusal is about — `foundry.toml: profile.default`,
228
- // `dependencies["forge-std"]`, an entry of a zip — or undefined for the
230
+ // `where` is what a refusal is about -- `foundry.toml: profile.default`,
231
+ // `dependencies["forge-std"]`, an entry of a zip -- or undefined for the
229
232
  // call as a whole; the message leads with it. `cause` is what a package
230
233
  // beneath refused with, where one did.
231
234
  export class DeptreeError extends Error {
@@ -0,0 +1,183 @@
1
+ // A .crate as `cargo vendor` unpacks it into vendor/, cargo 1.94 to 1.99:
2
+ // registry/mod.rs's unpack, through vendor.rs's vendor_this; what the archive
3
+ // reader takes and cargo would read otherwise is refused. As a 0o022 umask
4
+ // leaves them, each directory is 0o755 unless its own entry gives a mode, and
5
+ // each file its mode within 0o777, both without group and other write bits.
6
+
7
+ import { crc32 } from '@exodus/bytes/crc.js'
8
+ import { utf8fromString, utf8toString } from '@exodus/bytes/utf8.js'
9
+ import { CompressionError, decompress } from '@preventive/archive/compression.js'
10
+ import { ArchiveError, unpack } from '@preventive/archive/tar.js'
11
+ import { compareNames } from '@preventive/vfs/path.js'
12
+ import { DeptreeError, quote } from '../error.js'
13
+ import { bytesSha256Hex } from '../hash.js'
14
+ import { own } from '../manifest.js'
15
+
16
+ // Cargo's bound on what a .crate unpacks to: 512 MiB, or twenty times the
17
+ // .crate where that is more.
18
+ const unpackLimit = (bytes) => Math.max(512 * 1024 * 1024, bytes.length * 20)
19
+ const [FTEXT, FEXTRA, FNAME, FCOMMENT] = [0x01, 0x04, 0x08, 0x10]
20
+
21
+ // Where the gzip member's deflate data starts, past its header: a header CRC
22
+ // or a reserved flag, which a reader may take or not, is refused.
23
+ function deflateStart(bytes, where) {
24
+ if (bytes.length < 18 || bytes[0] !== 0x1f || bytes[1] !== 0x8b || bytes[2] !== 0x08) throw new DeptreeError('the .crate is not gzipped', where)
25
+ const flags = bytes[3]
26
+ if (flags & ~(FTEXT | FEXTRA | FNAME | FCOMMENT)) throw new DeptreeError('a gzip header with a header CRC or a reserved flag is not supported', where)
27
+ let at = 10
28
+ if (flags & FEXTRA) at += 2 + (bytes[at] | (bytes[at + 1] << 8))
29
+ for (const flag of [FNAME, FCOMMENT]) {
30
+ if (!(flags & flag)) continue
31
+ const end = bytes.indexOf(0, at)
32
+ at = end === -1 ? bytes.length : end + 1
33
+ }
34
+ if (at > bytes.length - 8) throw new DeptreeError('the .crate\'s gzip header runs past its end', where)
35
+ return at
36
+ }
37
+
38
+ // flate2's GzDecoder, which cargo reads a .crate through, reads its first
39
+ // gzip member alone, where the platform's stream reads on into any after it;
40
+ // so the first has to be all of it. Its deflate data has to end where its
41
+ // eight-byte trailer starts, which deflate-raw holds it to, refusing what
42
+ // follows; and the trailer has to be the data's CRC-32 and length, as flate2
43
+ // checks them.
44
+ async function gunzip(bytes, where) {
45
+ const start = deflateStart(bytes, where)
46
+ const limit = unpackLimit(bytes)
47
+ let tar
48
+ try {
49
+ tar = await decompress(bytes.subarray(start, bytes.length - 8), 'deflate-raw', { limit })
50
+ } catch (error) {
51
+ if (!(error instanceof CompressionError)) throw error
52
+ throw new DeptreeError(error.limited ? `the .crate unpacks to more than ${limit} bytes, which cargo refuses` : 'the .crate is not one gzip member, which cargo reads the first of alone', where, { cause: error })
53
+ }
54
+ const trailer = new DataView(bytes.buffer, bytes.byteOffset + bytes.length - 8, 8)
55
+ if (trailer.getUint32(0, true) !== crc32(tar) || trailer.getUint32(4, true) !== tar.length >>> 0) throw new DeptreeError('the .crate\'s gzip trailer does not match its data', where)
56
+ return tar
57
+ }
58
+
59
+ function entriesOf(tar, where) {
60
+ try {
61
+ return unpack(tar)
62
+ } catch (error) {
63
+ if (error instanceof ArchiveError) throw new DeptreeError(`the .crate cannot be read: ${error.message}`, where, { cause: error })
64
+ throw error
65
+ }
66
+ }
67
+
68
+ // vendor_this: a `.git` anywhere on the way, a .gitattributes or .gitignore
69
+ // by name, .cargo-ok at the root; each is passed over before its type is
70
+ // looked at, unlike unpack's own .cargo-ok anywhere, after it.
71
+ const vendored = (segments, last) => !segments.includes('.git') && last !== '.gitattributes' && last !== '.gitignore' && segments.join('/') !== '.cargo-ok'
72
+
73
+ const modeOf = (entry) => entry.mode & 0o777 & ~0o022
74
+ const unsupported = (entry, why, here) => new DeptreeError(`mode ${entry.mode.toString(8)}, which keeps cargo from ${why} as any user but root, is not supported`, here)
75
+
76
+ // As any user but root, cargo reads back no file without its owner's read
77
+ // bit; lists nothing in a directory without its owner's read and search
78
+ // bits, leaving what is in it out of .cargo-checksum.json; and writes
79
+ // nothing into one without its write bit once its entry has set it, `after`.
80
+ // A directory nothing is in may have any mode. The package's always has
81
+ // something written into it last, its .cargo-checksum.json.
82
+ function fileMode(entry, here) {
83
+ const mode = modeOf(entry)
84
+ if (!(mode & 0o400)) throw unsupported(entry, 'reading it back to checksum it', here)
85
+ return mode
86
+ }
87
+ function dirMode({ entry, here, after }, content) {
88
+ const mode = modeOf(entry)
89
+ if (content && (mode & 0o500) !== 0o500) throw unsupported(entry, 'listing what is in it', here)
90
+ if (after && !(mode & 0o200)) throw unsupported(entry, 'writing into it what comes after it', here)
91
+ return mode
92
+ }
93
+
94
+ // The directory `<name>-<version>` every entry has to be in, as Rust's
95
+ // strip_prefix reads a path: by its components, so `./` or `/` before it
96
+ // is not it.
97
+ function segmentsOf(entry, prefix, here) {
98
+ const [first, ...rest] = entry.name.split('/')
99
+ if (entry.storedName.startsWith('/') || entry.storedName.startsWith('./') || first !== prefix) throw new DeptreeError(`not under ${quote(prefix)}, which cargo refuses`, here)
100
+ // tar 0.4.44, in cargo 1.94.0, takes the header's size over a pax one.
101
+ if (entry.pax.has('size')) throw new DeptreeError('a pax size, which cargo 1.94.0 reads otherwise, is not supported', here)
102
+ return rest
103
+ }
104
+
105
+ // `root` is the mode of the package's directory; `dirs` maps each directory
106
+ // under it to its mode, 0o755 where no entry of its own gives one.
107
+ function vendorEntries(entries, prefix, where) {
108
+ const dirs = new Map()
109
+ const files = new Map()
110
+ // Each directory an entry of its own gives a mode, the package's as ''.
111
+ const given = new Map()
112
+ for (const entry of entries) {
113
+ const here = `${where}: ${quote(entry.storedName)}`
114
+ const segments = segmentsOf(entry, prefix, here)
115
+ const last = segments.at(-1)
116
+ if (!vendored(segments, last)) continue
117
+ if (entry.type !== 'file' && entry.type !== 'directory') throw new DeptreeError(`a ${entry.type}, which cargo refuses`, here)
118
+ if (last === '.cargo-ok') continue
119
+ if (segments.length === 0 && entry.type !== 'directory') throw new DeptreeError('the package\'s directory is not a directory', here)
120
+ if (segments[0] === '.cargo-checksum.json') throw new DeptreeError('a .cargo-checksum.json of its own, which cargo vendor lists and then writes over, so that cargo cannot build from it', here)
121
+ // Each directory it is written into, the package's first.
122
+ let dir = ''
123
+ for (let i = 0; i < segments.length; i++) {
124
+ if (given.has(dir)) given.get(dir).after = true
125
+ if (i > 0 && !dirs.has(dir)) dirs.set(dir, 0o755)
126
+ dir = i === 0 ? segments[0] : `${dir}/${segments[i]}`
127
+ }
128
+ const path = segments.join('/')
129
+ if (entry.type === 'file') files.set(path, { data: entry.data, mode: fileMode(entry, here) })
130
+ else if (!given.has(path)) given.set(path, { entry, here, after: path === '' })
131
+ }
132
+ // A directory under the package's has something in it where an entry made it.
133
+ let root = 0o755
134
+ for (const [path, dir] of given) {
135
+ if (path === '') root = dirMode(dir, true)
136
+ else dirs.set(path, dirMode(dir, dirs.has(path)))
137
+ }
138
+ return { root, dirs, files }
139
+ }
140
+
141
+ const COMMENT = 'This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.'
142
+
143
+ // vendor.rs's, as serde_json writes it: compact, each map's keys in UTF-8
144
+ // byte order, `$comment` from cargo 1.97 on.
145
+ async function checksumFile(files, checksum, comment) {
146
+ const paths = [...files.keys()].sort(compareNames)
147
+ const sums = await Promise.all(paths.map((path) => bytesSha256Hex(files.get(path).data)))
148
+ const listed = paths.map((path, i) => `${JSON.stringify(path)}:"${sums[i]}"`).join(',')
149
+ return `{${comment ? `"$comment":${JSON.stringify(COMMENT)},` : ''}"files":{${listed}},"package":${JSON.stringify(checksum)}}`
150
+ }
151
+
152
+ // A full commit id, as git writes one: 40 lowercase hex digits, or 64 in a
153
+ // repository of SHA-256 objects.
154
+ const COMMIT = /^(?:[\da-f]{40}|[\da-f]{64})$/u
155
+
156
+ // The commit .cargo_vcs_info.json names, which `cargo package` writes where
157
+ // it packs from a git checkout: none where it found the checkout dirty, as
158
+ // the files are then not that commit's, nor where it names anything but a
159
+ // full id. Cargo reads none of it, so one that is not JSON names none, and
160
+ // is vendored all the same.
161
+ function vcsCommitOf(file) {
162
+ if (file === undefined) return undefined
163
+ try {
164
+ const git = own(JSON.parse(utf8toString(file.data)), 'git')
165
+ if (![undefined, false].includes(own(git, 'dirty'))) return undefined
166
+ const sha1 = own(git, 'sha1')
167
+ return typeof sha1 === 'string' && COMMIT.test(sha1) ? sha1 : undefined
168
+ } catch {
169
+ return undefined
170
+ }
171
+ }
172
+
173
+ // What vendor/<directory> holds of a package, `.cargo-checksum.json` among
174
+ // its files. getCrate has held the .crate to its checksum; it is held to it
175
+ // again where it is unpacked.
176
+ export async function vendorCrate(bytes, { name, version, checksum }, comment, where) {
177
+ if (await bytesSha256Hex(bytes) !== checksum) throw new DeptreeError(`its .crate's sha256 is not ${checksum}`, where)
178
+ const { root, dirs, files } = vendorEntries(entriesOf(await gunzip(bytes, where), where), `${name}-${version}`, where)
179
+ const commit = vcsCommitOf(files.get('.cargo_vcs_info.json'))
180
+ const text = await checksumFile(files, checksum, comment)
181
+ files.set('.cargo-checksum.json', { data: utf8fromString(text), mode: 0o644 })
182
+ return { root, dirs, files, checksumText: text, commit }
183
+ }
@@ -0,0 +1,81 @@
1
+ // What buildCargoTree takes, as text or read from the project's root. Texts
2
+ // given are laid out as the project they stand for, so that both are read
3
+ // one way.
4
+
5
+ import { Vfs } from '@preventive/vfs'
6
+ import { DeptreeError, quote } from '../error.js'
7
+ import { UNSAFE, isInside } from '../mount.js'
8
+ import { checkHostKeys, checkLeftOut, checkProject, checkTexts, readText, typeOf } from '../project.js'
9
+
10
+ // 1.94 to 1.99 vendor alike, but for the `$comment` 1.97 and later write.
11
+ const VERSION = /^1\.(9[4-9])\.(?:0|[1-9]\d*)$/u
12
+
13
+ export function checkHost(host) {
14
+ checkHostKeys(host, ['cargo', 'os'], 'cargo and os')
15
+ const minor = VERSION.exec(host.cargo)?.[1]
16
+ if (minor === undefined) throw new DeptreeError(`cargo ${quote(host.cargo)} is not supported: only cargo 1.94.0 to 1.99.x are`, 'host.cargo')
17
+ if (host.os === 'win32') throw new DeptreeError('Windows is not supported: cargo unpacks and names files otherwise there', 'host.os')
18
+ return { cargo: host.cargo, os: host.os, comment: Number(minor) >= 97 }
19
+ }
20
+
21
+ // A file cargo reads, by its path from the root, as text, or undefined where
22
+ // there is none: a link at it or on the way to it is refused, so that nothing
23
+ // is read from outside the project's view.
24
+ export function readUnlinked(project, file, what) {
25
+ const segments = file.split('/')
26
+ for (let i = 1; i <= segments.length; i++) {
27
+ const path = segments.slice(0, i).join('/')
28
+ const type = typeOf(project, `/${path}`, false)
29
+ if (type === undefined) return undefined
30
+ if (type === 'symlink') throw new DeptreeError(`a link where cargo reads ${what} is not supported`, quote(path))
31
+ }
32
+ return readText(project, `/${file}`, file)
33
+ }
34
+
35
+ // Cargo reads .cargo/config where it is, in .cargo/config.toml's stead.
36
+ function readConfig(project) {
37
+ for (const file of ['.cargo/config', '.cargo/config.toml']) {
38
+ const text = readUnlinked(project, file, 'its config')
39
+ if (text !== undefined) return { text, file }
40
+ }
41
+ return { text: undefined, file: '.cargo/config.toml' }
42
+ }
43
+
44
+ const MANIFESTS = 'manifests must map each directory, "." for the root, to the text of its Cargo.toml'
45
+
46
+ // `.` or a path below the root, as a Cargo.toml's directory is named.
47
+ function given(manifests) {
48
+ if (manifests === null || typeof manifests !== 'object') throw new TypeError(MANIFESTS)
49
+ const vfs = new Vfs()
50
+ const dirs = new Set()
51
+ for (const [dir, text] of manifests instanceof Map ? manifests : Object.entries(manifests)) {
52
+ if (typeof dir !== 'string' || typeof text !== 'string') throw new TypeError(MANIFESTS)
53
+ if (dir !== '.' && (!isInside(dir) || UNSAFE.test(dir))) throw new DeptreeError('not a directory below the root, as it is named here', `manifests[${quote(dir)}]`)
54
+ const path = dir === '.' ? '' : `/${dir}`
55
+ if (path !== '') vfs.mkdir(path, { recursive: true })
56
+ vfs.writeFile(`${path}/Cargo.toml`, text)
57
+ dirs.add(dir)
58
+ }
59
+ return { vfs, dirs }
60
+ }
61
+
62
+ const LOCKFILE = 'lockfile must be the Cargo.lock text, or left out where project is given'
63
+
64
+ // `project` the view manifests are read from, and `given` the directories
65
+ // of those given, which have to be those read.
66
+ export function inputsOf(options) {
67
+ const { lockfile, manifests, config, project } = options
68
+ if (lockfile === undefined) {
69
+ if (project === undefined) throw new TypeError(LOCKFILE)
70
+ checkProject(project)
71
+ checkLeftOut({ manifests, config }, 'all')
72
+ const lock = readUnlinked(project, 'Cargo.lock', 'its lockfile')
73
+ if (lock === undefined) throw new DeptreeError('the project has no Cargo.lock, without which cargo resolves every dependency anew')
74
+ return { lockfile: lock, config: readConfig(project), project, given: undefined }
75
+ }
76
+ if (typeof lockfile !== 'string') throw new TypeError(LOCKFILE)
77
+ if (project !== undefined) throw new TypeError('project must be left out where lockfile is given')
78
+ checkTexts({ config })
79
+ const { vfs, dirs } = given(manifests)
80
+ return { lockfile, config: { text: config, file: '.cargo/config.toml' }, project: vfs, given: dirs }
81
+ }
@@ -0,0 +1,90 @@
1
+ // workspace.members, exclude and default-members as cargo reads them: each
2
+ // glob from the root through the glob crate, `*` and `?` taking any name in
3
+ // a directory, one with a leading dot too; `**` and `[`, and a path that
4
+ // leads out of the root or depends on where it is, are refused.
5
+
6
+ import { compareNames, join } from '@preventive/vfs/path.js'
7
+ import { DeptreeError, quote } from '../error.js'
8
+ import { wildcard } from '../matcher.js'
9
+ import { UNSAFE, fold } from '../mount.js'
10
+ import { typeOf } from '../project.js'
11
+
12
+ const WILD = /[*?]/u
13
+ const at = (dir) => (dir === '.' ? '/' : `/${dir}`)
14
+
15
+ // A path's components as Rust's Path has them past a root: no empty or `.`.
16
+ export const parts = (path) => path.split('/').filter((segment) => segment !== '' && segment !== '.')
17
+
18
+ // Each entry of the three lists, before anything is read by it.
19
+ export function checkLists(workspace) {
20
+ for (const key of ['members', 'exclude', 'defaultMembers']) {
21
+ for (const [index, entry] of (workspace[key] ?? []).entries()) {
22
+ const where = `Cargo.toml: workspace.${key === 'defaultMembers' ? 'default-members' : key}[${index}]`
23
+ if (entry.startsWith('/') || UNSAFE.test(entry)) throw new DeptreeError(`${quote(entry)} is not a relative path within the project, which is all that is read`, where)
24
+ if (key !== 'exclude' && parts(entry).includes('..')) throw new DeptreeError(`${quote(entry)} leads out of the root, which is not read`, where)
25
+ if (key !== 'exclude' && /\*\*|\[/u.test(entry)) throw new DeptreeError(`${quote(entry)} has a \`**\` or a \`[\`, which is not supported`, where)
26
+ }
27
+ }
28
+ }
29
+
30
+ // is_excluded: under an `exclude` path and no `members` one, each taken as
31
+ // written, a glob's wildcards as names.
32
+ export function isExcluded(workspace, path) {
33
+ const under = (list) => list.some((entry) => {
34
+ const prefix = parts(entry)
35
+ return prefix.length <= path.length && prefix.every((segment, i) => segment === path[i])
36
+ })
37
+ return under(workspace.exclude) && !under(workspace.members)
38
+ }
39
+
40
+ // A name glob() checks for by a path, which on macOS takes it in any case.
41
+ function literal(names, segment, folded, dir, where) {
42
+ if (names.includes(segment)) return [segment]
43
+ const other = folded ? names.find((name) => fold(name) === fold(segment)) : undefined
44
+ if (other !== undefined) throw new DeptreeError(`${quote(join(dir, segment))} is ${quote(join(dir, other))} on macOS, which is not supported`, where)
45
+ return []
46
+ }
47
+
48
+ // Every path the glob takes, files among them, which glob() lists too. A
49
+ // link it reaches is refused, as glob() follows it.
50
+ function expand(project, glob, folded, where) {
51
+ let found = ['.']
52
+ for (const segment of parts(glob)) {
53
+ const matches = WILD.test(segment) ? wildcard(segment, { one: true }) : undefined
54
+ const next = []
55
+ for (const dir of found) {
56
+ if (typeOf(project, at(dir), false) !== 'directory') continue
57
+ const names = project.readdir(at(dir))
58
+ for (const name of matches === undefined ? literal(names, segment, folded, dir, where) : names.filter(matches)) {
59
+ const path = join(dir, name)
60
+ if (typeOf(project, at(path), false) === 'symlink') throw new DeptreeError('a link where cargo looks for members is not supported', quote(path))
61
+ next.push(path)
62
+ }
63
+ }
64
+ found = next
65
+ }
66
+ return found.sort(compareNames)
67
+ }
68
+
69
+ // members_paths: the directories each glob takes, where one that takes
70
+ // nothing at all fails as cargo goes to read it.
71
+ function pathsOf(project, globs, key, folded) {
72
+ return globs.flatMap((glob, index) => {
73
+ const where = `Cargo.toml: workspace.${key}[${index}]`
74
+ const found = expand(project, glob, folded, where)
75
+ if (found.length === 0) throw new DeptreeError(`${quote(glob)} takes nothing, which cargo fails on`, where)
76
+ return found.filter((dir) => typeOf(project, at(dir)) === 'directory')
77
+ })
78
+ }
79
+
80
+ export const explicitMembers = (project, workspace, folded) => pathsOf(project, workspace.members, 'members', folded)
81
+
82
+ // Cargo, run at the root, holds each default member to be a member, or a
83
+ // directory `members` takes, `listed`, that is excluded.
84
+ export function checkDefaultMembers(project, workspace, members, listed, folded) {
85
+ if (workspace.defaultMembers === undefined) return
86
+ for (const dir of pathsOf(project, workspace.defaultMembers, 'default-members', folded)) {
87
+ if (members.has(dir) || (listed.has(dir) && isExcluded(workspace, parts(dir)))) continue
88
+ throw new DeptreeError(`${quote(dir)} is no member, which cargo refuses`, 'Cargo.toml: workspace.default-members')
89
+ }
90
+ }
@@ -0,0 +1,65 @@
1
+ // The packages `cargo vendor` copies into vendor/, each from its .crate:
2
+ // every one of the lockfile's but a path package, which is in the project
3
+ // already. Each is fetched from crates.io and unpacked as cargo unpacks it.
4
+
5
+ import { parseVersion } from '@preventive/lockfile/rust-semver.js'
6
+ import { getCrate } from '@preventive/upstream/cargo.js'
7
+ import { eachConcurrently } from '../concurrent.js'
8
+ import { DeptreeError, quote } from '../error.js'
9
+ import { vendorCrate } from './crate.js'
10
+
11
+ // As Cargo.lock names crates.io, however cargo reaches its index.
12
+ const CRATES_IO = 'registry+https://github.com/rust-lang/crates.io-index'
13
+
14
+ export const about = (key) => `packages[${quote(key)}]`
15
+
16
+ const sign = (a, b) => (a === b ? 0 : a < b ? -1 : 1)
17
+
18
+ // The semver crate's order of two versions the lockfile reader has read, but
19
+ // for build metadata, which crates.io takes no two versions apart by: a
20
+ // pre-release before its release, its identifiers digits before others and
21
+ // digits by their value.
22
+ function compareVersions(a, b) {
23
+ const [x, y] = [parseVersion(a), parseVersion(b)]
24
+ for (const part of ['major', 'minor', 'patch']) if (x[part] !== y[part]) return sign(x[part], y[part])
25
+ if (x.pre === '' || y.pre === '') return sign(x.pre === '', y.pre === '')
26
+ const [ids1, ids2] = [x.pre.split('.'), y.pre.split('.')]
27
+ for (let i = 0; i < Math.min(ids1.length, ids2.length); i++) {
28
+ const [p, q] = [ids1[i], ids2[i]]
29
+ const [digits1, digits2] = [/^\d+$/u.test(p), /^\d+$/u.test(q)]
30
+ if (digits1 !== digits2) return digits1 ? -1 : 1
31
+ const order = (digits1 && sign(p.length, q.length)) || sign(p, q)
32
+ if (order !== 0) return order
33
+ }
34
+ return sign(ids1.length, ids2.length)
35
+ }
36
+
37
+ // vendor.rs: the greatest version of a name has a directory of the name
38
+ // alone, and any other `<name>-<version>`.
39
+ export function vendoredPackages(lock) {
40
+ const crates = []
41
+ for (const [key, pkg] of Object.entries(lock.packages)) {
42
+ if (pkg.source === undefined) continue
43
+ if (pkg.source.startsWith('git+')) throw new DeptreeError('a git dependency, which cargo vendor checks out with git, is not supported', about(key))
44
+ if (pkg.source !== CRATES_IO) throw new DeptreeError('a package from a registry other than crates.io is not supported', about(key))
45
+ crates.push({ key, name: pkg.name, version: pkg.version, checksum: pkg.checksum })
46
+ }
47
+ const greatest = new Map()
48
+ for (const { name, version } of crates) {
49
+ const other = greatest.get(name)
50
+ const order = other === undefined ? 1 : compareVersions(version, other)
51
+ if (order === 0) throw new DeptreeError(`${quote(version)} and ${quote(other)} differ only in build metadata, which cargo vendors one of`, about(`${name} ${version}`))
52
+ if (order > 0) greatest.set(name, version)
53
+ }
54
+ for (const crate of crates) crate.directory = crate.version === greatest.get(crate.name) ? crate.name : `${crate.name}-${crate.version}`
55
+ return crates
56
+ }
57
+
58
+ // A few at a time; what each holds, by its key.
59
+ export async function fetchCrates(crates, comment) {
60
+ const vendored = new Map()
61
+ await eachConcurrently(crates, async (crate) => {
62
+ vendored.set(crate.key, await vendorCrate(await getCrate(crate.name, crate.version, crate.checksum), crate, comment, about(crate.key)))
63
+ }, ({ key }) => about(key))
64
+ return vendored
65
+ }