@sous-io/sous 0.2.3 → 0.2.6
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/README.md +27 -11
- package/bin/run.js +32 -20
- package/docs/markdown/README.md +31 -0
- package/docs/markdown/_sidebar.md +2 -0
- package/docs/markdown/commands.md +27 -1
- package/docs/markdown/config-discovery.md +3 -2
- package/docs/markdown/config-inspection.md +4 -1
- package/docs/markdown/configuration.md +2 -1
- package/docs/markdown/repositories-quickstart.md +4 -1
- package/package.json +1 -1
- package/recipes/core/sous-skills/sous.recipe.yaml +1 -1
- package/src/base-command.ts +76 -8
- package/src/commands/build.ts +3 -80
- package/src/commands/init.ts +269 -0
- package/src/lib/build-preparation.ts +86 -0
- package/src/lib/config-discovery.ts +2 -16
- package/src/lib/project-install.d.mts +31 -0
- package/src/lib/project-install.mjs +175 -0
- package/src/lib/project-scaffold/index.ts +251 -0
- package/src/lib/project-scaffold/templates.ts +230 -0
- package/src/lib/repos/links.ts +3 -1
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `sous init` sets a project up for sous.
|
|
3
|
+
*
|
|
4
|
+
* It writes the `.sous/` directory a project needs (a commented primary config,
|
|
5
|
+
* the starter prompt that config compiles, the two answers files and the
|
|
6
|
+
* sous-managed ignore block) and then runs the first build, which is what
|
|
7
|
+
* seeds the `core` recipe and pins it in the lockfile. A project that is
|
|
8
|
+
* already set up is left exactly as it is.
|
|
9
|
+
*
|
|
10
|
+
* This is the one command that runs BEFORE a project config exists, so it
|
|
11
|
+
* opts out of the config requirement every other command inherits. Discovery
|
|
12
|
+
* still runs, which is how `--sous-dir` and `SOUS_DIR` say where to write, and
|
|
13
|
+
* how a run inside an existing project is noticed.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { Args, Flags } from "@oclif/core";
|
|
18
|
+
import { confirm } from "@inquirer/prompts";
|
|
19
|
+
import { BaseCommand } from "../base-command.js";
|
|
20
|
+
import { prepareRepositoriesForBuild } from "../lib/build-preparation.js";
|
|
21
|
+
import { buildProjectOutputs } from "../lib/build-service.js";
|
|
22
|
+
import {
|
|
23
|
+
CONFIG_FILE_NAMES,
|
|
24
|
+
SOUS_DIR_NAME,
|
|
25
|
+
discoverConfig,
|
|
26
|
+
expandHome,
|
|
27
|
+
resolveConfigFlag,
|
|
28
|
+
} from "../lib/config-discovery.js";
|
|
29
|
+
import { ConfigError } from "../lib/errors.js";
|
|
30
|
+
import { nonInteractiveError } from "../lib/interactive.js";
|
|
31
|
+
import { subscriptionServiceFor } from "../lib/repos/subscription-service.js";
|
|
32
|
+
import {
|
|
33
|
+
PROJECT_CONFIG_FORMATS,
|
|
34
|
+
STARTER_OUTPUT_NAME,
|
|
35
|
+
STARTER_PROMPT_RELATIVE_PATH,
|
|
36
|
+
scaffoldProject,
|
|
37
|
+
sousDirFor,
|
|
38
|
+
type ProjectConfigFormat,
|
|
39
|
+
} from "../lib/project-scaffold/index.js";
|
|
40
|
+
import { SOUS_VERSION } from "../lib/settings.js";
|
|
41
|
+
import { confirmationFlag } from "../utils/flags.js";
|
|
42
|
+
import {
|
|
43
|
+
blankLine,
|
|
44
|
+
dryRunNotice,
|
|
45
|
+
footer,
|
|
46
|
+
heading,
|
|
47
|
+
log,
|
|
48
|
+
paragraph,
|
|
49
|
+
section,
|
|
50
|
+
showCommandVars,
|
|
51
|
+
showVariables,
|
|
52
|
+
warning,
|
|
53
|
+
} from "../utils/formatting.js";
|
|
54
|
+
|
|
55
|
+
export default class Init extends BaseCommand {
|
|
56
|
+
static description =
|
|
57
|
+
"Set a project up for sous: write its .sous/ directory, then run the first build";
|
|
58
|
+
|
|
59
|
+
/** This command creates the config; finding none is its normal case. */
|
|
60
|
+
static override requiresConfig = false;
|
|
61
|
+
|
|
62
|
+
static examples = [
|
|
63
|
+
"<%= config.bin %> init",
|
|
64
|
+
"<%= config.bin %> init ./my-project",
|
|
65
|
+
"<%= config.bin %> init --format json",
|
|
66
|
+
"<%= config.bin %> init --name 'My Project' --no-build",
|
|
67
|
+
"<%= config.bin %> init --dry-run",
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
static args = {
|
|
71
|
+
directory: Args.string({
|
|
72
|
+
description: "Project directory to set up (defaults to the current one)",
|
|
73
|
+
required: false,
|
|
74
|
+
}),
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
static flags = {
|
|
78
|
+
...BaseCommand.baseFlags,
|
|
79
|
+
format: Flags.string({
|
|
80
|
+
description: "Format of the primary config to write",
|
|
81
|
+
options: [...PROJECT_CONFIG_FORMATS],
|
|
82
|
+
default: PROJECT_CONFIG_FORMATS[0],
|
|
83
|
+
}),
|
|
84
|
+
name: Flags.string({
|
|
85
|
+
description: "Display name for the project (defaults to the directory's own name)",
|
|
86
|
+
}),
|
|
87
|
+
// The one question this command can ask: whether to set up a project
|
|
88
|
+
// inside another one.
|
|
89
|
+
yes: confirmationFlag(),
|
|
90
|
+
"dry-run": Flags.boolean({
|
|
91
|
+
description: "Print the files that would be written without writing them",
|
|
92
|
+
default: false,
|
|
93
|
+
}),
|
|
94
|
+
"no-build": Flags.boolean({
|
|
95
|
+
description: "Write the setup without running the first build",
|
|
96
|
+
default: false,
|
|
97
|
+
}),
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
async run(): Promise<void> {
|
|
101
|
+
const { args, flags } = await this.parse(Init);
|
|
102
|
+
const dryRun = flags["dry-run"];
|
|
103
|
+
const format = flags.format as ProjectConfigFormat;
|
|
104
|
+
|
|
105
|
+
const sousDir = this.targetSousDir(args.directory);
|
|
106
|
+
const projectRoot = path.dirname(sousDir);
|
|
107
|
+
|
|
108
|
+
showCommandVars({
|
|
109
|
+
Directory: projectRoot,
|
|
110
|
+
Config: path.join(sousDir, `sous.config.${format}`),
|
|
111
|
+
Name: flags.name ?? "(from the directory name)",
|
|
112
|
+
"Dry Run": dryRun,
|
|
113
|
+
Build: !dryRun && !flags["no-build"],
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
await this.confirmNesting(projectRoot, flags.yes);
|
|
117
|
+
|
|
118
|
+
section("Setting up the project");
|
|
119
|
+
|
|
120
|
+
const result = await scaffoldProject({
|
|
121
|
+
sousDir,
|
|
122
|
+
format,
|
|
123
|
+
name: flags.name,
|
|
124
|
+
dryRun,
|
|
125
|
+
sousVersion: SOUS_VERSION,
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
for (const file of result.files) {
|
|
129
|
+
if (result.dryRun) dryRunNotice(`would write ${file}`);
|
|
130
|
+
else log(` wrote ${file}`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (result.dryRun) {
|
|
134
|
+
blankLine();
|
|
135
|
+
dryRunNotice("Nothing was written. Run the same command without '--dry-run' to set the project up.");
|
|
136
|
+
footer();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!flags["no-build"]) {
|
|
141
|
+
await this.buildProject(result.configPath);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
section("What was set up");
|
|
145
|
+
showVariables([
|
|
146
|
+
{ label: "Config", value: result.configPath },
|
|
147
|
+
{ label: "Prompt source", value: path.join(sousDir, STARTER_PROMPT_RELATIVE_PATH) },
|
|
148
|
+
{ label: "Compiled to", value: path.join(projectRoot, STARTER_OUTPUT_NAME) },
|
|
149
|
+
{ label: "Skills", value: path.join(projectRoot, ".claude", "skills") },
|
|
150
|
+
{ label: "Shared answers", value: path.join(sousDir, ".env"), detail: "committed" },
|
|
151
|
+
{
|
|
152
|
+
label: "Local answers",
|
|
153
|
+
value: path.join(sousDir, ".env.local"),
|
|
154
|
+
detail: "gitignored; .env.local.example shows the layout",
|
|
155
|
+
},
|
|
156
|
+
]);
|
|
157
|
+
|
|
158
|
+
blankLine();
|
|
159
|
+
paragraph(
|
|
160
|
+
` ${STARTER_OUTPUT_NAME} and the skills directory are build output, compiled from the ` +
|
|
161
|
+
`prompt source and from the recipes this project subscribes to; a build recompiles ` +
|
|
162
|
+
`them. The config explains each of its blocks in its own comments.`
|
|
163
|
+
);
|
|
164
|
+
|
|
165
|
+
footer();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Where the `.sous/` directory goes. A directory argument wins; otherwise the
|
|
170
|
+
* config-locating flags say where the project is, and otherwise it is the
|
|
171
|
+
* working directory. A path that already names a `.sous/` directory, or a
|
|
172
|
+
* config file inside one, is honored as such.
|
|
173
|
+
*/
|
|
174
|
+
private targetSousDir(directory: string | undefined): string {
|
|
175
|
+
if (directory !== undefined) {
|
|
176
|
+
return sousDirFor(path.resolve(this.configLocator.cwd, expandHome(directory)));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const primary = this.configLocator.primary;
|
|
180
|
+
if (primary === undefined) return sousDirFor(this.configLocator.cwd);
|
|
181
|
+
|
|
182
|
+
const value = primary.value;
|
|
183
|
+
if (path.basename(value) === SOUS_DIR_NAME) return value;
|
|
184
|
+
if ((CONFIG_FILE_NAMES as readonly string[]).includes(path.basename(value))) {
|
|
185
|
+
return path.dirname(value);
|
|
186
|
+
}
|
|
187
|
+
return sousDirFor(value);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* A project set up inside another one is a real choice, not a mistake sous
|
|
192
|
+
* should prevent: a subproject may want its own instructions. So when a walk
|
|
193
|
+
* up from the target finds a config in a parent directory, the facts are
|
|
194
|
+
* stated and the question is asked once; `--yes` answers it ahead of time,
|
|
195
|
+
* and a run with no terminal fails naming that flag.
|
|
196
|
+
*
|
|
197
|
+
* The target's own `.sous/` holding a config is a different case, refused
|
|
198
|
+
* outright by the scaffold.
|
|
199
|
+
*/
|
|
200
|
+
private async confirmNesting(projectRoot: string, confirmed: boolean): Promise<void> {
|
|
201
|
+
const enclosing = discoverConfig(projectRoot);
|
|
202
|
+
if (enclosing === null || path.dirname(enclosing.sousDir) === projectRoot) return;
|
|
203
|
+
|
|
204
|
+
const enclosingRoot = path.dirname(enclosing.sousDir);
|
|
205
|
+
|
|
206
|
+
warning(
|
|
207
|
+
`${projectRoot} is inside a project that is already set up for sous.\n` +
|
|
208
|
+
` The enclosing project's config is ${enclosing.configPath}.\n` +
|
|
209
|
+
` Setting this directory up too gives it a config of its own: commands run ` +
|
|
210
|
+
`here will find this one, and commands run from ${enclosingRoot} will keep ` +
|
|
211
|
+
`finding the other.`
|
|
212
|
+
);
|
|
213
|
+
|
|
214
|
+
if (confirmed) return;
|
|
215
|
+
|
|
216
|
+
if (!this.interactive) {
|
|
217
|
+
throw nonInteractiveError({
|
|
218
|
+
prompt: `whether to set up ${projectRoot} inside the project at ${enclosingRoot}`,
|
|
219
|
+
remedy: "pass --yes (also -y, --force) to set it up anyway",
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
blankLine();
|
|
224
|
+
const proceed = await confirm({
|
|
225
|
+
message: `Set up ${projectRoot} as a project of its own?`,
|
|
226
|
+
default: false,
|
|
227
|
+
});
|
|
228
|
+
if (!proceed) {
|
|
229
|
+
throw new ConfigError(
|
|
230
|
+
`Nothing was written. Run 'sous init' from a directory outside ${enclosingRoot}, ` +
|
|
231
|
+
`or pass --yes to set this one up anyway.`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Adopts the config just written and builds the project with it, in the
|
|
238
|
+
* same two steps `sous build` takes: the repositories are prepared (which
|
|
239
|
+
* seeds the core recipe into the store and pins it in the lockfile), then
|
|
240
|
+
* the outputs are compiled.
|
|
241
|
+
*
|
|
242
|
+
* @param configPath - The primary config the scaffold wrote.
|
|
243
|
+
*/
|
|
244
|
+
private async buildProject(configPath: string): Promise<void> {
|
|
245
|
+
await this.adoptConfig(
|
|
246
|
+
resolveConfigFlag(configPath, this.configLocator.cwd, this.configLocator.confDirOverride)
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
await prepareRepositoriesForBuild(
|
|
250
|
+
subscriptionServiceFor({
|
|
251
|
+
configContext: this.configContext,
|
|
252
|
+
settings: this.settings,
|
|
253
|
+
shellEnv: this.shellEnv,
|
|
254
|
+
})
|
|
255
|
+
);
|
|
256
|
+
|
|
257
|
+
heading("Building the project");
|
|
258
|
+
|
|
259
|
+
const succeeded = await buildProjectOutputs(this.settings, this.configContext);
|
|
260
|
+
|
|
261
|
+
if (!succeeded) {
|
|
262
|
+
throw new ConfigError(
|
|
263
|
+
`The project is set up, but the first build failed, so its outputs may be ` +
|
|
264
|
+
`incomplete. Everything 'sous init' wrote is in place; fix what the build ` +
|
|
265
|
+
`reported above and run 'sous build' again.`
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The step that runs before a project's outputs are compiled, and what it says
|
|
3
|
+
* while it runs. `sous build` runs it on every build, and `sous init` runs it
|
|
4
|
+
* for the first build of a project it has just set up; both must say the same
|
|
5
|
+
* things about the same events, so the reporting lives here rather than in
|
|
6
|
+
* either command.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { SubscriptionService } from "./repos/subscription-service.js";
|
|
10
|
+
import { blankLine, footer, heading, paragraph, warning } from "../utils/formatting.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Gets this project's recipes ready to compile: restores whatever the store is
|
|
14
|
+
* missing (a fresh clone, or a collected store) and then asks upstream for the
|
|
15
|
+
* repositories that prefer a newer in-range version.
|
|
16
|
+
*
|
|
17
|
+
* Restoring asks nothing and decides nothing; it fetches exactly what the
|
|
18
|
+
* lockfile pins. An upstream check that fails is reported and then ignored,
|
|
19
|
+
* because a build must not depend on the network being up.
|
|
20
|
+
*
|
|
21
|
+
* @param repositories - The subscription service for this project.
|
|
22
|
+
*/
|
|
23
|
+
export async function prepareRepositoriesForBuild(
|
|
24
|
+
repositories: SubscriptionService
|
|
25
|
+
): Promise<void> {
|
|
26
|
+
const needsRestore = repositories.needsRestore();
|
|
27
|
+
if (needsRestore) {
|
|
28
|
+
heading("Restoring recipes");
|
|
29
|
+
blankLine();
|
|
30
|
+
paragraph(
|
|
31
|
+
"This project's lockfile pins recipes that are not in the store on this " +
|
|
32
|
+
"machine, so they are being fetched at exactly the versions it records."
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const { seed, subscriptions, restored, upstream } =
|
|
37
|
+
await repositories.prepareForBuild();
|
|
38
|
+
|
|
39
|
+
// Seeding the packaged core recipe is silent when it works, which is almost
|
|
40
|
+
// always; it is only worth a word when it could not be done at all.
|
|
41
|
+
if (seed.skippedBecause !== undefined) warning(seed.skippedBecause);
|
|
42
|
+
|
|
43
|
+
// A subscription the lockfile did not pin yet has just been pinned. That is
|
|
44
|
+
// a change to a committed file, so it is always announced.
|
|
45
|
+
if (subscriptions.added.length > 0 || subscriptions.moved.length > 0) {
|
|
46
|
+
heading("Locking subscribed recipes");
|
|
47
|
+
blankLine();
|
|
48
|
+
for (const entry of subscriptions.added) {
|
|
49
|
+
paragraph(` pinned: ${entry.key} at version ${entry.version}.`);
|
|
50
|
+
}
|
|
51
|
+
for (const change of subscriptions.moved) {
|
|
52
|
+
paragraph(` ${change.key} moved from version ${change.from} to version ${change.to}.`);
|
|
53
|
+
}
|
|
54
|
+
blankLine();
|
|
55
|
+
paragraph(
|
|
56
|
+
"The lockfile has been updated. Commit it, so everyone building this project " +
|
|
57
|
+
"gets exactly these versions."
|
|
58
|
+
);
|
|
59
|
+
footer();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
for (const failure of subscriptions.failed) {
|
|
63
|
+
warning(
|
|
64
|
+
`Sous could not work out which version of '${failure.key}' to use, so nothing ` +
|
|
65
|
+
`from it was compiled.\n${failure.reason}`
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (restored !== undefined && restored.restored.length > 0) {
|
|
70
|
+
blankLine();
|
|
71
|
+
for (const key of restored.restored) paragraph(` restored: ${key}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
for (const change of upstream.updated) {
|
|
75
|
+
paragraph(` ${change.key} moved from ${change.from} to ${change.to}.`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
for (const failure of upstream.failed) {
|
|
79
|
+
warning(
|
|
80
|
+
`Sous could not check the repository '${failure.repo}' for a newer version, so ` +
|
|
81
|
+
`this build uses the versions it already had.\n${failure.reason}`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (needsRestore) footer();
|
|
86
|
+
}
|
|
@@ -371,22 +371,8 @@ export function formatNotFoundMessage(startDir: string = process.cwd()): string
|
|
|
371
371
|
checked + more,
|
|
372
372
|
"",
|
|
373
373
|
" To fix this, either:",
|
|
374
|
-
` 1.
|
|
374
|
+
` 1. Set the project up: run 'sous init' in its root directory, which writes`,
|
|
375
|
+
` ${SOUS_DIR_NAME}/${CONFIG_FILE_NAMES[0]} and everything else a first build needs, or`,
|
|
375
376
|
" 2. Pass the config explicitly: sous <command> --config <path>",
|
|
376
|
-
"",
|
|
377
|
-
` A minimal ${CONFIG_FILE_NAMES[0]}:`,
|
|
378
|
-
"",
|
|
379
|
-
" export const config = {",
|
|
380
|
-
' name: "My Project",',
|
|
381
|
-
' _vars: { projectRoot: "${sousDir}/.." },',
|
|
382
|
-
" compilation: {",
|
|
383
|
-
" targets: [",
|
|
384
|
-
" {",
|
|
385
|
-
' entryPoint: "${sousDir}/AGENTS.md",',
|
|
386
|
-
' outputs: [{ destinationFile: "${projectRoot}/AGENTS.md" }],',
|
|
387
|
-
" },",
|
|
388
|
-
" ],",
|
|
389
|
-
" },",
|
|
390
|
-
" };",
|
|
391
377
|
].join("\n");
|
|
392
378
|
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for project-install.mjs, which is plain JavaScript because it runs
|
|
3
|
+
* before tsx is registered. Keep the two in step by hand.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const PACKAGE_NAME: "@sous-io/sous";
|
|
7
|
+
export const NO_DELEGATE_ENV: "SOUS_NO_DELEGATE";
|
|
8
|
+
export const DEBUG_ENV: "SOUS_DEBUG";
|
|
9
|
+
|
|
10
|
+
export type ProjectInstall =
|
|
11
|
+
| { same: true; root: string }
|
|
12
|
+
| { same: false; root: string; version: string; bin: string };
|
|
13
|
+
|
|
14
|
+
export type HandoffPlan =
|
|
15
|
+
| { kind: "run-self" }
|
|
16
|
+
| { kind: "hand-off"; install: Extract<ProjectInstall, { same: false }>; notice: string | undefined };
|
|
17
|
+
|
|
18
|
+
export function isEnvFlagOn(value: string | undefined): boolean;
|
|
19
|
+
export function binEntryOf(pkg: unknown): string | undefined;
|
|
20
|
+
export function findProjectInstall(startDir: string, ownRoot: string): ProjectInstall | undefined;
|
|
21
|
+
export function planHandoff(input: {
|
|
22
|
+
cwd: string;
|
|
23
|
+
ownRoot: string;
|
|
24
|
+
env: Record<string, string | undefined>;
|
|
25
|
+
}): HandoffPlan;
|
|
26
|
+
export function handOffToProjectInstall(input: {
|
|
27
|
+
ownRoot: string;
|
|
28
|
+
cwd?: string;
|
|
29
|
+
env?: Record<string, string | undefined>;
|
|
30
|
+
stderr?: { write(chunk: string): unknown };
|
|
31
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hand-off from the sous that was invoked to the sous a project installs.
|
|
3
|
+
*
|
|
4
|
+
* A global install is a convenience launcher; a project's own `@sous-io/sous`
|
|
5
|
+
* dependency is the version its templates and its lockfile were written
|
|
6
|
+
* against, and it is the one that has to do the work (the implicit `core`
|
|
7
|
+
* subscription asks for exactly the running version, so two versions taking
|
|
8
|
+
* turns in one project rewrite the committed lockfile back and forth). The
|
|
9
|
+
* published bin (bin/run.js) calls `handOffToProjectInstall` before it loads
|
|
10
|
+
* anything else, and when a project copy is found, imports that copy's own bin
|
|
11
|
+
* in this same process and lets it run the command.
|
|
12
|
+
*
|
|
13
|
+
* Plain JavaScript ESM, no TypeScript syntax: this runs BEFORE tsx is
|
|
14
|
+
* registered, under bare Node, because the whole point is to load none of the
|
|
15
|
+
* invoked install's code when another copy should run. It ships to npm via the
|
|
16
|
+
* package.json "files": "src" allowlist, like the config kernel next to it.
|
|
17
|
+
*
|
|
18
|
+
* The rules, all of them here and nowhere else:
|
|
19
|
+
* - The lookup walks up from the working directory looking for
|
|
20
|
+
* `node_modules/@sous-io/sous`, the way Node resolves a package, so a copy
|
|
21
|
+
* hoisted to a monorepo root is found from any package inside it.
|
|
22
|
+
* - A copy whose real path is the invoked install's own root is "self", and
|
|
23
|
+
* self never hands off; that is what stops the project's copy from
|
|
24
|
+
* handing off to itself after the global copy handed off to it.
|
|
25
|
+
* - The copy's bin is read from its package.json `bin` field, never assumed,
|
|
26
|
+
* so an older layout (the bin was once called `xcv`) still works.
|
|
27
|
+
* - Anything unreadable or ambiguous means "run the copy that was invoked".
|
|
28
|
+
* A hand-off is a convenience; a refusal to run is not.
|
|
29
|
+
* - `SOUS_NO_DELEGATE` (anything but 0/false/no/off) runs the invoked copy.
|
|
30
|
+
* - The notice goes to stderr, so piped stdout stays clean, and only when
|
|
31
|
+
* the two versions differ; `SOUS_DEBUG` prints it on every hand-off.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import fs from "node:fs";
|
|
35
|
+
import path from "node:path";
|
|
36
|
+
import { pathToFileURL } from "node:url";
|
|
37
|
+
|
|
38
|
+
/** The npm package name a project copy is looked up under. */
|
|
39
|
+
export const PACKAGE_NAME = "@sous-io/sous";
|
|
40
|
+
|
|
41
|
+
/** The environment variable that keeps the invoked copy running. */
|
|
42
|
+
export const NO_DELEGATE_ENV = "SOUS_NO_DELEGATE";
|
|
43
|
+
|
|
44
|
+
/** The environment variable that makes every hand-off announce itself. */
|
|
45
|
+
export const DEBUG_ENV = "SOUS_DEBUG";
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Whether an on/off environment variable is on: set to anything but an empty
|
|
49
|
+
* string, `0`, `false`, `no` or `off` (case-insensitive, whitespace trimmed).
|
|
50
|
+
* The same reading `SOUS_DEBUG` has always had.
|
|
51
|
+
*/
|
|
52
|
+
export function isEnvFlagOn(value) {
|
|
53
|
+
return !["", "0", "false", "no", "off"].includes((value ?? "").trim().toLowerCase());
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Reads a package.json, returning the parsed object or undefined for a file
|
|
58
|
+
* that is missing, unreadable or not JSON.
|
|
59
|
+
*/
|
|
60
|
+
function readPackageJson(dir) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
|
|
63
|
+
} catch {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Works out which file a package's `bin` field names for the `sous` command,
|
|
70
|
+
* relative to the package root, or undefined when it cannot be told: no field,
|
|
71
|
+
* an object naming neither `sous` nor `xcv` with more than one entry, or a
|
|
72
|
+
* value that is not a string.
|
|
73
|
+
*/
|
|
74
|
+
export function binEntryOf(pkg) {
|
|
75
|
+
const bin = pkg?.bin;
|
|
76
|
+
if (typeof bin === "string") return bin;
|
|
77
|
+
if (!bin || typeof bin !== "object") return undefined;
|
|
78
|
+
const named = bin.sous ?? bin.xcv;
|
|
79
|
+
if (typeof named === "string") return named;
|
|
80
|
+
const entries = Object.values(bin);
|
|
81
|
+
if (entries.length === 1 && typeof entries[0] === "string") return entries[0];
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Looks up from `startDir` for a project install of the package.
|
|
87
|
+
*
|
|
88
|
+
* Returns undefined when no ancestor holds `node_modules/@sous-io/sous`, or
|
|
89
|
+
* when the first one found is not usable (its package.json does not name the
|
|
90
|
+
* package, or its bin cannot be determined or does not exist). Returns
|
|
91
|
+
* `{ same: true, root }` when the first copy found IS the invoked install
|
|
92
|
+
* (`ownRoot`), compared by real path, and otherwise `{ same: false, root,
|
|
93
|
+
* version, bin }` with `bin` as an absolute path.
|
|
94
|
+
*
|
|
95
|
+
* The walk stops at the first copy, usable or not: a broken copy nearer the
|
|
96
|
+
* working directory is what `npx` would run too, and skipping past it to an
|
|
97
|
+
* older one further up would be a guess.
|
|
98
|
+
*/
|
|
99
|
+
export function findProjectInstall(startDir, ownRoot) {
|
|
100
|
+
let dir = path.resolve(startDir);
|
|
101
|
+
for (;;) {
|
|
102
|
+
const candidate = path.join(dir, "node_modules", ...PACKAGE_NAME.split("/"));
|
|
103
|
+
if (fs.existsSync(path.join(candidate, "package.json"))) {
|
|
104
|
+
return describeInstall(candidate, ownRoot);
|
|
105
|
+
}
|
|
106
|
+
const parent = path.dirname(dir);
|
|
107
|
+
if (parent === dir) return undefined;
|
|
108
|
+
dir = parent;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function realpathOr(p) {
|
|
113
|
+
try {
|
|
114
|
+
return fs.realpathSync(p);
|
|
115
|
+
} catch {
|
|
116
|
+
return path.resolve(p);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function describeInstall(candidate, ownRoot) {
|
|
121
|
+
const root = realpathOr(candidate);
|
|
122
|
+
if (root === realpathOr(ownRoot)) return { same: true, root };
|
|
123
|
+
const pkg = readPackageJson(root);
|
|
124
|
+
if (!pkg || pkg.name !== PACKAGE_NAME) return undefined;
|
|
125
|
+
const entry = binEntryOf(pkg);
|
|
126
|
+
if (!entry) return undefined;
|
|
127
|
+
const bin = path.resolve(root, entry);
|
|
128
|
+
if (!fs.existsSync(bin)) return undefined;
|
|
129
|
+
return { same: false, root, version: typeof pkg.version === "string" ? pkg.version : "unknown", bin };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Decides what the invoked install should do, without doing it.
|
|
134
|
+
*
|
|
135
|
+
* Returns `{ kind: "run-self" }` when the invoked copy runs the command, or
|
|
136
|
+
* `{ kind: "hand-off", install, notice }` naming the project copy to import
|
|
137
|
+
* and the sentence to print on stderr first (undefined when nothing is said).
|
|
138
|
+
*/
|
|
139
|
+
export function planHandoff({ cwd, ownRoot, env }) {
|
|
140
|
+
if (isEnvFlagOn(env[NO_DELEGATE_ENV])) return { kind: "run-self" };
|
|
141
|
+
const install = findProjectInstall(cwd, ownRoot);
|
|
142
|
+
if (!install || install.same) return { kind: "run-self" };
|
|
143
|
+
|
|
144
|
+
const ownPkg = readPackageJson(ownRoot);
|
|
145
|
+
const ownVersion = typeof ownPkg?.version === "string" ? ownPkg.version : "unknown";
|
|
146
|
+
const differ = ownVersion !== install.version;
|
|
147
|
+
let notice;
|
|
148
|
+
if (differ) {
|
|
149
|
+
notice =
|
|
150
|
+
`Running the project's own sous ${install.version} from ${install.root} instead of the ` +
|
|
151
|
+
`sous ${ownVersion} you invoked; set ${NO_DELEGATE_ENV}=1 to run the one you invoked.`;
|
|
152
|
+
} else if (isEnvFlagOn(env[DEBUG_ENV])) {
|
|
153
|
+
notice = `Running the project's own sous ${install.version} from ${install.root}.`;
|
|
154
|
+
}
|
|
155
|
+
return { kind: "hand-off", install, notice };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Hands the current invocation to the project's copy when there is one to hand
|
|
160
|
+
* it to. Resolves true after that copy's bin has run (it reads the same
|
|
161
|
+
* process.argv and sets the same exit code), and false, having loaded nothing,
|
|
162
|
+
* when the invoked copy should run the command itself.
|
|
163
|
+
*/
|
|
164
|
+
export async function handOffToProjectInstall({
|
|
165
|
+
ownRoot,
|
|
166
|
+
cwd = process.cwd(),
|
|
167
|
+
env = process.env,
|
|
168
|
+
stderr = process.stderr,
|
|
169
|
+
}) {
|
|
170
|
+
const plan = planHandoff({ cwd, ownRoot, env });
|
|
171
|
+
if (plan.kind !== "hand-off") return false;
|
|
172
|
+
if (plan.notice) stderr.write(`${plan.notice}\n`);
|
|
173
|
+
await import(pathToFileURL(plan.install.bin).href);
|
|
174
|
+
return true;
|
|
175
|
+
}
|