@seangalie/precast 0.1.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -5,6 +5,42 @@ and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.2.0] - 2026-11-18
9
+
10
+ ### Added
11
+
12
+ - Interactive prompts: run in a terminal with required options missing, Precast
13
+ asks for the platform, tier, namespace, repository, and output folder,
14
+ checks each answer, and prints the equivalent command, under a small ASCII
15
+ header and with color where the terminal supports it (`NO_COLOR` turns color
16
+ off). `--no-input` turns the questions off; scripts, CI, and anything
17
+ without a terminal still get an error.
18
+ - Named profiles in a user settings file, chosen with `--profile`, save a
19
+ platform, server, namespace, and other defaults for servers you use often.
20
+ `--config` reads profiles from another file.
21
+ - Regular and full projects get a `commit-msg` hook that enforces Conventional
22
+ Commit messages and a `no-commit-to-branch` guard for their default branch,
23
+ which also covers local merge commits. `pre-commit install` installs both,
24
+ generated CI skips the guard, and `SETUP.md` has the first commit made before
25
+ the hooks are installed.
26
+ - GitLab projects generated for GitLab.com set `image: python:3.14-trixie` in
27
+ `.gitlab-ci.yml`, because the hosted runners' default image lacks Python's
28
+ `venv`. Other GitLab servers keep their runners' image.
29
+
30
+ ### Changed
31
+
32
+ - **Breaking:** Forgejo projects default to `https://codeberg.org` and GitLab
33
+ projects to `https://gitlab.com`, instead of my own Forgejo and PPPL's GitLab.
34
+ Use `--server-url` or a profile for any other server.
35
+ - GitLab and Forgejo setup checklists no longer refer to PPPL, and the Forgejo
36
+ checklist explains choosing a hosted runner's label with `--runner`.
37
+
38
+ ### Fixed
39
+
40
+ - A default branch or runner containing a character outside the Basic
41
+ Multilingual Plane, such as an emoji, now renders as valid YAML in generated
42
+ workflows and hook settings.
43
+
8
44
  ## [0.1.0] - 2026-11-17
9
45
 
10
46
  ### Added
