@sous-io/sous 0.2.36 → 1.0.1

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.
Files changed (244) hide show
  1. package/README.md +14 -256
  2. package/dist/bin.js +11 -0
  3. package/dist/sous.js +1093 -0
  4. package/docs/markdown/README.md +5 -4
  5. package/docs/markdown/_sidebar.md +21 -1
  6. package/docs/markdown/commands.md +294 -431
  7. package/docs/markdown/config-discovery.md +25 -14
  8. package/docs/markdown/config-inspection.md +53 -31
  9. package/docs/markdown/config-layers.md +168 -66
  10. package/docs/markdown/config-variables.md +44 -11
  11. package/docs/markdown/configuration.md +104 -17
  12. package/docs/markdown/design-principles.md +4 -1
  13. package/docs/markdown/repositories-authoring.md +30 -0
  14. package/docs/markdown/repositories-consuming.md +72 -14
  15. package/docs/markdown/repositories-file-formats.md +31 -13
  16. package/docs/markdown/repositories-providers.md +48 -57
  17. package/docs/markdown/repositories-quickstart.md +3 -2
  18. package/docs/markdown/repositories-troubleshooting.md +27 -1
  19. package/docs/markdown/repositories-variables.md +6 -1
  20. package/docs/markdown/repositories.md +18 -8
  21. package/package.json +48 -107
  22. package/recipes/core/sous-skills/skills/about-liquid-templates/SKILL.tpl.md +4 -6
  23. package/recipes/core/sous-skills/skills/about-liquid-templates/references/liquid-filters.tpl.md +2 -0
  24. package/recipes/core/sous-skills/skills/about-sous/SKILL.tpl.md +10 -9
  25. package/recipes/core/sous-skills/skills/about-sous-configuration/SKILL.tpl.md +35 -14
  26. package/recipes/core/sous-skills/skills/about-sous-recipes/SKILL.tpl.md +51 -20
  27. package/recipes/core/sous-skills/sous.recipe.yaml +1 -1
  28. package/sous.config.schema.json +351 -132
  29. package/bin/run.js +0 -51
  30. package/src/base-command.ts +0 -457
  31. package/src/commands/build.ts +0 -181
  32. package/src/commands/clear.ts +0 -79
  33. package/src/commands/compile.ts +0 -155
  34. package/src/commands/config/get.ts +0 -110
  35. package/src/commands/config/show.ts +0 -32
  36. package/src/commands/config/validate.ts +0 -53
  37. package/src/commands/help.ts +0 -46
  38. package/src/commands/init.ts +0 -289
  39. package/src/commands/launch.ts +0 -139
  40. package/src/commands/lock/rebuild.ts +0 -239
  41. package/src/commands/lock/show.ts +0 -115
  42. package/src/commands/namespace/list.ts +0 -138
  43. package/src/commands/namespace/show.ts +0 -130
  44. package/src/commands/prune.ts +0 -43
  45. package/src/commands/recipe/list.ts +0 -112
  46. package/src/commands/recipe/show.ts +0 -439
  47. package/src/commands/repo/add.ts +0 -145
  48. package/src/commands/repo/contribute.ts +0 -604
  49. package/src/commands/repo/gc.ts +0 -173
  50. package/src/commands/repo/init.ts +0 -136
  51. package/src/commands/repo/link.ts +0 -899
  52. package/src/commands/repo/list.ts +0 -236
  53. package/src/commands/repo/release.ts +0 -685
  54. package/src/commands/repo/remove.ts +0 -194
  55. package/src/commands/repo/search.ts +0 -243
  56. package/src/commands/repo/submit.ts +0 -341
  57. package/src/commands/repo/unlink.ts +0 -461
  58. package/src/commands/subscription/add.ts +0 -286
  59. package/src/commands/subscription/list.ts +0 -208
  60. package/src/commands/subscription/remove.ts +0 -182
  61. package/src/commands/subscription/update.ts +0 -216
  62. package/src/commands/update.ts +0 -178
  63. package/src/commands/vars/ask.ts +0 -417
  64. package/src/commands/vars/index.ts +0 -79
  65. package/src/commands/vars/list.ts +0 -67
  66. package/src/commands/vars/show.ts +0 -77
  67. package/src/config-command.ts +0 -30
  68. package/src/lib/build-preparation.ts +0 -128
  69. package/src/lib/build-service.ts +0 -580
  70. package/src/lib/config-discovery.ts +0 -378
  71. package/src/lib/config-inspect.ts +0 -145
  72. package/src/lib/config-kernel.mjs +0 -379
  73. package/src/lib/config-schema.ts +0 -401
  74. package/src/lib/env-file.ts +0 -328
  75. package/src/lib/env-local.ts +0 -212
  76. package/src/lib/errors.ts +0 -32
  77. package/src/lib/glob-pattern.ts +0 -24
  78. package/src/lib/include-resolver.ts +0 -523
  79. package/src/lib/interactive.ts +0 -165
  80. package/src/lib/markdown-compiler.ts +0 -947
  81. package/src/lib/package-info.ts +0 -25
  82. package/src/lib/pid-service.ts +0 -99
  83. package/src/lib/project-install.d.mts +0 -44
  84. package/src/lib/project-install.mjs +0 -234
  85. package/src/lib/project-scaffold/index.ts +0 -332
  86. package/src/lib/project-scaffold/templates.ts +0 -240
  87. package/src/lib/repos/catalog-display.ts +0 -215
  88. package/src/lib/repos/catalog-inputs.ts +0 -288
  89. package/src/lib/repos/catalog.ts +0 -842
  90. package/src/lib/repos/contribute.ts +0 -452
  91. package/src/lib/repos/core-recipe.ts +0 -105
  92. package/src/lib/repos/declarations.ts +0 -187
  93. package/src/lib/repos/defaults.ts +0 -175
  94. package/src/lib/repos/formats/common.ts +0 -440
  95. package/src/lib/repos/formats/index-file.ts +0 -253
  96. package/src/lib/repos/formats/links-map.ts +0 -98
  97. package/src/lib/repos/formats/lockfile.ts +0 -169
  98. package/src/lib/repos/formats/patterns.ts +0 -57
  99. package/src/lib/repos/formats/recipe-manifest.ts +0 -205
  100. package/src/lib/repos/formats/repo-manifest.ts +0 -97
  101. package/src/lib/repos/formats/store-entry.ts +0 -84
  102. package/src/lib/repos/formats/variable-definition.ts +0 -268
  103. package/src/lib/repos/freshness.ts +0 -264
  104. package/src/lib/repos/git-clone.ts +0 -850
  105. package/src/lib/repos/identity.ts +0 -89
  106. package/src/lib/repos/index.ts +0 -57
  107. package/src/lib/repos/links.ts +0 -356
  108. package/src/lib/repos/load-manifest.ts +0 -237
  109. package/src/lib/repos/lock-service.ts +0 -454
  110. package/src/lib/repos/locked-namespace-resolver.ts +0 -232
  111. package/src/lib/repos/locked-recipe-lookup.ts +0 -123
  112. package/src/lib/repos/locked-recipes.ts +0 -254
  113. package/src/lib/repos/managed-layer.ts +0 -422
  114. package/src/lib/repos/memories-hash-name.ts +0 -33
  115. package/src/lib/repos/namespace-resolver.ts +0 -527
  116. package/src/lib/repos/providers/base.ts +0 -268
  117. package/src/lib/repos/providers/git.ts +0 -237
  118. package/src/lib/repos/providers/github.ts +0 -589
  119. package/src/lib/repos/providers/gitlab.ts +0 -332
  120. package/src/lib/repos/providers/http.ts +0 -128
  121. package/src/lib/repos/providers/index-cache.ts +0 -421
  122. package/src/lib/repos/providers/index.ts +0 -106
  123. package/src/lib/repos/providers/local.ts +0 -391
  124. package/src/lib/repos/providers/provider.ts +0 -615
  125. package/src/lib/repos/recipe-config-layers.ts +0 -316
  126. package/src/lib/repos/recipe-key-matcher.ts +0 -62
  127. package/src/lib/repos/recipe-memories.ts +0 -178
  128. package/src/lib/repos/recipe-targets.ts +0 -236
  129. package/src/lib/repos/ref-search.ts +0 -46
  130. package/src/lib/repos/release/bump.ts +0 -161
  131. package/src/lib/repos/release/changelog.ts +0 -461
  132. package/src/lib/repos/release/git-state.ts +0 -460
  133. package/src/lib/repos/release/index-builder.ts +0 -1108
  134. package/src/lib/repos/release/index.ts +0 -19
  135. package/src/lib/repos/release/plan.ts +0 -521
  136. package/src/lib/repos/release/settle.ts +0 -154
  137. package/src/lib/repos/release/submissions.ts +0 -214
  138. package/src/lib/repos/release/submit-checkout.ts +0 -290
  139. package/src/lib/repos/release/submit-questions.ts +0 -153
  140. package/src/lib/repos/release/submit-service.ts +0 -898
  141. package/src/lib/repos/release/tags.ts +0 -239
  142. package/src/lib/repos/release/validate.ts +0 -463
  143. package/src/lib/repos/resolver.ts +0 -1028
  144. package/src/lib/repos/scaffold/index.ts +0 -245
  145. package/src/lib/repos/scaffold/templates.ts +0 -517
  146. package/src/lib/repos/seed.ts +0 -473
  147. package/src/lib/repos/store/contract.ts +0 -64
  148. package/src/lib/repos/store/hash.ts +0 -191
  149. package/src/lib/repos/store/recipe-store.ts +0 -599
  150. package/src/lib/repos/store/settings.ts +0 -58
  151. package/src/lib/repos/subscription-service.ts +0 -3859
  152. package/src/lib/repos/trust.ts +0 -447
  153. package/src/lib/repos/update-plan.ts +0 -235
  154. package/src/lib/self-update/index.ts +0 -14
  155. package/src/lib/self-update/installs.ts +0 -412
  156. package/src/lib/self-update/managers.ts +0 -126
  157. package/src/lib/self-update/plan.ts +0 -315
  158. package/src/lib/self-update/registry.ts +0 -99
  159. package/src/lib/self-update/run.ts +0 -506
  160. package/src/lib/self-update/versions.ts +0 -243
  161. package/src/lib/settings.ts +0 -1105
  162. package/src/lib/sous-home.ts +0 -104
  163. package/src/lib/state.ts +0 -167
  164. package/src/lib/vars/answers.ts +0 -192
  165. package/src/lib/vars/ask.ts +0 -1152
  166. package/src/lib/vars/definition-source.ts +0 -261
  167. package/src/lib/vars/display.ts +0 -231
  168. package/src/lib/vars/index.ts +0 -20
  169. package/src/lib/vars/ladder.ts +0 -282
  170. package/src/lib/vars/mappings.ts +0 -260
  171. package/src/lib/vars/names.ts +0 -94
  172. package/src/lib/vars/preanswers.ts +0 -395
  173. package/src/lib/vars/question-plan.ts +0 -241
  174. package/src/lib/vars/report.ts +0 -228
  175. package/src/lib/vars/safe-regex.ts +0 -235
  176. package/src/lib/vars/secrets.ts +0 -131
  177. package/src/lib/vars/validate.ts +0 -312
  178. package/src/lib/version-report.ts +0 -90
  179. package/src/lib/watch-loop.ts +0 -148
  180. package/src/lib/watch-service.ts +0 -116
  181. package/src/services/ref-resolver/container.ts +0 -107
  182. package/src/services/ref-resolver/dependency.ts +0 -60
  183. package/src/services/ref-resolver/format.ts +0 -197
  184. package/src/services/ref-resolver/glob.ts +0 -115
  185. package/src/services/ref-resolver/hash-names.ts +0 -155
  186. package/src/services/ref-resolver/index.ts +0 -55
  187. package/src/services/ref-resolver/injectable.ts +0 -36
  188. package/src/services/ref-resolver/location.ts +0 -62
  189. package/src/services/ref-resolver/lookups/cached-index-lookup.ts +0 -53
  190. package/src/services/ref-resolver/lookups/catalog-lookup.ts +0 -23
  191. package/src/services/ref-resolver/lookups/catalog-matcher.ts +0 -261
  192. package/src/services/ref-resolver/lookups/chained-lookup.ts +0 -27
  193. package/src/services/ref-resolver/lookups/env-var-lookup.ts +0 -65
  194. package/src/services/ref-resolver/lookups/fetched-index-lookup.ts +0 -150
  195. package/src/services/ref-resolver/lookups/recorded-dependency-lookup.ts +0 -62
  196. package/src/services/ref-resolver/lookups/ref-lookup.ts +0 -54
  197. package/src/services/ref-resolver/lookups/variable-lookup.ts +0 -123
  198. package/src/services/ref-resolver/named-refs.ts +0 -144
  199. package/src/services/ref-resolver/parser/env-var-splitter.ts +0 -27
  200. package/src/services/ref-resolver/parser/location-splitter.ts +0 -239
  201. package/src/services/ref-resolver/parser/name-path-splitter.ts +0 -200
  202. package/src/services/ref-resolver/parser/partial-ref.ts +0 -84
  203. package/src/services/ref-resolver/parser/query-splitter.ts +0 -61
  204. package/src/services/ref-resolver/parser/range-splitter.ts +0 -52
  205. package/src/services/ref-resolver/parser/ref-parser.ts +0 -115
  206. package/src/services/ref-resolver/parser/repo-qualifier-splitter.ts +0 -51
  207. package/src/services/ref-resolver/parts.ts +0 -115
  208. package/src/services/ref-resolver/pruners/command-line-pruner.ts +0 -47
  209. package/src/services/ref-resolver/pruners/include-pruner.ts +0 -66
  210. package/src/services/ref-resolver/pruners/manifest-pruner.ts +0 -130
  211. package/src/services/ref-resolver/pruners/ref-pruner.ts +0 -135
  212. package/src/services/ref-resolver/pruners/rule-helpers.ts +0 -44
  213. package/src/services/ref-resolver/pruners/stored-key-pruner.ts +0 -136
  214. package/src/services/ref-resolver/ref-helpers.ts +0 -62
  215. package/src/services/ref-resolver/ref-picker-service.ts +0 -204
  216. package/src/services/ref-resolver/ref-report.ts +0 -84
  217. package/src/services/ref-resolver/ref-resolve-arguments.ts +0 -47
  218. package/src/services/ref-resolver/ref-resolve-result.ts +0 -36
  219. package/src/services/ref-resolver/ref-resolver-service.ts +0 -323
  220. package/src/services/ref-resolver/source.ts +0 -48
  221. package/src/services/ref-resolver/tokens.ts +0 -25
  222. package/src/services/ref-resolver/types.ts +0 -155
  223. package/src/templating/filters/bullet-list.ts +0 -9
  224. package/src/templating/filters/index.ts +0 -8
  225. package/src/templating/init-liquid-engine.ts +0 -139
  226. package/src/templating/lib/glob-files.ts +0 -74
  227. package/src/templating/lib/import-export.ts +0 -32
  228. package/src/templating/lib/secret-scope.ts +0 -41
  229. package/src/templating/lib/tag-args.ts +0 -19
  230. package/src/templating/tags/exportScalarVarsJs.ts +0 -46
  231. package/src/templating/tags/getFiles.ts +0 -89
  232. package/src/templating/tags/index.ts +0 -14
  233. package/src/templating/tags/listFiles.ts +0 -54
  234. package/src/templating/tags/showVars.ts +0 -28
  235. package/src/utils/choice-prompt.ts +0 -143
  236. package/src/utils/command-errors.ts +0 -186
  237. package/src/utils/command-help.ts +0 -45
  238. package/src/utils/confirm-prompt.ts +0 -110
  239. package/src/utils/flags.ts +0 -177
  240. package/src/utils/formatting.ts +0 -849
  241. package/src/utils/prompts.ts +0 -53
  242. package/src/utils/sous-directory.ts +0 -245
  243. package/src/utils/table.ts +0 -603
  244. package/src/utils/value-prompt.ts +0 -119
