@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/bin/compare.js ADDED
@@ -0,0 +1,123 @@
1
+ // The two sides `deptree compare` sets beside each other, what is on disk
2
+ // and what deptree builds, each a map from a path under the folders an
3
+ // install makes to its type, mode, and bytes or link target; and how they
4
+ // differ: files and links as @preventive/compare tells them, the rest here.
5
+
6
+ import { Buffer } from 'node:buffer'
7
+ import { lstatSync, readFileSync, readdirSync, readlinkSync, statSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { compareTrees } from '@preventive/compare'
10
+ import { compareNames, dirname, normalize } from '@preventive/vfs/path.js'
11
+ import { typeOf } from '../src/project.js'
12
+
13
+ const kindOf = (st) => (st.isSymbolicLink() ? 'symlink' : st.isDirectory() ? 'directory' : st.isFile() ? 'file' : 'other')
14
+
15
+ // The project's directory as deptree reads one, by paths from `/`, never
16
+ // above it, its names in code point order, as a Vfs lists them, and its
17
+ // modes with the setuid, setgid and sticky bits, as a Vfs keeps them.
18
+ export function projectView(root) {
19
+ const at = (path) => join(root, normalize(`/${path}`))
20
+ return {
21
+ readdir: (path) => readdirSync(at(path)).sort(compareNames),
22
+ lstat(path) {
23
+ const st = lstatSync(at(path))
24
+ return { type: kindOf(st), mode: st.mode & 0o7777 }
25
+ },
26
+ stat: (path) => ({ type: kindOf(statSync(at(path))) }),
27
+ readFile: (path) => readFileSync(at(path)),
28
+ readlink: (path) => readlinkSync(at(path)),
29
+ }
30
+ }
31
+
32
+ // What deptree never builds: the .bin directories, each package manager's
33
+ // record of its install, and the .git of a dependency Soldeer clones.
34
+ const NOT_BUILT = /(?:^|\/)node_modules\/(?:\.bin|\.modules\.yaml|\.pnpm-workspace-state(?:-v\d+)?\.json|\.pnpm\/lock\.yaml|\.package-lock\.json|\.yarn-integrity)(?:\/|$)|^dependencies\/[^/]+\/\.git(?:\/|$)/u
35
+
36
+ // Everything under each of `dirs` as `view` has it, the disk's projectView
37
+ // or the tree's Vfs: links not followed, every file read whole, and a
38
+ // folder not there left out. A directory deptree never builds is one entry,
39
+ // not entered, as only it is ever listed.
40
+ export function readSide(view, dirs) {
41
+ const entries = new Map()
42
+ const stack = dirs.filter((dir) => typeOf(view, dir, false) !== undefined)
43
+ while (stack.length > 0) {
44
+ const path = stack.pop()
45
+ const { type, mode } = view.lstat(path)
46
+ const entry = { type, mode }
47
+ if (type === 'file') entry.data = view.readFile(path)
48
+ if (type === 'symlink') entry.target = view.readlink(path)
49
+ entries.set(path, entry)
50
+ if (type === 'directory' && !NOT_BUILT.test(path)) for (const name of view.readdir(path)) stack.push(`${path}/${name}`)
51
+ }
52
+ return entries
53
+ }
54
+
55
+ // The paths on disk alone that hold nothing Node resolves: what deptree never
56
+ // builds, and directories of nothing else, as pnpm leaves a node_modules of a
57
+ // .bin of links to what it removed, a scope once its last package goes, or
58
+ // the hoisted linker's .pnpm of its state alone.
59
+ export function leftOut(changes, disk) {
60
+ const left = new Set(changes.filter(({ mark }) => mark === '-').map(({ path }) => path))
61
+ for (const [path, { type }] of disk) {
62
+ if (left.size === 0) break
63
+ if (type === 'directory' || NOT_BUILT.test(path)) continue
64
+ // Nothing listed is under another listed, so the first one up is its.
65
+ for (let at = path; at !== '.'; at = dirname(at)) {
66
+ if (left.delete(at)) break
67
+ }
68
+ }
69
+ return left
70
+ }
71
+
72
+ // A package's directory in node_modules/.pnpm on disk alone, which pnpm keeps
73
+ // for a while after no install has it.
74
+ export const leftBehind = ({ mark, type, path }) => mark === '-' && type === 'directory' && /(?:^|\/)node_modules\/\.pnpm\/[^/]*@[^/]*$/u.test(path)
75
+
76
+ // Walk order, as Vfs.walk goes: a `/` sorts before anything a name can hold.
77
+ export const byPath = (a, b) => compareNames(a.replaceAll('/', '\0'), b.replaceAll('/', '\0'))
78
+
79
+ const octal = (mode) => mode.toString(8).padStart(3, '0')
80
+
81
+ // What compare compares: files and links, whose directories it implies.
82
+ const compared = (entry) => entry === undefined || entry.type === 'file' || entry.type === 'symlink'
83
+ function entriesOf(side) {
84
+ const entries = []
85
+ for (const [name, { type, mode, data, target }] of side) {
86
+ if (type === 'file') entries.push({ name, mode, data })
87
+ if (type === 'symlink') entries.push({ name, type, linkname: target })
88
+ }
89
+ return entries
90
+ }
91
+
92
+ // A file or a link compare finds differs, in deptree's words, and whether a
93
+ // file's bytes do, as its mode alone may.
94
+ function changeOf({ status, old: disk, new: tree }) {
95
+ if (status === 'added') return { mark: '+', type: tree.type }
96
+ if (status === 'deleted') return { mark: '-', type: disk.type }
97
+ if (status === 'type-changed') return { mark: '~', type: tree.type, what: `${disk.type} on disk, ${tree.type} in the tree` }
98
+ if (tree.type === 'symlink') return { mark: '~', type: tree.type, what: `link to ${disk.target} on disk, to ${tree.target} in the tree` }
99
+ const content = disk.mode === tree.mode || Buffer.compare(disk.data, tree.data) !== 0
100
+ const what = content ? ['content'] : []
101
+ if (disk.mode !== tree.mode) what.push(`mode ${octal(disk.mode)} on disk, ${octal(tree.mode)} in the tree`)
102
+ return { mark: '~', type: tree.type, what: what.join('; '), content }
103
+ }
104
+
105
+ // How the disk differs from the tree, in walk order, each file or link with
106
+ // compare's `status` of it, as formatPatch takes it. Nothing is listed under
107
+ // a path only one side has, or of another type on each, as only a directory
108
+ // has anything in it; a directory's own mode is the umask's, not compared.
109
+ export function difference(disk, tree) {
110
+ const shown = (path) => disk.get(dirname(path))?.type === tree.get(dirname(path))?.type
111
+ const changes = []
112
+ for (const path of new Set([...disk.keys(), ...tree.keys()])) {
113
+ const [one, two] = [disk.get(path), tree.get(path)]
114
+ if ((compared(one) && compared(two)) || !shown(path) || one?.type === two?.type) continue
115
+ const mark = one === undefined ? '+' : two === undefined ? '-' : '~'
116
+ changes.push({ path, mark, type: (two ?? one).type, ...(mark === '~' && { what: `${one.type} on disk, ${two.type} in the tree` }) })
117
+ }
118
+ for (const status of compareTrees(entriesOf(disk), entriesOf(tree), { renames: false, lines: false })) {
119
+ const { path } = status.new ?? status.old
120
+ if (compared(disk.get(path)) && compared(tree.get(path)) && shown(path)) changes.push({ path, ...changeOf(status), status })
121
+ }
122
+ return changes.sort((a, b) => byPath(a.path, b.path))
123
+ }
package/bin/deptree.js ADDED
@@ -0,0 +1,217 @@
1
+ #!/usr/bin/env node
2
+ // The deptree command: `compare` sets what a package manager installed
3
+ // beside the tree deptree builds; see USAGE.
4
+
5
+ import { resolve } from 'node:path'
6
+ import process from 'node:process'
7
+ import { parseArgs, styleText } from 'node:util'
8
+ import { CompareError, formatPatch } from '@preventive/compare'
9
+ import { diffLineStyles } from '@preventive/diff/color.js'
10
+ import { createClient } from '@preventive/upstream/github.js'
11
+ import { defaultCacheDir, setCacheDir } from '@preventive/upstream/npm.js'
12
+ import { join } from '@preventive/vfs/path.js'
13
+ import { buildCargoTree } from '../cargo.js'
14
+ import { buildNpmTree, findNpmWorkspaces } from '../npm.js'
15
+ import { DeptreeError, LockfileError, buildPnpmTree, findPnpmProjects } from '../pnpm.js'
16
+ import { TomlError, buildSoldeerTree } from '../soldeer.js'
17
+ import { buildYarn1Tree, findYarn1Workspaces } from '../yarn1.js'
18
+ import { escaped } from '../src/error.js'
19
+ import { typeOf } from '../src/project.js'
20
+ import { difference, leftBehind, leftOut, projectView, readSide } from './compare.js'
21
+ import { userToken } from './npmrc.js'
22
+
23
+ const USAGE = `Usage: deptree compare [options] [<dir>]
24
+
25
+ Builds the tree the lockfile in <dir> (by default .) installs, from
26
+ pnpm-lock.yaml, package-lock.json, yarn.lock, soldeer.lock or Cargo.lock,
27
+ and lists where it differs from what is on disk, every node_modules of the
28
+ project, Soldeer's dependencies or cargo's vendor:
29
+
30
+ + <path> only in the tree
31
+ - <path> only on disk
32
+ ~ <path> in both, but of another type, content, mode or link target
33
+
34
+ A directory one side has alone is one line, ending in /. Left out unless
35
+ --all: .bin directories, state files, Soldeer's .git, and directories on
36
+ disk holding nothing else. Exits 0 where the two are the same, 1 where
37
+ they differ, 2 on trouble.
38
+
39
+ Tarballs, zips and crates are kept in ${defaultCacheDir ?? 'no cache, as no home directory is known'}.
40
+ A scoped package is fetched with PREVENTIVE_MEASURES_NPM_TOKEN,
41
+ STASIS_NPM_TOKEN or NPM_TOKEN, else with a ~/.npmrc line of nothing but
42
+ //registry.npmjs.org/:_authToken=npm_\u2026; a Soldeer git dependency with
43
+ GITHUB_TOKEN or GH_TOKEN, else anonymously.
44
+
45
+ --pnpm, --yarn, --npm, --soldeer, --cargo <version>
46
+ the one that installed: by default the one
47
+ packageManager pins, or Soldeer 0.12.0; npm's and
48
+ cargo's are needed
49
+ --node <version> the Node it installed with; by default this one
50
+ --metadata fetch each package's version document from npm's
51
+ registry too, and hold its tarball's dist to it
52
+ --all list what is left out too
53
+ --diff follow each file of other content with its patch, as
54
+ git diff writes it, for patch -p1 or git apply in <dir>
55
+ -h, --help show this message
56
+ `
57
+
58
+ const OPTIONS = {
59
+ pnpm: { type: 'string' },
60
+ yarn: { type: 'string' },
61
+ npm: { type: 'string' },
62
+ soldeer: { type: 'string' },
63
+ cargo: { type: 'string' },
64
+ node: { type: 'string' },
65
+ metadata: { type: 'boolean', default: false },
66
+ all: { type: 'boolean' },
67
+ diff: { type: 'boolean' },
68
+ help: { type: 'boolean', short: 'h' },
69
+ }
70
+
71
+ // Each package manager by its version flag: its lockfile, the folder it
72
+ // installs into in each project it finds, and the version where the flag is
73
+ // left out and nothing pins one, or, `unpinned`, that the flag is needed.
74
+ const MANAGERS = {
75
+ pnpm: { lockfile: 'pnpm-lock.yaml', folder: 'node_modules', projects: findPnpmProjects, build: buildPnpmTree },
76
+ yarn: { lockfile: 'yarn.lock', folder: 'node_modules', projects: findYarn1Workspaces, build: buildYarn1Tree },
77
+ npm: { lockfile: 'package-lock.json', folder: 'node_modules', unpinned: true, projects: findNpmWorkspaces, build: buildNpmTree },
78
+ soldeer: {
79
+ lockfile: 'soldeer.lock',
80
+ folder: 'dependencies',
81
+ version: '0.12.0',
82
+ projects: () => ['.'],
83
+ build: (options) => buildSoldeerTree({ ...options, github: createClient({ token: process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null }) }),
84
+ },
85
+ cargo: { lockfile: 'Cargo.lock', folder: 'vendor', unpinned: true, projects: () => ['.'], build: buildCargoTree },
86
+ }
87
+
88
+ async function main(argv) {
89
+ const { values, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true })
90
+ if (values.help) {
91
+ process.stdout.write(USAGE)
92
+ return 0
93
+ }
94
+ const [command, dir = '.', ...rest] = positionals
95
+ if (command !== 'compare' || rest.length > 0) return fail(USAGE)
96
+ const project = projectView(resolve(dir))
97
+ const name = managerOf(project, dir, values)
98
+ const manager = MANAGERS[name]
99
+ if (defaultCacheDir !== undefined) setCacheDir()
100
+ // upstream reads it for each request, and sends it for a scoped package.
101
+ process.env.NPM_TOKEN ||= userToken() ?? ''
102
+ // This machine, which installed what is on disk; npm takes no libc where
103
+ // there is none to find.
104
+ const libc = libcOf()
105
+ const host = { [name]: values[name] ?? manager.version, node: values.node ?? process.versions.node, os: process.platform, cpu: process.arch, ...(name === 'npm' && libc === 'unknown' ? {} : { libc }) }
106
+ // The disk first, as it is before anything is fetched.
107
+ const dirs = manager.projects({ project, host, os: host.os }).map((at) => join(at, manager.folder))
108
+ const disk = readSide(project, dirs)
109
+ const files = [...disk.values()].filter((entry) => entry.type === 'file')
110
+ note(`${manager.folder} on disk: ${files.length} files, ${size(files.reduce((sum, file) => sum + file.data.length, 0))}`)
111
+ const tree = await manager.build({ project, host, metadata: values.metadata })
112
+ note(`${manager.lockfile}: ${tree.stats.files} files, ${size(tree.stats.bytes)} built`)
113
+ const built = readSide(tree.vfs, dirs)
114
+ const changes = difference(disk, built)
115
+ const left = values.all ? new Set() : leftOut(changes, disk)
116
+ const listed = changes.filter((change) => !left.has(change.path))
117
+ // A file of other content, with its mode lines where those differ too, as
118
+ // patch -p1 carries out no link's. A name that ends in a space git apply
119
+ // reads, and patch does not.
120
+ const patch = ({ content, status }) => (values.diff && content ? painted(formatPatch([status])) : '')
121
+ process.stdout.write(listed.map((change) => line(change) + patch(change)).join(''))
122
+ note(summary(listed, left.size))
123
+ if (name === 'pnpm') pruneHint(listed)
124
+ return listed.length === 0 ? 0 : 1
125
+ }
126
+
127
+ // The one a version flag names, or else the one whose lockfile is there.
128
+ function managerOf(project, dir, values) {
129
+ const names = Object.keys(MANAGERS)
130
+ const named = names.filter((name) => values[name] !== undefined)
131
+ const [name, ...others] = named.length > 0 ? named : names.filter((n) => typeOf(project, MANAGERS[n].lockfile) === 'file')
132
+ if (name === undefined) fail(`deptree: ${dir}: no ${names.map((n) => MANAGERS[n].lockfile).join(', ')}\n`)
133
+ if (others.length > 0) fail(`deptree: ${dir}: give one of --${[name, ...others].join(', --')}, for the package manager that installed\n`)
134
+ if (MANAGERS[name].unpinned && values[name] === undefined) fail(`deptree: ${MANAGERS[name].lockfile}: give --${name} <version>, the ${name} that installed, which no file pins\n`)
135
+ return name
136
+ }
137
+
138
+ // As pnpm's detect-libc tells it, from Node's report, which leaves out the
139
+ // network, whose reverse DNS can stall.
140
+ function libcOf() {
141
+ if (process.platform !== 'linux') return 'unknown'
142
+ process.report.excludeNetwork = true
143
+ const { header, sharedObjects } = process.report.getReport()
144
+ if (header.glibcVersionRuntime) return 'glibc'
145
+ return sharedObjects.some((file) => file.includes('libc.musl-') || file.includes('ld-musl-')) ? 'musl' : 'unknown'
146
+ }
147
+
148
+ const MARKS = { '+': 'green', '-': 'red', '~': 'yellow' }
149
+
150
+ // A path is whatever a tarball spells: escaped, so that no name can act on a
151
+ // terminal or break a line, a backslash doubled first so an escape reads as one.
152
+ const shown = (text) => escaped(text.replaceAll('\\', '\\\\'))
153
+
154
+ function line({ mark, path, type, what }) {
155
+ const slash = mark !== '~' && type === 'directory' ? '/' : ''
156
+ const why = what === undefined ? '' : ` (${shown(what)})`
157
+ return `${styleText(MARKS[mark], `${mark} ${shown(path)}${slash}`, { stream: process.stdout })}${why}\n`
158
+ }
159
+
160
+ // On a terminal, a diff's lines escaped as names are, but for tabs and
161
+ // backslashes, and painted; elsewhere byte for byte, for patch to apply.
162
+ function painted(patch) {
163
+ if (!process.stdout.isTTY) return patch
164
+ const styles = diffLineStyles(patch)
165
+ return patch.split('\n').map((text, i) => {
166
+ const plain = text.split('\t').map(escaped).join('\t')
167
+ return styles?.[i] ? styleText(styles[i], plain, { stream: process.stdout }) : plain
168
+ }).join('\n')
169
+ }
170
+
171
+ function summary(changes, left) {
172
+ const count = (mark) => changes.filter((change) => change.mark === mark).length
173
+ const counts = changes.length === 0 ? 'the same' : `${count('+')} only in the tree, ${count('-')} only on disk, ${count('~')} different`
174
+ return left === 0 ? counts : `${counts}; ${left} left out (--all lists them)`
175
+ }
176
+
177
+ function pruneHint(changes) {
178
+ const count = changes.filter(leftBehind).length
179
+ if (count === 0) return
180
+ const [what, them] = count === 1 ? ['a package', 'it'] : [`${count} packages`, 'them']
181
+ note(`${what} in node_modules/.pnpm that the lockfile no longer installs, as pnpm keeps for a while: \`pnpm prune\` removes ${them}, and so does every install with modulesCacheMaxAge: 0 in pnpm-workspace.yaml`)
182
+ }
183
+
184
+ const UNITS = ['B', 'KiB', 'MiB', 'GiB']
185
+ function size(bytes) {
186
+ const unit = Math.max(0, UNITS.findLastIndex((_, i) => bytes >= 1024 ** i))
187
+ return unit === 0 ? `${bytes} B` : `${(bytes / 1024 ** unit).toFixed(1)} ${UNITS[unit]}`
188
+ }
189
+
190
+ // A refusal says what and where: deptree's or its lockfile reader's,
191
+ // compare's of a side that is no tree it can hold (a link to nothing, say),
192
+ // the system's on a call it names, parseArgs's of an option, or a host
193
+ // deptree takes no version of from what is there. Anything else is a bug,
194
+ // and shows its stack, though Node gave it a code.
195
+ const REFUSALS = [DeptreeError, LockfileError, TomlError, CompareError]
196
+ const refused = (error) => REFUSALS.some((type) => error instanceof type) || typeof error?.syscall === 'string' || String(error?.code).startsWith('ERR_PARSE_ARGS_') || (error instanceof TypeError && error.message.startsWith('host.'))
197
+ function describe(error) {
198
+ if (!refused(error)) return error?.stack ?? String(error)
199
+ const lines = [error.message]
200
+ for (let cause = error.cause; cause instanceof Error; cause = cause.cause) {
201
+ if (!lines.some((text) => text.includes(cause.message))) lines.push(` ${cause.message}`)
202
+ }
203
+ return lines.join('\n')
204
+ }
205
+
206
+ const note = (text) => process.stderr.write(`${text}\n`)
207
+ const fail = (message) => {
208
+ process.stderr.write(message)
209
+ process.exit(2)
210
+ }
211
+
212
+ try {
213
+ process.exitCode = await main(process.argv.slice(2))
214
+ } catch (error) {
215
+ note(`deptree: ${describe(error)}`)
216
+ process.exitCode = 2
217
+ }
package/bin/npmrc.js ADDED
@@ -0,0 +1,21 @@
1
+ // The npm registry's token from ~/.npmrc, for bin/deptree.js alone: the
2
+ // library reads no .npmrc but the project's.
3
+
4
+ import { readFileSync } from 'node:fs'
5
+ import { homedir } from 'node:os'
6
+ import { isAbsolute, join } from 'node:path'
7
+
8
+ // A line of nothing but the registry's token, as `npm login` writes it.
9
+ const TOKEN_LINE = /^\/\/registry\.npmjs\.org\/:_authToken=(npm_[\dA-Za-z]+)$/u
10
+
11
+ // The last such line's, as npm takes the last of a key.
12
+ export const tokenIn = (text) => text.split(/\r?\n/u).map((line) => TOKEN_LINE.exec(line)?.[1]).findLast((token) => token !== undefined)
13
+
14
+ export function userToken(home = homedir()) {
15
+ if (!isAbsolute(home)) return undefined
16
+ try {
17
+ return tokenIn(readFileSync(join(home, '.npmrc'), 'utf8'))
18
+ } catch {
19
+ return undefined
20
+ }
21
+ }
package/cargo.d.ts ADDED
@@ -0,0 +1,221 @@
1
+ import type { NodeType, Vfs } from '@preventive/vfs'
2
+
3
+ export { LockfileError, TomlError } from '@preventive/lockfile/cargo.js'
4
+
5
+ // Where @preventive/upstream caches what it fetches, .crate files among
6
+ // them. Each .crate is fetched through it, and that is the one place
7
+ // anything here touches a filesystem. Before the network, it takes one from
8
+ // cargo's own cache -- each registry's under $CARGO_HOME/registry/cache, or
9
+ // ~/.cargo where that is unset -- where one there has the lockfile's
10
+ // checksum, and writes none of it; then from its own cache, where one is
11
+ // set, which is where it writes each .crate it fetches: setCacheDir() sets
12
+ // the default one, and setCacheDir(false) unsets it. Unset, which it is
13
+ // until set, it writes nothing. The project is read only through the view
14
+ // given as `project`, and the tree built in a Vfs.
15
+ export { setCacheDir } from '@preventive/upstream/npm.js'
16
+
17
+ // The machine cargo would vendor on: `cargo` is the version that vendors,
18
+ // exact, 1.94.0 to 1.99.x, which unpack a .crate alike, those from 1.97 on
19
+ // writing a `$comment` in each .cargo-checksum.json that those before do
20
+ // not; `os` as Node names it -- `linux`, `darwin`. Windows is refused:
21
+ // cargo unpacks and names files otherwise there.
22
+ export interface CargoHost {
23
+ cargo: string
24
+ os: string
25
+ }
26
+
27
+ // A view of the project's root, by paths from `/`: a Vfs, or anything with
28
+ // its readdir, lstat, stat and readFile, such as one of a directory on
29
+ // disk, of which only this is read: Cargo.lock; the Cargo.toml of every
30
+ // path package cargo reads, as below, and of each directory between one and
31
+ // the root, as cargo looks there for a workspace's root; the directories
32
+ // workspace.members takes; and .cargo/config, or else .cargo/config.toml.
33
+ // Each is read as UTF-8, and refused where it is not. A link where cargo
34
+ // looks for members, or at or on the way to any file it reads -- Cargo.lock,
35
+ // the config, a Cargo.toml -- is refused, so that nothing is read from
36
+ // outside the view. Each throws an error
37
+ // whose `code` is ENOENT, ENOTDIR or ELOOP for a path that leads nowhere.
38
+ // Nothing is written to it.
39
+ export interface CargoProject {
40
+ readdir(path: string): string[]
41
+ lstat(path: string): { type: NodeType }
42
+ stat(path: string): { type: NodeType }
43
+ readFile(path: string): Uint8Array
44
+ }
45
+
46
+ // The files `cargo vendor` reads, run at the project's root, which is taken
47
+ // to be the workspace's, with no workspace above it: Cargo.lock; the
48
+ // Cargo.toml of the root and of every other path package cargo reads; and
49
+ // the project's .cargo/config.toml, where there is one.
50
+ //
51
+ // The path packages are the members -- the root's package, each directory
52
+ // workspace.members takes and workspace.exclude does not, and each path
53
+ // dependency of a member that is in the root and not excluded -- and every
54
+ // other package cargo reads from a path: each path dependency of a member
55
+ // that is not one, each [patch] from a path, and each normal or build path
56
+ // dependency of those, which cargo resolves where it resolves their
57
+ // dev-dependencies for members alone. Each inherits from the root's
58
+ // [workspace] where cargo has it inherit: where it is in the root and not
59
+ // excluded, or its package.workspace points to the root.
60
+ //
61
+ // With `lockfile`, they are given as text: `manifests` by directory, `.`
62
+ // for the root and each other's path from it, with no `.`, `..` or empty
63
+ // segment; and `config`, where there is one. They stand for the project, so
64
+ // that a directory none of them is in is taken not to be there, and every
65
+ // one cargo reads has to be given, and none else. Without it, they are read
66
+ // from `project`, and none of them may be given. A refusal names each by
67
+ // its path from the root: `crates/a/Cargo.toml`.
68
+ //
69
+ // Of a workspace, what cargo reads otherwise than this is refused: a glob
70
+ // in workspace.members or default-members with a `**` or a `[`, a path in
71
+ // one of the three lists or in a manifest that is absolute, leads out of
72
+ // the project or has a `..` after a name; a package.workspace that points
73
+ // elsewhere than the root, or a root's at all; a [workspace] between a
74
+ // package and the root. What cargo refuses of one is refused too: a glob
75
+ // that takes nothing, a member with no Cargo.toml or with a [workspace] of
76
+ // its own, a root excluded from its own workspace, a default member that is
77
+ // no member, a path dependency or [patch] that leads to no package or to
78
+ // another of the name. Settings from anywhere else -- a config above the
79
+ // project or in cargo's home, the environment, the command line -- are not
80
+ // read, and are taken to be at their defaults. Of the config, [patch] is
81
+ // read, as cargo resolves with it; `paths` and `include` are refused; the
82
+ // rest is passed over, as it bears on where packages are fetched from and
83
+ // not on what is vendored: `cargo vendor` replaces no source unless told
84
+ // to with --respect-source-config.
85
+ //
86
+ // `vfs` is a Vfs to mount the tree into, at its root, which is taken to be
87
+ // the project's -- it may be `project` too; without one, a new Vfs holds
88
+ // the tree alone. A Vfs that holds a `vendor` at its root, or on macOS a
89
+ // name that is one there, is refused before anything is fetched: cargo
90
+ // would remove what is in it. Nothing there is written over: each
91
+ // directory the tree has is one there or is made, and every file is written
92
+ // where nothing is. The tree is built, and held to every check below,
93
+ // before any of it is written, so a refusal leaves the Vfs as it was.
94
+ export type CargoTreeOptions = CargoTreeGiven | CargoTreeRead
95
+
96
+ export interface CargoTreeGiven {
97
+ lockfile: string
98
+ manifests: Record<string, string> | Map<string, string>
99
+ config?: string
100
+ project?: undefined
101
+ host: CargoHost
102
+ vfs?: Vfs
103
+ }
104
+
105
+ export interface CargoTreeRead {
106
+ lockfile?: undefined
107
+ manifests?: undefined
108
+ config?: undefined
109
+ project: CargoProject
110
+ host: CargoHost
111
+ vfs?: Vfs
112
+ }
113
+
114
+ // What buildCargoTree counts, all of it plain numbers: `packages` the
115
+ // lockfile's; `vendored` those copied into vendor/, each a .crate fetched;
116
+ // `files` and `bytes` what is written, each .cargo-checksum.json among it.
117
+ export interface CargoTreeStats {
118
+ packages: number
119
+ vendored: number
120
+ files: number
121
+ bytes: number
122
+ }
123
+
124
+ // A package in the tree, as an SBOM would list it: `path` is its
125
+ // directory, from the project's root, which is `/` of the Vfs --
126
+ // vendor/<name>, or vendor/<name>-<version> for all but the greatest
127
+ // version of a name; `name`, `version` and `source` the lockfile's;
128
+ // `checksum` the hex sha256 its .crate is held to; `commit` the commit its
129
+ // .cargo_vcs_info.json names, as `cargo package` writes one where it packs
130
+ // from a git checkout, where that is a full commit id and the checkout was
131
+ // not dirty, and undefined elsewhere; `repository` and `homepage` those its
132
+ // Cargo.toml's [package] gives, as cargo packed it, each undefined where it
133
+ // gives none. All of it is the publisher's word, held to no repository.
134
+ export interface CargoInstalled {
135
+ path: string
136
+ name: string
137
+ version: string
138
+ source: string
139
+ checksum: string
140
+ commit: string | undefined
141
+ repository: string | undefined
142
+ homepage: string | undefined
143
+ }
144
+
145
+ // `vfs` is the one given, the tree mounted into it, or a new one.
146
+ // `installed` is each package vendored, in the lockfile's order.
147
+ export interface CargoTree {
148
+ vfs: Vfs
149
+ stats: CargoTreeStats
150
+ installed: CargoInstalled[]
151
+ }
152
+
153
+ // The vendor directory `cargo vendor` makes from the lockfile, with
154
+ // host.cargo and none of its options, in a project with no vendor directory
155
+ // yet: rooted at the project's root, it holds vendor/<directory> for each
156
+ // package of the lockfile but a path one, and nothing else of the project;
157
+ // none at all where every package is a path one. Each package's directory
158
+ // is its name, or `<name>-<version>` for all but the greatest version of
159
+ // that name, by the semver crate's order. What cargo writes or prints
160
+ // beside it -- the config that reads from it, the lockfile again -- is not
161
+ // written.
162
+ //
163
+ // The lockfile is held to the manifests, as cargo would resolve anew one
164
+ // that is out of date with them and vendor what that comes to: every
165
+ // package's, a vendored one's from its .crate, laid over it with
166
+ // @preventive/lockfile/cargo.js's linkCargo, with what that refuses, and
167
+ // each path dependency to the package in the directory it leads to. Every
168
+ // path package of the lockfile has to be one cargo reads, and every member
169
+ // one of the lockfile's.
170
+ //
171
+ // Each .crate is fetched from crates.io and held to the lockfile's checksum,
172
+ // its sha256. It is unpacked as cargo unpacks it into vendor/: every entry
173
+ // under the directory `<name>-<version>`, that directory taken off; of what
174
+ // is under it, anything under a `.git`, a .gitattributes or .gitignore,
175
+ // and a .cargo-ok, passed over, and a directory none but such entries are
176
+ // in not made. Each directory is 0o755, or its own entry's mode where it has
177
+ // one; each file its mode within 0o777; both as a umask of 0o022 leaves
178
+ // them. Each directory then gets a .cargo-checksum.json, 0o644, as cargo
179
+ // writes it: the sha256 of each file and of the .crate, as serde_json
180
+ // writes them.
181
+ //
182
+ // What the archive readers refuse is refused: @preventive/archive's
183
+ // compression.js and tar.js refuse a name with a backslash, a control or
184
+ // formatting character, an empty or `..` segment, or a drive letter, two
185
+ // entries of one name that differ, an entry inside one that is not a
186
+ // directory, a sparse entry -- where cargo would take some of it. What cargo
187
+ // reads otherwise than the readers is refused:
188
+ // a .crate of more than one gzip member, of which cargo reads the first
189
+ // alone; a gzip header CRC or reserved flag; a pax size, which cargo 1.94.0
190
+ // reads otherwise. What cargo refuses or fails on is refused: a .crate that
191
+ // unpacks to more than 512 MiB, or twenty times its size where that is
192
+ // more; an entry not under `<name>-<version>`, an entry not a file or
193
+ // directory, a .crate's own .cargo-checksum.json, which cargo lists and
194
+ // writes over so that it cannot build from it. So is what cargo fails on or
195
+ // reads otherwise as any user but root: a file whose mode lacks the owner's
196
+ // read, which cargo cannot checksum; a directory with anything in it whose
197
+ // mode lacks the owner's read or search, whose files cargo leaves out of
198
+ // .cargo-checksum.json; and one whose mode lacks the owner's write where
199
+ // anything is written into it after its own entry, as .cargo-checksum.json
200
+ // always is into the package's. A directory with nothing in it may have any
201
+ // mode. On macOS, two names in one directory that differ only in case
202
+ // or normalization are refused, as they would be one name there.
203
+ //
204
+ // Packages come from crates.io alone: one from git, which cargo vendor
205
+ // checks out with git, or from another registry, is refused.
206
+ //
207
+ // Nothing is left to a guess: a lockfile or manifest the lockfile reader
208
+ // refuses, a workspace this does not read as cargo reads it, a package from
209
+ // anywhere but crates.io, a check above that fails -- each is refused with a
210
+ // DeptreeError, a LockfileError or a TomlError that says where. A TypeError
211
+ // is thrown for options of the wrong type.
212
+ export function buildCargoTree(options: CargoTreeOptions): Promise<CargoTree>
213
+
214
+ // `where` is what a refusal is about -- `crates/a/Cargo.toml`,
215
+ // `packages["serde 1.0.0 (registry+...)"]`, an entry of a .crate -- or
216
+ // undefined for the call as a whole; the message leads with it. `cause` is
217
+ // what a package beneath refused with, where one did.
218
+ export class DeptreeError extends Error {
219
+ constructor(detail: string, where?: string, options?: { cause?: unknown })
220
+ where: string | undefined
221
+ }
package/cargo.js ADDED
@@ -0,0 +1,6 @@
1
+ // The vendor directory built in memory from a Cargo.lock, as `cargo vendor`
2
+ // makes it; see cargo.d.ts.
3
+ export { buildCargoTree } from './src/cargo/tree.js'
4
+ export { DeptreeError } from './src/error.js'
5
+ export { setCacheDir } from '@preventive/upstream/npm.js'
6
+ export { LockfileError, TomlError } from '@preventive/lockfile/cargo.js'