package/README.md CHANGED
@@ -19,6 +19,7 @@ Start a new project with its documentation, checks, and forge settings already i
19
19
  - [Generate a project](#generate-a-project)
20
20
  - [Publish it](#publish-it)
21
21
  - [Options](#options)
22
+ - [Save your servers as profiles](#save-your-servers-as-profiles)
22
23
  - [What Precast will not do](#what-precast-will-not-do)
23
24
  - [Roadmap](#roadmap)
24
25
  - [Changelog](#changelog)
@@ -60,13 +61,14 @@ extra files later.
60
61
 
61
62
  | Platform | Default server | Platform files |
62
63
  | --- | --- | --- |
63
- | `forgejo` | `https://git.galie.io` | `.forgejo/`, plus `renovate.json` in full |
64
+ | `forgejo` | `https://codeberg.org` | `.forgejo/`, plus `renovate.json` in full |
64
65
  | `github` | `https://github.com` | `.github/` |
65
- | `gitlab` | `https://git.pppl.gov` | `.gitlab/`, plus `.gitlab-ci.yml` in regular and full |
66
+ | `gitlab` | `https://gitlab.com` | `.gitlab/`, plus `.gitlab-ci.yml` in regular and full |
66
67
 
67
68
  Each platform keeps its own native formats: Forgejo and GitHub use issue forms
68
69
  and Actions workflows, and GitLab uses Markdown templates and GitLab CI. Any of
69
- them can point at a different server with `--server-url`.
70
+ them can point at a different server, such as your own Forgejo or your
71
+ organization's GitLab, with `--server-url` or a [profile](#save-your-servers-as-profiles).
70
72
 
71
73
  ## Getting Started
72
74
 
@@ -75,8 +77,8 @@ them can point at a different server with `--server-url`.
75
77
  - Node.js 22.18 or newer, which includes npm. Precast has no other runtime
76
78
  dependencies.
77
79
  - Git, to publish the project you generate.
78
- - An account on the forge where the new project will live. For PPPL's GitLab,
79
- you also need to be on PPPL's VPN when you push.
80
+ - An account on the forge where the new project will live. For a server inside
81
+ an organization's network, you may also need its VPN when you push.
80
82
 
81
83
  ### Installation
82
84
 
@@ -99,8 +101,17 @@ The examples below use `precast`. If you did not install it, use
99
101
 
100
102
  ### Generate a project
101
103
 
102
- Run `precast` from the folder where you keep your projects. This creates a
103
- `regular` GitHub project for the account `my-name` in a new folder:
104
+ The quickest start is to run `precast` on its own in a terminal. It asks for the
105
+ platform, tier, namespace, repository name, and output folder, checks each
106
+ answer, and then prints the full command so you can skip the questions next
107
+ time. Pressing Enter at the tier question keeps `regular`. Press
108
+ Ctrl+C to stop without writing anything. The questions use color in terminals
109
+ that support it; set `NO_COLOR=1` to turn it off. Commands that give every
110
+ required option ask nothing and print plain text.
111
+
112
+ You can also give everything as options. Run `precast` from the folder where you
113
+ keep your projects. This creates a `regular` GitHub project for the account
114
+ `my-name` in a new folder:
104
115
 
105
116
  ```sh
106
117
  precast --platform github --namespace my-name \
@@ -165,10 +176,56 @@ If you used `--default-branch`, use that name in place of `main` above.
165
176
  | `--codeowner` | A user or team to own every file, such as `@my-name`; without it, the code owners file holds a commented example |
166
177
  | `--runner` | The Actions runner label or GitLab runner tag for CI |
167
178
  | `--server-url` | A different server than the platform's default |
179
+ | `--profile` | Use the saved settings with this name; see below |
180
+ | `--config` | The settings file to read profiles from, if not the usual one |
168
181
  | `--dry-run` | Check everything and list the files without writing them |
182
+ | `--no-input` | Never ask questions; report missing options instead, as scripts need |
169
183
 
170
184
  `precast --help` prints the same list, and `precast --version` prints the version.
171
185
 
186
+ ### Save your servers as profiles
187
+
188
+ If you use your own Forgejo, an organization's GitLab, or the same settings
189
+ every time, save them as a profile instead of typing them for each project.
190
+ Profiles live in a settings file you create:
191
+
192
+ - macOS and Linux: `~/.config/precast/config.json`, or `$XDG_CONFIG_HOME/precast/config.json`
193
+ - Windows: `%APPDATA%\precast\config.json`
194
+
195
+ Each profile names a platform and any defaults you want:
196
+
197
+ ```json
198
+ {
199
+ "profiles": {
200
+ "home": {
201
+ "platform": "forgejo",
202
+ "serverUrl": "https://git.example.org",
203
+ "namespace": "my-name",
204
+ "author": "My Name",
205
+ "runner": "docker"
206
+ },
207
+ "work": {
208
+ "platform": "gitlab",
209
+ "serverUrl": "https://gitlab.example.com",
210
+ "runner": "linux",
211
+ "tier": "regular"
212
+ }
213
+ }
214
+ }
215
+ ```
216
+
217
+ A profile can set `platform` (required), `serverUrl`, `namespace`, `author`,
218
+ `description`, `defaultBranch`, `codeowner`, `runner`, and `tier`. Then:
219
+
220
+ ```sh
221
+ precast --profile work --namespace group/subgroup --repo my-project --output my-project
222
+ ```
223
+
224
+ Anything you type on the command line wins over the profile, and Precast asks
225
+ for anything still missing, such as the repository name. Precast only reads
226
+ the settings file when you use `--profile`, so commands without it always behave
227
+ the same way.
228
+
172
229
  ### What Precast will not do
173
230
 
174
231
  Precast never contacts a forge, runs Git, or asks for passwords or tokens. It
package/dist/bin.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { main } from "./cli.js";
3
- process.exitCode = main(process.argv.slice(2));
3
+ process.exitCode = await main(process.argv.slice(2));
package/dist/cli.d.ts CHANGED
@@ -1 +1,7 @@
1
- export declare function main(argv: string[], root?: string): number;
1
+ import { type Ask } from "./prompts.ts";
2
+ /** Where questions are asked; tests replace it with scripted answers. */
3
+ export interface Terminal {
4
+ interactive: boolean;
5
+ prompt<T>(use: (ask: Ask) => Promise<T>): Promise<T>;
6
+ }
7
+ export declare function main(argv: string[], root?: string, terminal?: Terminal): Promise<number>;
package/dist/cli.js CHANGED
@@ -5,6 +5,9 @@ import { DEFAULT_BRANCH, DEFAULT_DESCRIPTION } from "./context.js";
5
5
  import { isSystemError, PrecastError } from "./errors.js";
6
6
  import { generate, ROOT } from "./generate.js";
7
7
  import { platformNames } from "./platforms.js";
8
+ import { defaultConfigPath, readProfile } from "./profiles.js";
9
+ import { Cancelled, promptForMissing, shellQuote, withTerminal, } from "./prompts.js";
10
+ import { header, paint } from "./style.js";
8
11
  import { DEFAULT_TIER, isTier, TIERS } from "./tiers.js";
9
12
  const OPTIONS = {
10
13
  platform: { type: "string" },
@@ -19,32 +22,46 @@ const OPTIONS = {
19
22
  "default-branch": { type: "string" },
20
23
  codeowner: { type: "string" },
21
24
  runner: { type: "string" },
25
+ profile: { type: "string" },
26
+ config: { type: "string" },
22
27
  "dry-run": { type: "boolean" },
28
+ "no-input": { type: "boolean" },
23
29
  help: { type: "boolean", short: "h" },
24
30
  version: { type: "boolean", short: "v" },
25
31
  };
26
- const REQUIRED = ["platform", "namespace", "repo", "output"];
27
32
  function usage(root) {
28
- return `Usage: precast --platform <id> --namespace <owner> --repo <name> --output <dir> [options]
33
+ return `Usage:
34
+ precast Ask for everything needed (at a terminal)
35
+ precast --platform <id> --namespace <owner> --repo <name> --output <dir> [options]
36
+ precast --profile <name> --repo <name> --output <dir> [options]
29
37
 
30
38
  Render shared files and one platform's native files into a new project directory.
31
39
 
32
- Required:
40
+ Required. At a terminal, Precast asks for any that are missing:
33
41
  --platform <id> ${platformNames(root).join(", ")}
34
42
  --namespace <owner> Owner, organization, or GitLab group/subgroup
35
43
  --repo <name> Repository slug
36
44
  --output <dir> New directory outside the Precast source directory
37
45
 
38
- Options:
39
- --tier <tier> ${TIERS.join(", ")}; each tier adds to the previous one (default: ${DEFAULT_TIER})
40
- --server-url <url> Override the platform's default instance URL
46
+ Optional. When Precast is asking, it also asks for these (defaults shown):
47
+ --tier <tier> ${TIERS.join(", ")}; each adds to the one before (default: ${DEFAULT_TIER})
48
+
49
+ Never asked; set these as options:
41
50
  --project-name <name> Human-readable title; defaults to the repository slug
42
51
  --author <name> Display name; defaults to the namespace
43
52
  --description <text> Defaults to "${DEFAULT_DESCRIPTION}"
44
53
  --default-branch <name> Defaults to ${DEFAULT_BRANCH}
45
54
  --codeowner <@owner> Explicit @user or @namespace/team; omitted means a commented example
55
+ --server-url <url> Override the platform's default instance URL
46
56
  --runner <label> Actions runner label or GitLab runner tag
57
+
58
+ Profiles (a profile can set everything above except the repository, output, and title):
59
+ --profile <name> Use saved settings, such as a self-hosted server; options given here win
60
+ --config <file> Settings file for --profile (default: ${defaultConfigPath()})
61
+
62
+ Other options:
47
63
  --dry-run Validate and list files without writing
64
+ --no-input Never ask questions; report missing options instead
48
65
  -h, --help Show this help
49
66
  -v, --version Show the version
50
67
  `;
@@ -52,89 +69,183 @@ Options:
52
69
  /** Thrown for unusable command lines, which exit with status 2 like other CLIs. */
53
70
  class UsageError extends Error {
54
71
  }
55
- export function main(argv, root = ROOT) {
72
+ const nodeTerminal = {
73
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
74
+ prompt: (use) => withTerminal(process.stdin, process.stdout, use),
75
+ };
76
+ export async function main(argv, root = ROOT, terminal = nodeTerminal) {
56
77
  let values;
57
78
  try {
58
- values = parse(argv, root);
79
+ values = parse(argv);
59
80
  }
60
81
  catch (error) {
61
- if (error instanceof UsageError ||
62
- (isSystemError(error) && error.code.startsWith("ERR_PARSE_ARGS"))) {
63
- process.stderr.write(`error: ${error.message}\nRun precast --help for usage.\n`);
64
- return 2;
65
- }
66
- throw error;
82
+ return usageFailure(error);
67
83
  }
68
84
  if (values.help) {
69
85
  process.stdout.write(usage(root));
70
86
  return 0;
71
87
  }
72
88
  if (values.version) {
73
- const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
74
- process.stdout.write(`${manifest.version}\n`);
89
+ process.stdout.write(`${readVersion(root)}\n`);
75
90
  return 0;
76
91
  }
77
- const tier = values.tier ?? DEFAULT_TIER;
78
- if (!isTier(tier)) {
79
- throw new Error("unreachable: tier is validated during parsing");
80
- }
81
92
  try {
82
- const { destination, files } = generate({
83
- platform: values.platform,
84
- namespace: values.namespace,
85
- repo: values.repo,
86
- output: values.output,
87
- tier,
88
- serverUrl: values["server-url"],
89
- projectName: values["project-name"],
90
- author: values.author,
91
- description: values.description,
92
- defaultBranch: values["default-branch"],
93
- codeowner: values.codeowner,
94
- runner: values.runner,
95
- dryRun: values["dry-run"],
96
- }, root);
97
- const verb = values["dry-run"] ? "Would generate" : "Generated";
93
+ let profile;
94
+ try {
95
+ // Compare with undefined so an empty `--profile=` is rejected, not ignored.
96
+ profile =
97
+ values.profile !== undefined
98
+ ? readProfile(values.config ?? defaultConfigPath(), values.profile)
99
+ : undefined;
100
+ }
101
+ catch (error) {
102
+ return failure(error);
103
+ }
104
+ let options;
105
+ let nextTime;
106
+ let tier;
107
+ try {
108
+ const required = merge(values, profile);
109
+ // Reject a bad platform or tier before asking anything about it.
110
+ checkChoices(required.platform, values.tier ?? profile?.tier, root);
111
+ const missing = missingNames(required);
112
+ if (missing.length > 0 && terminal.interactive && !values["no-input"]) {
113
+ process.stdout.write(header(readVersion(root)));
114
+ // A session that is already asking also offers the tier, unless one was chosen.
115
+ const askTier = (values.tier ?? profile?.tier) === undefined;
116
+ const answers = await terminal.prompt((ask) => promptForMissing(required, ask, (text) => process.stdout.write(text), root, {
117
+ askTier,
118
+ }));
119
+ // `--key=value` keeps a value such as `-draft` from reading as an option,
120
+ // and the new options go before any `--` that ended the original options.
121
+ const added = missing.map((name) => `--${name}=${answers[name]}`);
122
+ if (answers.tier !== undefined)
123
+ added.push(`--tier=${answers.tier}`);
124
+ tier = answers.tier;
125
+ const end = argv.indexOf("--");
126
+ const replay = end < 0 ? [...argv, ...added] : [...argv.slice(0, end), ...added, ...argv.slice(end)];
127
+ nextTime = `precast ${replay.map(shellQuote).join(" ")}`;
128
+ Object.assign(required, {
129
+ platform: answers.platform,
130
+ namespace: answers.namespace,
131
+ repo: answers.repo,
132
+ output: answers.output,
133
+ });
134
+ }
135
+ options = resolve(values, profile, required, root, tier);
136
+ }
137
+ catch (error) {
138
+ if (error instanceof Cancelled) {
139
+ process.stderr.write(`\n${error.message}\n`);
140
+ return 130;
141
+ }
142
+ return usageFailure(error);
143
+ }
144
+ const { destination, files } = generate(options, root);
145
+ const verb = options.dryRun ? "Would generate" : "Generated";
98
146
  const lines = [
99
- `${verb} ${files.length} files for ${values.platform} (${tier} tier): ${destination}`,
147
+ `${verb} ${files.length} files for ${options.platform} (${options.tier} tier): ${destination}`,
100
148
  ];
101
- if (values["dry-run"]) {
149
+ if (options.dryRun) {
102
150
  lines.push(...files.map((file) => ` ${file}`));
103
151
  }
104
152
  else {
105
153
  lines.push("Review SETUP.md before creating the destination repository and pushing.");
106
154
  }
155
+ if (nextTime) {
156
+ // A prompted session marks success and shows how to skip the questions.
157
+ // Only a prompted run is styled; complete commands print plain text.
158
+ lines[0] = `\n${paint("green", `✓ ${lines[0]}`)}`;
159
+ lines.push("", paint("dim", "Next time, run:"), ` ${paint("cyan", nextTime)}`);
160
+ }
107
161
  process.stdout.write(`${lines.join("\n")}\n`);
108
162
  return 0;
109
163
  }
110
164
  catch (error) {
111
- if (error instanceof PrecastError || isSystemError(error)) {
112
- process.stderr.write(`error: ${error.message}\n`);
113
- return 1;
114
- }
115
- throw error;
165
+ return failure(error);
116
166
  }
117
167
  }
118
- function parse(argv, root) {
168
+ /** Report an expected failure without a stack trace; rethrow anything else. */
169
+ function failure(error) {
170
+ if (error instanceof PrecastError || isSystemError(error)) {
171
+ process.stderr.write(`error: ${error.message}\n`);
172
+ return 1;
173
+ }
174
+ throw error;
175
+ }
176
+ function usageFailure(error) {
177
+ if (error instanceof UsageError ||
178
+ (isSystemError(error) && error.code.startsWith("ERR_PARSE_ARGS"))) {
179
+ process.stderr.write(`error: ${error.message}\nRun precast --help for usage.\n`);
180
+ return 2;
181
+ }
182
+ throw error;
183
+ }
184
+ function parse(argv) {
119
185
  const { values } = parseArgs({
120
186
  args: argv,
121
187
  options: OPTIONS,
122
188
  strict: true,
123
189
  allowPositionals: false,
124
190
  });
125
- if (values.help || values.version) {
126
- return values;
191
+ if (values.config !== undefined && values.profile === undefined) {
192
+ throw new UsageError("--config only applies with --profile");
193
+ }
194
+ return values;
195
+ }
196
+ /** The required values from the command line and profile; options given explicitly win. */
197
+ function merge(values, profile) {
198
+ if (profile && values.platform !== undefined && values.platform !== profile.platform) {
199
+ throw new UsageError(`--platform ${values.platform} conflicts with profile ${values.profile}, which uses ${profile.platform}`);
127
200
  }
128
- const missing = REQUIRED.filter((name) => values[name] === undefined);
201
+ return {
202
+ platform: values.platform ?? profile?.platform,
203
+ namespace: values.namespace ?? profile?.namespace,
204
+ repo: values.repo,
205
+ output: values.output,
206
+ };
207
+ }
208
+ function missingNames(required) {
209
+ return ["platform", "namespace", "repo", "output"].filter((name) => required[name] === undefined);
210
+ }
211
+ /** Validate the platform and tier and fill in the optional values. */
212
+ function resolve(values, profile, required, root, answeredTier) {
213
+ const missing = missingNames(required);
129
214
  if (missing.length > 0) {
130
215
  throw new UsageError(`missing required options: ${missing.map((name) => `--${name}`).join(", ")}`);
131
216
  }
217
+ const tier = values.tier ?? profile?.tier ?? answeredTier ?? DEFAULT_TIER;
218
+ checkChoices(required.platform, tier, root);
219
+ if (!isTier(tier)) {
220
+ throw new Error("unreachable: checkChoices validates the tier");
221
+ }
222
+ return {
223
+ platform: required.platform,
224
+ namespace: required.namespace,
225
+ repo: required.repo,
226
+ output: required.output,
227
+ tier,
228
+ serverUrl: values["server-url"] ?? profile?.serverUrl,
229
+ projectName: values["project-name"],
230
+ author: values.author ?? profile?.author,
231
+ description: values.description ?? profile?.description,
232
+ defaultBranch: values["default-branch"] ?? profile?.defaultBranch,
233
+ codeowner: values.codeowner ?? profile?.codeowner,
234
+ runner: values.runner ?? profile?.runner,
235
+ dryRun: values["dry-run"],
236
+ };
237
+ }
238
+ /** Validate a platform and tier when they are known; either may still be missing. */
239
+ function checkChoices(platform, tier, root) {
132
240
  const platforms = platformNames(root);
133
- if (!platforms.includes(values.platform)) {
241
+ if (platform !== undefined && !platforms.includes(platform)) {
134
242
  throw new UsageError(`--platform must be one of: ${platforms.join(", ")}`);
135
243
  }
136
- if (values.tier !== undefined && !isTier(values.tier)) {
244
+ if (tier !== undefined && !isTier(tier)) {
137
245
  throw new UsageError(`--tier must be one of: ${TIERS.join(", ")}`);
138
246
  }
139
- return values;
247
+ }
248
+ function readVersion(root) {
249
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
250
+ return manifest.version;
140
251
  }
package/dist/context.d.ts CHANGED
@@ -16,6 +16,10 @@ export interface ContextOptions {
16
16
  }
17
17
  export declare const DEFAULT_DESCRIPTION = "Describe this project.";
18
18
  export declare const DEFAULT_BRANCH = "main";
19
+ /** Validate an owner, organization, or group path; only some platforms allow subgroups. */
20
+ export declare function checkNamespace(value: string, nestedAllowed: boolean): string;
21
+ /** Validate a repository slug. */
22
+ export declare function checkRepo(value: string): string;
19
23
  export declare function makeContext(options: ContextOptions, platform: PlatformDescriptor): Context;
20
24
  /** Reject empty values, control characters, and anything that would read as a template token. */
21
25
  export declare function textValue(value: string | undefined, label: string): string;
@@ -24,9 +28,11 @@ export declare function markdown(value: string): string;
24
28
  /** Percent-encode UTF-8 bytes outside unreserved characters and `safe`. */
25
29
  export declare function quote(value: string, safe?: string): string;
26
30
  /**
27
- * Serialize a string as JSON with non-ASCII characters escaped. The result is
28
- * also a valid YAML scalar, and ASCII output stays readable in any editor.
31
+ * Serialize a string as an ASCII YAML double-quoted scalar. JSON's escapes for
32
+ * quotes, backslashes, and control characters are also YAML escapes, but JSON
33
+ * writes characters outside the Basic Multilingual Plane as two surrogate
34
+ * escapes, which YAML parsers reject. Those become one `\UXXXXXXXX` escape.
29
35
  */
30
- export declare function jsonAscii(value: string): string;
36
+ export declare function yamlString(value: string): string;
31
37
  /** Replace `{KEY}` with earlier context values; `{{` and `}}` are literal braces. */
32
38
  export declare function formatValue(value: string, context: Context, key: string): string;
package/dist/context.js CHANGED
@@ -4,17 +4,31 @@ export const DEFAULT_DESCRIPTION = "Describe this project.";
4
4
  export const DEFAULT_BRANCH = "main";
5
5
  const COMPONENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
6
6
  const CODEOWNER = /^@[A-Za-z0-9_][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]*)*$/;
7
- export function makeContext(options, platform) {
8
- const namespace = textValue(options.namespace, "Namespace");
7
+ /** Validate an owner, organization, or group path; only some platforms allow subgroups. */
8
+ export function checkNamespace(value, nestedAllowed) {
9
+ const namespace = textValue(value, "Namespace");
9
10
  const components = namespace.split("/");
10
- if (!platform.nested_namespaces && components.length !== 1) {
11
+ if (!nestedAllowed && components.length !== 1) {
11
12
  throw new PrecastError("This platform does not support nested namespaces");
12
13
  }
13
- for (const component of [...components, options.repo]) {
14
- if (!COMPONENT.test(component) || component.endsWith(".git") || component.endsWith(".")) {
15
- throw new PrecastError(`Invalid repository or namespace component: '${component}'`);
16
- }
14
+ for (const component of components) {
15
+ checkComponent(component);
16
+ }
17
+ return namespace;
18
+ }
19
+ /** Validate a repository slug. */
20
+ export function checkRepo(value) {
21
+ checkComponent(value);
22
+ return value;
23
+ }
24
+ function checkComponent(component) {
25
+ if (!COMPONENT.test(component) || component.endsWith(".git") || component.endsWith(".")) {
26
+ throw new PrecastError(`Invalid repository or namespace component: '${component}'`);
17
27
  }
28
+ }
29
+ export function makeContext(options, platform) {
30
+ const namespace = checkNamespace(options.namespace, platform.nested_namespaces);
31
+ checkRepo(options.repo);
18
32
  const server = serverUrl(options.serverUrl || platform.server_url);
19
33
  const branch = defaultBranch(options.defaultBranch ?? DEFAULT_BRANCH);
20
34
  const name = textValue(options.projectName || options.repo, "Project name");
@@ -36,10 +50,10 @@ export function makeContext(options, platform) {
36
50
  AUTHOR: markdown(author),
37
51
  DESCRIPTION: markdown(description),
38
52
  DEFAULT_BRANCH: branch,
39
- DEFAULT_BRANCH_YAML: jsonAscii(branch),
53
+ DEFAULT_BRANCH_YAML: yamlString(branch),
40
54
  BRANCH_URL: quote(branch),
41
- RUNNER_YAML: jsonAscii(runner ?? platform.runner),
42
- RUNNER_TAGS_YAML: runner ? `[${jsonAscii(runner)}]` : "[]",
55
+ RUNNER_YAML: yamlString(runner ?? platform.runner),
56
+ RUNNER_TAGS_YAML: runner ? `[${yamlString(runner)}]` : "[]",
43
57
  CODEOWNER: owner || "",
44
58
  CODEOWNERS_RULE: owner
45
59
  ? `${platform.codeowners_pattern} ${owner}`
@@ -47,14 +61,32 @@ export function makeContext(options, platform) {
47
61
  `# ${platform.codeowners_pattern} @username-or-team`,
48
62
  };
49
63
  // Descriptor entries are ordered so later values can refer to earlier URLs.
64
+ const onDefaultServer = sameServer(server, platform.server_url);
50
65
  for (const [key, value] of Object.entries(platform.context)) {
51
66
  if (Object.hasOwn(context, key)) {
52
67
  throw new PrecastError(`Platform descriptor overrides reserved context key: ${key}`);
53
68
  }
54
- context[key] = formatValue(value, context, key);
69
+ const hosted = platform.default_server_context;
70
+ const chosen = onDefaultServer && hosted && Object.hasOwn(hosted, key) ? hosted[key] : value;
71
+ context[key] = formatValue(chosen, context, key);
55
72
  }
56
73
  return context;
57
74
  }
75
+ /**
76
+ * Compare server URLs as the same origin and path: the URL parser lowercases
77
+ * the scheme and host and drops a default port, so `https://GitLab.com:443/`
78
+ * matches `https://gitlab.com`. Both URLs passed `serverUrl` first, but that
79
+ * check accepts some the URL parser rejects, such as an IPv6 address with a
80
+ * zone ID; such a server is never a hosted default, so it is not a match.
81
+ */
82
+ function sameServer(left, right) {
83
+ const normalize = (url) => {
84
+ const parsed = URL.parse(url);
85
+ return parsed && `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(/\/+$/, "")}`;
86
+ };
87
+ const a = normalize(left);
88
+ return a !== null && a === normalize(right);
89
+ }
58
90
  /** Reject empty values, control characters, and anything that would read as a template token. */
59
91
  export function textValue(value, label) {
60
92
  if (!value || [...value].some(isControl)) {
@@ -130,11 +162,26 @@ export function quote(value, safe = "") {
130
162
  return result;
131
163
  }
132
164
  /**
133
- * Serialize a string as JSON with non-ASCII characters escaped. The result is
134
- * also a valid YAML scalar, and ASCII output stays readable in any editor.
165
+ * Serialize a string as an ASCII YAML double-quoted scalar. JSON's escapes for
166
+ * quotes, backslashes, and control characters are also YAML escapes, but JSON
167
+ * writes characters outside the Basic Multilingual Plane as two surrogate
168
+ * escapes, which YAML parsers reject. Those become one `\UXXXXXXXX` escape.
135
169
  */
136
- export function jsonAscii(value) {
137
- return JSON.stringify(value).replace(/[\u0080-￿]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
170
+ export function yamlString(value) {
171
+ let result = "";
172
+ for (const char of JSON.stringify(value)) {
173
+ const code = char.codePointAt(0) ?? 0;
174
+ if (code > 0xffff) {
175
+ result += `\\U${code.toString(16).padStart(8, "0")}`;
176
+ }
177
+ else if (code > 0x7f) {
178
+ result += `\\u${code.toString(16).padStart(4, "0")}`;
179
+ }
180
+ else {
181
+ result += char;
182
+ }
183
+ }
184
+ return result;
138
185
  }
139
186
  /** Replace `{KEY}` with earlier context values; `{{` and `}}` are literal braces. */
140
187
  export function formatValue(value, context, key) {
@@ -15,3 +15,9 @@ export interface GenerateResult {
15
15
  files: string[];
16
16
  }
17
17
  export declare function generate(options: GenerateOptions, root?: string): GenerateResult;
18
+ /**
19
+ * Resolve the output to the canonical path that will be written and check it:
20
+ * it must not exist yet and must be outside the source directory. Prompts use
21
+ * the same check so an answer is refused before any generation starts.
22
+ */
23
+ export declare function checkOutput(output: string, root?: string): string;
package/dist/generate.js CHANGED
@@ -13,15 +13,7 @@ export function generate(options, root = ROOT) {
13
13
  const platform = readPlatform(root, options.platform);
14
14
  const context = makeContext(options, platform);
15
15
  const files = collectFiles(root, options.platform, context, options.tier ?? DEFAULT_TIER);
16
- // The same canonical path is checked and written, so `..` after a symlink or a
17
- // case-only alias of the source directory cannot slip past the checks.
18
- const destination = canonicalPath(options.output);
19
- if (exists(destination)) {
20
- throw new PrecastError(`Output already exists; choose a new directory: ${destination}`);
21
- }
22
- if (isInside(destination, realpathSync.native(root))) {
23
- throw new PrecastError("Output must be outside the Precast source directory");
24
- }
16
+ const destination = checkOutput(options.output, root);
25
17
  const listing = [...files.keys()].sort(comparePaths);
26
18
  if (options.dryRun) {
27
19
  return { destination, files: listing };
@@ -48,6 +40,23 @@ export function generate(options, root = ROOT) {
48
40
  }
49
41
  return { destination, files: listing };
50
42
  }
43
+ /**
44
+ * Resolve the output to the canonical path that will be written and check it:
45
+ * it must not exist yet and must be outside the source directory. Prompts use
46
+ * the same check so an answer is refused before any generation starts.
47
+ */
48
+ export function checkOutput(output, root = ROOT) {
49
+ // The same canonical path is checked and written, so `..` after a symlink or a
50
+ // case-only alias of the source directory cannot slip past the checks.
51
+ const destination = canonicalPath(output);
52
+ if (exists(destination)) {
53
+ throw new PrecastError(`Output already exists; choose a new directory: ${destination}`);
54
+ }
55
+ if (isInside(destination, realpathSync.native(root))) {
56
+ throw new PrecastError("Output must be outside the Precast source directory");
57
+ }
58
+ return destination;
59
+ }
51
60
  /** True for anything at the path, including a dangling symlink. */
52
61
  function exists(path) {
53
62
  try {