@@ -1,457 +0,0 @@
1
- import path from "node:path";
2
- import { Command, Flags } from "@oclif/core";
3
- import {
4
- discoverConfig,
5
- expandHome,
6
- formatNotFoundMessage,
7
- refreshDiscoveredConfig,
8
- resolveConfigFlag,
9
- type DiscoveredConfig,
10
- } from "./lib/config-discovery.js";
11
- import { loadEnvFiles } from "./lib/env-local.js";
12
- import { loadSettings, type ConfigContext, type Settings } from "./lib/settings.js";
13
- import { isInteractive } from "./lib/interactive.js";
14
- import { displayError, displayErrorBlock, header, log, warning } from "./utils/formatting.js";
15
- import { nonInteractiveFlag } from "./utils/flags.js";
16
- import { reportCommandError } from "./utils/command-errors.js";
17
-
18
- /**
19
- * Base class for all CLI commands.
20
- *
21
- * Startup sequence:
22
- * 1. Locate the config. Primary-config precedence, highest first:
23
- * `--config`/`-c`/`--sous-config` flag > `SOUS_CONFIG` env >
24
- * `--sous-dir` flag > `SOUS_DIR` env > walk up from cwd looking for a
25
- * `.sous/` directory holding sous.config.{js,mjs,json,yaml}. The conf.d
26
- * drop-in directory precedence is: `--sous-confd` flag > `SOUS_CONFD` env >
27
- * `<sousDir>/conf.d`. Env vars are read from the REAL environment only
28
- * (never `.env.local`), because they decide where `.env.local` lives.
29
- * 2. Load `<.sous>/.env.local`, then `<.sous>/.env`, into process.env (never
30
- * overwriting real env vars). Precedence: shell > .env.local > .env.
31
- * 3. Load every config layer (primary + conf.d) through the config kernel and
32
- * deep-merge them. Variable resolution happens later, per command.
33
- *
34
- * There is no user-level config: nothing is read from `~/.sous`.
35
- *
36
- * Every command also carries `--non-interactive`, which tells sous never to ask
37
- * a question: a run that would have prompted fails instead, naming the prompt
38
- * and the flag (or environment variables) that would have answered it, and this
39
- * class prints the command's own help underneath that error. The rule itself
40
- * lives in `lib/interactive.ts`, which also treats a truthy `CI` and a
41
- * non-terminal stdin or stdout the same way.
42
- */
43
- /**
44
- * What the config-locating flags and environment said on this run, resolved to
45
- * absolute paths but not yet turned into a config.
46
- */
47
- export type ConfigLocator = {
48
- /** The working directory discovery started from. */
49
- cwd: string;
50
- /**
51
- * The explicit config location, when one was given: the resolved path and
52
- * the flag or environment variable that supplied it (`--config`,
53
- * `--sous-config`, `SOUS_CONFIG`, `--sous-dir` or `SOUS_DIR`).
54
- */
55
- primary?: { value: string; source: string };
56
- /** The conf.d directory override, when `--sous-confd` or `SOUS_CONFD` gave one. */
57
- confDirOverride?: string;
58
- };
59
-
60
- export abstract class BaseCommand extends Command {
61
- static baseFlags = {
62
- config: Flags.string({
63
- char: "c",
64
- description:
65
- "Path to a sous config file (or a directory containing one). Overrides .sous/ discovery",
66
- }),
67
- "sous-config": Flags.string({
68
- description:
69
- "Alias of --config: path to a sous config file (or a directory containing one)",
70
- }),
71
- "sous-dir": Flags.string({
72
- description: "Path to the .sous directory to use (overrides walk-up discovery)",
73
- }),
74
- "sous-confd": Flags.string({
75
- description: "Path to the conf.d drop-in layer directory (overrides <sousDir>/conf.d)",
76
- }),
77
- "non-interactive": nonInteractiveFlag(),
78
- };
79
-
80
- /**
81
- * Whether a run of this command needs a project config to exist. Every
82
- * command that works on a project leaves this true, and a run that finds no
83
- * config fails before `run()` with the "No sous config found" block. The one
84
- * command whose job is to CREATE the config sets it false: discovery still
85
- * runs, so the config-locating flags still say where the project is, but
86
- * finding nothing is the expected case rather than an error, and `settings`
87
- * stays unset until `adoptConfig` is given the config that was written.
88
- */
89
- static requiresConfig = true;
90
-
91
- /**
92
- * Whether a config that cannot be located or loaded stops this command. It
93
- * is false on every command but the one whose job may be to repair that
94
- * config: `sous update` installs a sous that may understand a config this
95
- * copy rejects (one written for a newer version, say). When true, a failure
96
- * to locate or load the config becomes one warning, naming the config and
97
- * quoting the error, and the run carries on with no config adopted:
98
- * `hasConfig` is false, the env files are not applied, and `rejectedConfig`
99
- * says where the config that failed to load was, when discovery found it.
100
- * It only changes what a FAILURE does; finding no config at all is still
101
- * decided by `requiresConfig`.
102
- */
103
- static toleratesConfigErrors = false;
104
-
105
- protected settings!: Settings;
106
-
107
- /** Where the active config was found. */
108
- protected configContext!: ConfigContext;
109
-
110
- /**
111
- * What the config-locating flags and environment said, before discovery
112
- * turned it into a config. A command that runs without a config reads the
113
- * project's location from here.
114
- */
115
- protected configLocator!: ConfigLocator;
116
-
117
- /** The full discovery result, including how the config was located. */
118
- protected discovered!: DiscoveredConfig;
119
-
120
- /**
121
- * The config discovery found but could not load, on a command that
122
- * `toleratesConfigErrors`. Undefined when the config loaded, when there was
123
- * none, or when the failure came before any config file was identified.
124
- */
125
- protected rejectedConfig?: { configPath: string; sousDir: string };
126
-
127
- /**
128
- * The real shell environment, snapshotted BEFORE the `.sous/` env files are
129
- * injected into `process.env`. The variables layer needs it to tell a value
130
- * the shell supplied from one an env file supplied; after injection the two
131
- * are indistinguishable.
132
- */
133
- protected shellEnv: NodeJS.ProcessEnv = {};
134
-
135
- /**
136
- * Emits the decorative CLI header during init(). The default writes it to
137
- * stdout. Commands whose stdout must stay machine-readable (the `sous config *`
138
- * JSON commands) override this to route the banner to stderr.
139
- */
140
- protected emitHeader(): void {
141
- header();
142
- }
143
-
144
- /**
145
- * Line sink for error rendering during init()/catch(). Defaults to stdout (via
146
- * `log`). Commands whose stdout must stay machine-readable (the `sous config *`
147
- * JSON commands) override this to route error text to stderr, so a broken
148
- * config never corrupts a piped stdout stream (e.g. `sous config show | jq`).
149
- */
150
- protected errorSink: (line: string) => void = log;
151
-
152
- /**
153
- * Whether this run may ask the user a question. One rule, shared by every
154
- * prompt in sous: see `lib/interactive.ts`.
155
- */
156
- protected get interactive(): boolean {
157
- return isInteractive();
158
- }
159
-
160
- async init(): Promise<void> {
161
- await super.init();
162
- this.emitHeader();
163
-
164
- // Read config-locating flags off argv directly. oclif's parse() runs inside
165
- // each command's run(), which is too late: the config (and thus the env
166
- // files) must be located before any variable resolution. `SOUS_*` env vars
167
- // are read from the REAL environment here, BEFORE loadEnvFiles below, because
168
- // they decide where `.env.local` itself lives.
169
- const cwd = process.cwd();
170
- const configFlag = blankToUndefined(readConfigFlagFromArgv(this.argv));
171
- const sousConfigFlag = blankToUndefined(readLongFlagFromArgv(this.argv, "sous-config"));
172
- const sousDirFlag = blankToUndefined(readLongFlagFromArgv(this.argv, "sous-dir"));
173
- const sousConfdFlag = blankToUndefined(readLongFlagFromArgv(this.argv, "sous-confd"));
174
-
175
- // Empty-string env vars are coerced to undefined and treated as unset. A
176
- // bare `export SOUS_CONFD=` (or a variable that expands empty) must not turn
177
- // cwd into the conf.d dir, and an empty SOUS_CONFIG/SOUS_DIR must not mask a
178
- // lower-precedence source or disable walk-up discovery.
179
- const sousConfdEnv = blankToUndefined(process.env.SOUS_CONFD);
180
- const sousConfigEnv = blankToUndefined(process.env.SOUS_CONFIG);
181
- const sousDirEnv = blankToUndefined(process.env.SOUS_DIR);
182
-
183
- // conf.d directory: --sous-confd flag > SOUS_CONFD env > <sousDir>/conf.d.
184
- const confdRaw = sousConfdFlag ?? sousConfdEnv;
185
- const confDirOverride =
186
- confdRaw !== undefined ? path.resolve(cwd, expandHome(confdRaw)) : undefined;
187
-
188
- // Primary config, highest precedence first: --config/-c/--sous-config flag,
189
- // SOUS_CONFIG env, --sous-dir flag, SOUS_DIR env. All resolve with the same
190
- // rules as --config (a file, or a directory holding/containing a config).
191
- // The paired source label is carried through to resolveConfigFlag so an
192
- // error names the source the user actually set (not always `--config`).
193
- const primaryCandidates: [string | undefined, string][] = [
194
- [configFlag, "--config"],
195
- [sousConfigFlag, "--sous-config"],
196
- [sousConfigEnv, "SOUS_CONFIG"],
197
- [sousDirFlag, "--sous-dir"],
198
- [sousDirEnv, "SOUS_DIR"],
199
- ];
200
- const primary = primaryCandidates.find(([value]) => value !== undefined);
201
- const { requiresConfig, toleratesConfigErrors } = this.constructor as typeof BaseCommand;
202
-
203
- this.configLocator = {
204
- cwd,
205
- primary:
206
- primary !== undefined
207
- ? { value: path.resolve(cwd, expandHome(primary[0] as string)), source: primary[1] }
208
- : undefined,
209
- confDirOverride,
210
- };
211
-
212
- let discovered: DiscoveredConfig | null;
213
-
214
- if (primary !== undefined) {
215
- const [primarySource, sourceLabel] = primary as [string, string];
216
- try {
217
- discovered = resolveConfigFlag(primarySource, cwd, confDirOverride, sourceLabel);
218
- } catch (error) {
219
- if (toleratesConfigErrors) {
220
- return this.warnConfigNotLoaded(
221
- error,
222
- `the project config at ${this.configLocator.primary?.value} (named by ${sourceLabel})`
223
- );
224
- }
225
- // A command that creates the config is pointed at a place with none in
226
- // it by design; the flag still says where, so this is not a failure.
227
- if (!requiresConfig) return;
228
- displayError(error instanceof Error ? error.message : String(error), this.errorSink);
229
- return this.exit(1);
230
- }
231
- } else {
232
- try {
233
- discovered = discoverConfig(cwd, confDirOverride);
234
- } catch (error) {
235
- if (!toleratesConfigErrors) throw error;
236
- return this.warnConfigNotLoaded(error, `the project config it found searching up from ${cwd}`);
237
- }
238
- }
239
-
240
- if (!discovered) {
241
- if (!requiresConfig) return;
242
- displayErrorBlock(formatNotFoundMessage(), this.errorSink);
243
- return this.exit(1);
244
- }
245
-
246
- await this.adoptConfig(discovered);
247
- }
248
-
249
- /** True once a config has been discovered or adopted and its settings loaded. */
250
- protected get hasConfig(): boolean {
251
- return this.discovered !== undefined;
252
- }
253
-
254
- /**
255
- * Makes a discovered config THE config for the rest of the run: loads its
256
- * env files, enumerates its layers again now that `SOUS_HOME` may have
257
- * changed, and loads the settings. `init()` calls it for the config discovery
258
- * found; a command that creates a config calls it for the one it wrote, so
259
- * both go through the same steps in the same order.
260
- *
261
- * @param discovered - The config to adopt.
262
- */
263
- protected async adoptConfig(discovered: DiscoveredConfig): Promise<void> {
264
- // Inject .sous/.env.local and .sous/.env before anything resolves variables,
265
- // keeping a copy of what the shell itself set so the variables layer can
266
- // still tell the two apart.
267
- this.shellEnv = { ...process.env };
268
- loadEnvFiles(discovered.sousDir);
269
-
270
- // Enumerated a second time now that the env files are loaded: `SOUS_HOME` is
271
- // file-settable, and it decides where the store holding a subscribed
272
- // recipe's config layers is. A first pass already ran during discovery, when
273
- // only the real environment was known.
274
- let refreshed: DiscoveredConfig;
275
- try {
276
- refreshed = refreshDiscoveredConfig(discovered);
277
- } catch (error) {
278
- if (this.toleratesConfigErrors) return this.rejectConfig(discovered, error);
279
- displayErrorBlock(error instanceof Error ? error.message : String(error), this.errorSink);
280
- return this.exit(1);
281
- }
282
-
283
- this.discovered = refreshed;
284
- this.configContext = {
285
- sousDir: refreshed.sousDir,
286
- configPath: refreshed.configPath,
287
- confDir: refreshed.confDir,
288
- layerPaths: refreshed.layerPaths,
289
- };
290
-
291
- // Routed through the command's error sink, not stdout: a recipe layer
292
- // warning must not land in the middle of `sous config show | jq`.
293
- for (const notice of refreshed.recipeLayerWarnings) warning(notice, this.errorSink);
294
-
295
- try {
296
- this.settings = await loadSettings(refreshed);
297
- } catch (error) {
298
- if (this.toleratesConfigErrors) return this.rejectConfig(refreshed, error);
299
- displayErrorBlock(error instanceof Error ? error.message : String(error), this.errorSink);
300
- return this.exit(1);
301
- }
302
- }
303
-
304
- /** The `toleratesConfigErrors` setting of the running command's class. */
305
- private get toleratesConfigErrors(): boolean {
306
- return (this.constructor as typeof BaseCommand).toleratesConfigErrors;
307
- }
308
-
309
- /**
310
- * Undoes a config adoption that failed on a command that tolerates it: the
311
- * env files it injected are taken back out of `process.env`, nothing is left
312
- * adopted, and one warning says what happened.
313
- */
314
- private rejectConfig(discovered: DiscoveredConfig, error: unknown): void {
315
- for (const name of Object.keys(process.env)) {
316
- if (!(name in this.shellEnv)) delete process.env[name];
317
- }
318
- this.shellEnv = {};
319
- this.discovered = undefined as unknown as DiscoveredConfig;
320
- this.configContext = undefined as unknown as ConfigContext;
321
- this.rejectedConfig = { configPath: discovered.configPath, sousDir: discovered.sousDir };
322
- this.warnConfigNotLoaded(error, `the project config at ${discovered.configPath}`);
323
- }
324
-
325
- /**
326
- * The one warning a command that tolerates config errors prints in place of
327
- * failing.
328
- *
329
- * @param error - What locating or loading the config threw.
330
- * @param config - Which config: its file, or where it was looked for.
331
- */
332
- private warnConfigNotLoaded(error: unknown, config: string): void {
333
- const message = error instanceof Error ? error.message : String(error);
334
- warning(
335
- `Sous could not load ${config}, so this command carries on without it.\n` +
336
- "\n" +
337
- "The error was:\n" +
338
- message,
339
- this.errorSink
340
- );
341
- }
342
-
343
- /**
344
- * Renders any failure as a plain, readable message instead of an oclif stack
345
- * trace: a config mistake, a mistyped command line, or a question sous could
346
- * not ask. A stack pointing into oclif's parser or into sous's internals
347
- * tells the user nothing about the mistake they need to fix, so it is printed
348
- * only when `SOUS_DEBUG` asks for it. The rules live in
349
- * `utils/command-errors.ts`, so every command in sous fails the same way.
350
- *
351
- * A clean `this.exit()` and a command rendering JSON still belong to oclif,
352
- * and fall through to its handling untouched.
353
- */
354
- protected async catch(error: Error & { exitCode?: number }): Promise<unknown> {
355
- const exitCode = await reportCommandError(this, error, { write: this.errorSink });
356
- if (exitCode === undefined) return super.catch(error);
357
- return this.exit(exitCode);
358
- }
359
-
360
- /**
361
- * Re-runs discovery and reloads settings, committing the result onto this
362
- * command only if everything loads cleanly (last-good semantics: a failed
363
- * reload throws and leaves the previously loaded config untouched).
364
- *
365
- * Used by watch mode when a full-rebuild path (the config file, the conf.d
366
- * directory, or the templating dir) changes: conf.d layer files can appear or
367
- * disappear at runtime, so the ordered layer list must be rebuilt (and the
368
- * duplicate-baseName check re-run) before settings reload.
369
- */
370
- protected async reloadDiscoveredConfig(): Promise<void> {
371
- const refreshed = refreshDiscoveredConfig(this.discovered);
372
- const reloaded = await loadSettings(refreshed);
373
-
374
- // Commit only after a clean load, so a broken edit keeps the last-good config.
375
- this.discovered = refreshed;
376
- this.configContext = {
377
- sousDir: refreshed.sousDir,
378
- configPath: refreshed.configPath,
379
- confDir: refreshed.confDir,
380
- layerPaths: refreshed.layerPaths,
381
- };
382
- this.settings = reloaded;
383
- }
384
-
385
- /**
386
- * Human-readable label for the configured project: the config's `name` when
387
- * set, otherwise the basename of the directory holding `.sous/`.
388
- */
389
- protected get projectLabel(): string {
390
- return this.settings.name ?? path.basename(path.dirname(this.configContext.sousDir));
391
- }
392
- }
393
-
394
- /**
395
- * Pulls the value of `--config` / `-c` out of a raw argv array.
396
- * Supports `--config X`, `--config=X`, `-c X`, and `-cX`.
397
- *
398
- * Scanning stops at a bare `--`: anything after it belongs to a launched tool
399
- * (see `launch`'s pass-through args), never to sous.
400
- *
401
- * @param argv - Raw arguments (oclif's `this.argv`, i.e. argv minus the command).
402
- * @returns The flag value, or undefined when the flag is absent.
403
- */
404
- export function readConfigFlagFromArgv(argv: string[]): string | undefined {
405
- for (let i = 0; i < argv.length; i++) {
406
- const arg = argv[i];
407
-
408
- if (arg === "--") return undefined;
409
- if (arg === "--config" || arg === "-c") return argv[i + 1];
410
- if (arg.startsWith("--config=")) return arg.slice("--config=".length);
411
- if (arg.startsWith("-c") && arg.length > 2 && !arg.startsWith("-c-")) return arg.slice(2);
412
- }
413
- return undefined;
414
- }
415
-
416
- /**
417
- * Coerces an empty or whitespace-only string to `undefined`, passing every other
418
- * value through unchanged.
419
- *
420
- * Config-locating inputs (`SOUS_CONFIG`, `SOUS_DIR`, `SOUS_CONFD`, and their flag
421
- * aliases) must treat an empty value as "unset", never as a real path. A bare
422
- * `export SOUS_CONFD=` (or a variable that expands empty) would otherwise resolve
423
- * to cwd and load every file in the working directory as a config layer; an empty
424
- * `SOUS_CONFIG` / `SOUS_DIR` would mask a lower-precedence source and disable
425
- * walk-up discovery. Normalising to `undefined` up front lets the plain `??`
426
- * precedence chain fall through correctly.
427
- */
428
- export function blankToUndefined(value: string | undefined): string | undefined {
429
- if (value === undefined) return undefined;
430
- return value.trim() === "" ? undefined : value;
431
- }
432
-
433
- /**
434
- * Pulls the value of a long-only flag (`--<flagName> VALUE` or
435
- * `--<flagName>=VALUE`) out of a raw argv array. Used for the `--sous-config`,
436
- * `--sous-dir` and `--sous-confd` aliases, which (like `--config`) must be
437
- * read before oclif's parse() so the config is located before env files load.
438
- *
439
- * Scanning stops at a bare `--` for the same reason as `readConfigFlagFromArgv`:
440
- * anything after it belongs to a launched tool, never to sous.
441
- *
442
- * @param argv - Raw arguments (oclif's `this.argv`).
443
- * @param flagName - The flag name without leading dashes (e.g. `sous-dir`).
444
- * @returns The flag value, or undefined when the flag is absent (or has no value).
445
- */
446
- export function readLongFlagFromArgv(argv: string[], flagName: string): string | undefined {
447
- const long = `--${flagName}`;
448
- const eq = `${long}=`;
449
- for (let i = 0; i < argv.length; i++) {
450
- const arg = argv[i];
451
-
452
- if (arg === "--") return undefined;
453
- if (arg === long) return argv[i + 1];
454
- if (arg.startsWith(eq)) return arg.slice(eq.length);
455
- }
456
- return undefined;
457
- }
@@ -1,181 +0,0 @@
1
- import { Flags } from "@oclif/core";
2
- import { BaseCommand } from "../base-command.js";
3
- import { runProjectBuild } from "../lib/build-service.js";
4
- import { PidService } from "../lib/pid-service.js";
5
- import { resolveRootScope } from "../lib/settings.js";
6
- import { resolveStoreSettings } from "../lib/repos/store/settings.js";
7
- import { subscriptionServiceFor } from "../lib/repos/subscription-service.js";
8
- import { buildReloadWatchConfig, startConfigReloadWatch } from "../lib/watch-loop.js";
9
- import type { WatchHandle } from "../lib/watch-service.js";
10
- import { WatchService } from "../lib/watch-service.js";
11
- import { log, paragraph, showCommandVars } from "../utils/formatting.js";
12
-
13
- export default class Build extends BaseCommand {
14
- static description =
15
- "Compile this project's outputs and remove the ones its config no longer produces";
16
-
17
- static examples = [
18
- "<%= config.bin %> build",
19
- "<%= config.bin %> build --no-prune",
20
- "<%= config.bin %> build --rebuild",
21
- "<%= config.bin %> build --dry-run",
22
- ];
23
-
24
- static flags = {
25
- ...BaseCommand.baseFlags,
26
- "no-prune": Flags.boolean({
27
- description: "Skip the prune step",
28
- default: false,
29
- }),
30
- "no-compile": Flags.boolean({
31
- description: "Skip the compile step (prune only)",
32
- default: false,
33
- }),
34
- rebuild: Flags.boolean({
35
- description: "Ignore cached hashes and reprocess all outputs",
36
- default: false,
37
- }),
38
- "dry-run": Flags.boolean({
39
- description: "Print what would be written/pruned without making changes",
40
- default: false,
41
- }),
42
- strict: Flags.boolean({
43
- description: "Treat compile warnings as errors",
44
- default: false,
45
- }),
46
- watch: Flags.boolean({
47
- char: "w",
48
- description: "Watch source files and rebuild on changes",
49
- default: false,
50
- }),
51
- };
52
-
53
- async run(): Promise<void> {
54
- const { flags } = await this.parse(Build);
55
-
56
- showCommandVars({
57
- Project: this.projectLabel,
58
- Config: this.configContext.configPath,
59
- Rebuild: flags.rebuild,
60
- "Dry Run": flags["dry-run"],
61
- "No Compile": flags["no-compile"],
62
- "No Prune": flags["no-prune"],
63
- });
64
-
65
- const buildOptions = {
66
- strict: flags.strict,
67
- rebuild: flags.rebuild,
68
- dryRun: flags["dry-run"],
69
- noCompile: flags["no-compile"],
70
- noPrune: flags["no-prune"],
71
- };
72
-
73
- const success = await runProjectBuild({
74
- settings: this.settings,
75
- configContext: this.configContext,
76
- shellEnv: this.shellEnv,
77
- options: buildOptions,
78
- });
79
-
80
- if (!success && !flags.watch) {
81
- this.exit(1);
82
- }
83
-
84
- if (flags.watch) {
85
- const rootScope = resolveRootScope(this.settings, this.configContext);
86
-
87
- // --- PID file enforcement ---
88
- const pidService = new PidService();
89
- const pidFilePath = pidService.getFilePath(rootScope);
90
- await pidService.acquire(pidFilePath, this.projectLabel);
91
-
92
- const cleanup = async (watchHandle?: WatchHandle) => {
93
- if (process.stdin.isTTY) {
94
- process.stdin.setRawMode(false);
95
- }
96
- process.stdin.pause();
97
- if (watchHandle) await watchHandle.stop();
98
- await pidService.release(pidFilePath);
99
- };
100
-
101
- process.on("SIGINT", () => { void cleanup().then(() => process.exit(0)); });
102
- process.on("SIGTERM", () => { void cleanup().then(() => process.exit(0)); });
103
-
104
- const watchService = new WatchService();
105
-
106
- // Reruns the build with the command's current settings. Called for
107
- // partial rebuilds (with the changed file) and, after a clean reload, for
108
- // full rebuilds, which prepare the recipes again the way the first build did.
109
- const rebuild = async (changedFile?: string) => {
110
- // A failed rebuild has already listed its errors, and the watch keeps
111
- // running so the next save can fix them.
112
- await runProjectBuild({
113
- settings: this.settings,
114
- configContext: this.configContext,
115
- shellEnv: this.shellEnv,
116
- heading: "Rebuilding",
117
- options: {
118
- ...buildOptions,
119
- // --rebuild means full clean build on every trigger; skip partial optimisation
120
- changedFile: buildOptions.rebuild ? undefined : changedFile,
121
- },
122
- });
123
- };
124
-
125
- const { handle, triggerFullRebuild } = startConfigReloadWatch({
126
- watchService,
127
- buildWatchConfig: () => buildReloadWatchConfig(this.settings, this.configContext),
128
- rebuild,
129
- reloadConfig: () => this.reloadDiscoveredConfig(),
130
- });
131
-
132
- // Watch mode polls upstream for the repositories that prefer a newer
133
- // in-range version. The poll is cheap (one index request per repository)
134
- // and a failure never breaks the watch; the last good answer stands.
135
- const pollSeconds = resolveStoreSettings(this.settings).watchPollSeconds;
136
- if (pollSeconds > 0) {
137
- const repositories = subscriptionServiceFor({
138
- configContext: this.configContext,
139
- settings: this.settings,
140
- shellEnv: this.shellEnv,
141
- });
142
- const poll = setInterval(() => {
143
- void repositories
144
- .checkUpstream()
145
- .then(async (report) => {
146
- if (report.updated.length === 0) return;
147
- for (const change of report.updated) {
148
- paragraph(` ${change.key} moved from ${change.from} to ${change.to}.`);
149
- }
150
- await triggerFullRebuild("A newer recipe version arrived upstream.");
151
- })
152
- .catch(() => {
153
- // checkUpstream already reports its own failures as warnings.
154
- });
155
- }, pollSeconds * 1000);
156
- poll.unref();
157
- }
158
-
159
- // Display the interactive prompt
160
- log("[ Press Q to quit | any other key: rebuild ]");
161
-
162
- if (process.stdin.isTTY) {
163
- process.stdin.setRawMode(true);
164
- process.stdin.resume();
165
- process.stdin.setEncoding("utf8");
166
-
167
- process.stdin.on("data", (key: string) => {
168
- // q, Q, or Ctrl+C → clean exit
169
- if (key === "q" || key === "Q" || key === "\u0003") {
170
- void cleanup(handle.current ?? undefined).then(() => process.exit(0));
171
- return;
172
- }
173
- // Any other key → trigger a full rebuild immediately (bypass debounce)
174
- void triggerFullRebuild("Manual rebuild triggered.");
175
- });
176
- }
177
-
178
- await new Promise(() => {}); // keep process alive
179
- }
180
- }
181
- }