@seangalie/precast 0.2.0 → 0.4.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 +35 -0
- package/README.md +39 -23
- package/dist/cli.d.ts +2 -6
- package/dist/cli.js +119 -20
- package/dist/errors.d.ts +3 -0
- package/dist/errors.js +3 -0
- package/dist/profile-command.d.ts +6 -0
- package/dist/profile-command.js +194 -0
- package/dist/profiles.d.ts +46 -1
- package/dist/profiles.js +192 -10
- package/dist/prompts.d.ts +24 -0
- package/dist/prompts.js +51 -37
- package/package.json +3 -3
- package/platforms/forgejo/files/.forgejo/SETUP.md.tmpl +19 -10
- package/platforms/forgejo/files/.forgejo/default_merge_message/MERGE_TEMPLATE.md +2 -0
- package/platforms/forgejo/files/.forgejo/workflows/lint.yml.tmpl +8 -5
- package/platforms/forgejo/files/.forgejo/workflows/pre-commit.yml.tmpl +10 -1
- package/platforms/forgejo/platform.json +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,41 @@ and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.4.0] - 2026-11-29
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- Generated Forgejo workflows run on the `node-latest` runner label instead of
|
|
13
|
+
`ubuntu-latest`. Forgejo's checkout action needs Node.js in the job container,
|
|
14
|
+
and runners that map `ubuntu-latest` to the stock Ubuntu image fail before
|
|
15
|
+
the first step. Generate with `--runner LABEL` to keep another label.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- The generated Forgejo Pre-commit job installs Python's venv with apt when the
|
|
20
|
+
job container lacks it, as official Node.js and Debian images do.
|
|
21
|
+
- Generated Forgejo projects' actionlint checks no longer reject runner labels
|
|
22
|
+
that actionlint doesn't know, such as `node-latest` or a `--runner` label.
|
|
23
|
+
|
|
24
|
+
## [0.3.0] - 2026-11-18
|
|
25
|
+
|
|
26
|
+
### Added
|
|
27
|
+
|
|
28
|
+
- `precast profile add`, `list`, and `remove` manage saved profiles without
|
|
29
|
+
editing the settings file. At a terminal, `profile add` asks for the name,
|
|
30
|
+
platform, server, and optional defaults.
|
|
31
|
+
- A prompted run offers your saved profiles as its first question, and after a
|
|
32
|
+
run that used `--server-url` without a profile it offers to save that server
|
|
33
|
+
as a new profile.
|
|
34
|
+
- Regular and full Forgejo projects get
|
|
35
|
+
`.forgejo/default_merge_message/MERGE_TEMPLATE.md`, so merge commits start
|
|
36
|
+
with the PR's title and reference and have an empty body.
|
|
37
|
+
|
|
38
|
+
### Changed
|
|
39
|
+
|
|
40
|
+
- `--config` no longer requires `--profile`: it also sets the settings file that
|
|
41
|
+
prompts read and save profiles in.
|
|
42
|
+
|
|
8
43
|
## [0.2.0] - 2026-11-18
|
|
9
44
|
|
|
10
45
|
### Added
|
package/README.md
CHANGED
|
@@ -186,45 +186,61 @@ If you used `--default-branch`, use that name in place of `main` above.
|
|
|
186
186
|
### Save your servers as profiles
|
|
187
187
|
|
|
188
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
|
-
|
|
189
|
+
every time, save them as a profile instead of typing them for each project. The
|
|
190
|
+
easiest way is to let Precast ask:
|
|
191
|
+
|
|
192
|
+
```sh
|
|
193
|
+
precast profile add
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
It asks for a name, the platform, the server, and optional defaults such as the
|
|
197
|
+
namespace, author, runner, and tier. You can also give them as options:
|
|
198
|
+
|
|
199
|
+
```sh
|
|
200
|
+
precast profile add work --platform gitlab \
|
|
201
|
+
--server-url https://gitlab.example.com --runner linux
|
|
202
|
+
precast profile list
|
|
203
|
+
precast profile remove work
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
Then use a profile with `--profile`. Anything you type on the command line wins
|
|
207
|
+
over the profile, and Precast asks for anything still missing, such as the
|
|
208
|
+
repository name:
|
|
209
|
+
|
|
210
|
+
```sh
|
|
211
|
+
precast --profile work --namespace group/subgroup --repo my-project --output my-project
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
When you run `precast` on its own and have saved profiles, the first question
|
|
215
|
+
offers them; press Enter to continue without one. After a run that used
|
|
216
|
+
`--server-url` without a profile, Precast offers to save that server as a new
|
|
217
|
+
profile.
|
|
218
|
+
|
|
219
|
+
Profiles live in a settings file:
|
|
191
220
|
|
|
192
221
|
- macOS and Linux: `~/.config/precast/config.json`, or `$XDG_CONFIG_HOME/precast/config.json`
|
|
193
222
|
- Windows: `%APPDATA%\precast\config.json`
|
|
194
223
|
|
|
195
|
-
|
|
224
|
+
You can edit it by hand too. Profile names use letters, digits, hyphens, and
|
|
225
|
+
underscores; a new name can't be only digits. Each profile names a `platform`
|
|
226
|
+
and may set `serverUrl`, `namespace`, `author`, `description`, `defaultBranch`,
|
|
227
|
+
`codeowner`, `runner`, and `tier`:
|
|
196
228
|
|
|
197
229
|
```json
|
|
198
230
|
{
|
|
199
231
|
"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
232
|
"work": {
|
|
208
233
|
"platform": "gitlab",
|
|
209
234
|
"serverUrl": "https://gitlab.example.com",
|
|
210
|
-
"runner": "linux"
|
|
211
|
-
"tier": "regular"
|
|
235
|
+
"runner": "linux"
|
|
212
236
|
}
|
|
213
237
|
}
|
|
214
238
|
}
|
|
215
239
|
```
|
|
216
240
|
|
|
217
|
-
|
|
218
|
-
|
|
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.
|
|
241
|
+
Commands that give every required option never read the settings file unless
|
|
242
|
+
you name a profile, so they always behave the same way. `--config` points
|
|
243
|
+
Precast at a different settings file.
|
|
228
244
|
|
|
229
245
|
### What Precast will not do
|
|
230
246
|
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
|
|
3
|
-
export interface Terminal {
|
|
4
|
-
interactive: boolean;
|
|
5
|
-
prompt<T>(use: (ask: Ask) => Promise<T>): Promise<T>;
|
|
6
|
-
}
|
|
1
|
+
import { type Terminal } from "./prompts.ts";
|
|
2
|
+
export type { Terminal } from "./prompts.ts";
|
|
7
3
|
export declare function main(argv: string[], root?: string, terminal?: Terminal): Promise<number>;
|
package/dist/cli.js
CHANGED
|
@@ -2,11 +2,12 @@ import { readFileSync } from "node:fs";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
import { DEFAULT_BRANCH, DEFAULT_DESCRIPTION } from "./context.js";
|
|
5
|
-
import { isSystemError, PrecastError } from "./errors.js";
|
|
5
|
+
import { isSystemError, PrecastError, UsageError } from "./errors.js";
|
|
6
6
|
import { generate, ROOT } from "./generate.js";
|
|
7
7
|
import { platformNames } from "./platforms.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
8
|
+
import { profileCommand, useHint } from "./profile-command.js";
|
|
9
|
+
import { checkNewProfileName, defaultConfigPath, listProfiles, profileNames, readProfile, saveProfile, } from "./profiles.js";
|
|
10
|
+
import { Cancelled, promptForMissing, questions, shellQuote, withTerminal, } from "./prompts.js";
|
|
10
11
|
import { header, paint } from "./style.js";
|
|
11
12
|
import { DEFAULT_TIER, isTier, TIERS } from "./tiers.js";
|
|
12
13
|
const OPTIONS = {
|
|
@@ -34,6 +35,7 @@ function usage(root) {
|
|
|
34
35
|
precast Ask for everything needed (at a terminal)
|
|
35
36
|
precast --platform <id> --namespace <owner> --repo <name> --output <dir> [options]
|
|
36
37
|
precast --profile <name> --repo <name> --output <dir> [options]
|
|
38
|
+
precast profile list|add|remove Manage saved profiles (see precast profile --help)
|
|
37
39
|
|
|
38
40
|
Render shared files and one platform's native files into a new project directory.
|
|
39
41
|
|
|
@@ -57,7 +59,7 @@ Never asked; set these as options:
|
|
|
57
59
|
|
|
58
60
|
Profiles (a profile can set everything above except the repository, output, and title):
|
|
59
61
|
--profile <name> Use saved settings, such as a self-hosted server; options given here win
|
|
60
|
-
--config <file> Settings file for
|
|
62
|
+
--config <file> Settings file for profiles (default: ${defaultConfigPath()})
|
|
61
63
|
|
|
62
64
|
Other options:
|
|
63
65
|
--dry-run Validate and list files without writing
|
|
@@ -66,14 +68,28 @@ Other options:
|
|
|
66
68
|
-v, --version Show the version
|
|
67
69
|
`;
|
|
68
70
|
}
|
|
69
|
-
/** Thrown for unusable command lines, which exit with status 2 like other CLIs. */
|
|
70
|
-
class UsageError extends Error {
|
|
71
|
-
}
|
|
72
71
|
const nodeTerminal = {
|
|
73
72
|
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
74
73
|
prompt: (use) => withTerminal(process.stdin, process.stdout, use),
|
|
75
74
|
};
|
|
76
75
|
export async function main(argv, root = ROOT, terminal = nodeTerminal) {
|
|
76
|
+
if (argv[0] === "profile") {
|
|
77
|
+
try {
|
|
78
|
+
return await profileCommand(argv.slice(1), root, terminal);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (error instanceof Cancelled) {
|
|
82
|
+
process.stderr.write("\nCancelled; no profile was saved\n");
|
|
83
|
+
return 130;
|
|
84
|
+
}
|
|
85
|
+
if (error instanceof UsageError ||
|
|
86
|
+
(isSystemError(error) && error.code.startsWith("ERR_PARSE_ARGS"))) {
|
|
87
|
+
process.stderr.write(`error: ${error.message}\nRun precast profile --help for usage.\n`);
|
|
88
|
+
return 2;
|
|
89
|
+
}
|
|
90
|
+
return failure(error);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
77
93
|
let values;
|
|
78
94
|
try {
|
|
79
95
|
values = parse(argv);
|
|
@@ -90,13 +106,12 @@ export async function main(argv, root = ROOT, terminal = nodeTerminal) {
|
|
|
90
106
|
return 0;
|
|
91
107
|
}
|
|
92
108
|
try {
|
|
109
|
+
const settings = values.config ?? defaultConfigPath();
|
|
93
110
|
let profile;
|
|
111
|
+
let pickedProfile;
|
|
94
112
|
try {
|
|
95
113
|
// 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;
|
|
114
|
+
profile = values.profile !== undefined ? readProfile(settings, values.profile) : undefined;
|
|
100
115
|
}
|
|
101
116
|
catch (error) {
|
|
102
117
|
return failure(error);
|
|
@@ -108,17 +123,43 @@ export async function main(argv, root = ROOT, terminal = nodeTerminal) {
|
|
|
108
123
|
const required = merge(values, profile);
|
|
109
124
|
// Reject a bad platform or tier before asking anything about it.
|
|
110
125
|
checkChoices(required.platform, values.tier ?? profile?.tier, root);
|
|
111
|
-
|
|
126
|
+
let missing = missingNames(required);
|
|
112
127
|
if (missing.length > 0 && terminal.interactive && !values["no-input"]) {
|
|
113
128
|
process.stdout.write(header(readVersion(root)));
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
129
|
+
const write = (text) => process.stdout.write(text);
|
|
130
|
+
const answers = await terminal.prompt(async (ask) => {
|
|
131
|
+
// With no profile or platform chosen yet, saved profiles come first.
|
|
132
|
+
const saved = new Map();
|
|
133
|
+
if (values.profile === undefined && values.platform === undefined) {
|
|
134
|
+
for (const entry of listProfiles(settings, root)) {
|
|
135
|
+
if (entry.profile) {
|
|
136
|
+
saved.set(entry.name, entry.profile);
|
|
137
|
+
}
|
|
138
|
+
else {
|
|
139
|
+
// One broken entry should not hide the others or stop the run.
|
|
140
|
+
write(`${paint("yellow", `! Skipping profile '${entry.name}': ${entry.error}`)}\n`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (saved.size > 0) {
|
|
145
|
+
const rows = [...saved].map(([name, settings]) => [name, summarize(settings)]);
|
|
146
|
+
pickedProfile = await questions(ask, write).choose(`${paint("bold", "Profiles")}\n`, rows, "Profile", { label: "none", value: undefined });
|
|
147
|
+
if (pickedProfile !== undefined) {
|
|
148
|
+
profile = saved.get(pickedProfile);
|
|
149
|
+
Object.assign(required, merge(values, profile));
|
|
150
|
+
checkChoices(required.platform, values.tier ?? profile?.tier, root);
|
|
151
|
+
missing = missingNames(required);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
// A session that is already asking also offers the tier, unless one was chosen.
|
|
155
|
+
const askTier = (values.tier ?? profile?.tier) === undefined;
|
|
156
|
+
return promptForMissing(required, ask, write, root, { askTier });
|
|
157
|
+
});
|
|
119
158
|
// `--key=value` keeps a value such as `-draft` from reading as an option,
|
|
120
159
|
// and the new options go before any `--` that ended the original options.
|
|
121
160
|
const added = missing.map((name) => `--${name}=${answers[name]}`);
|
|
161
|
+
if (pickedProfile !== undefined)
|
|
162
|
+
added.unshift(`--profile=${pickedProfile}`);
|
|
122
163
|
if (answers.tier !== undefined)
|
|
123
164
|
added.push(`--tier=${answers.tier}`);
|
|
124
165
|
tier = answers.tier;
|
|
@@ -159,12 +200,73 @@ export async function main(argv, root = ROOT, terminal = nodeTerminal) {
|
|
|
159
200
|
lines.push("", paint("dim", "Next time, run:"), ` ${paint("cyan", nextTime)}`);
|
|
160
201
|
}
|
|
161
202
|
process.stdout.write(`${lines.join("\n")}\n`);
|
|
203
|
+
// After a prompted run on a server of your own, offer to save it as a profile.
|
|
204
|
+
if (nextTime &&
|
|
205
|
+
profile === undefined &&
|
|
206
|
+
values["server-url"] !== undefined &&
|
|
207
|
+
!options.dryRun) {
|
|
208
|
+
// Saving is optional: a problem with it is reported, but the project was
|
|
209
|
+
// generated, so the run still succeeds.
|
|
210
|
+
try {
|
|
211
|
+
await offerToSave(options, settings, values.config, terminal);
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (error instanceof Cancelled) {
|
|
215
|
+
process.stderr.write("\nNo profile was saved\n");
|
|
216
|
+
}
|
|
217
|
+
else if (error instanceof PrecastError || isSystemError(error)) {
|
|
218
|
+
process.stderr.write(`warning: the profile was not saved: ${error.message}\n`);
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
162
225
|
return 0;
|
|
163
226
|
}
|
|
164
227
|
catch (error) {
|
|
165
228
|
return failure(error);
|
|
166
229
|
}
|
|
167
230
|
}
|
|
231
|
+
/** Ask for a profile name and save this run's server and settings under it. */
|
|
232
|
+
async function offerToSave(options, settings, config, terminal) {
|
|
233
|
+
const existing = new Set(profileNames(settings));
|
|
234
|
+
const write = (text) => process.stdout.write(text);
|
|
235
|
+
const name = await terminal.prompt((ask) => questions(ask, write).answer("Save this server as a profile?", "(a name, or Enter to skip)", (reply) => {
|
|
236
|
+
if (reply === "")
|
|
237
|
+
return reply;
|
|
238
|
+
checkNewProfileName(reply);
|
|
239
|
+
if (existing.has(reply)) {
|
|
240
|
+
throw new PrecastError(`Profile '${reply}' already exists; choose another name`);
|
|
241
|
+
}
|
|
242
|
+
return reply;
|
|
243
|
+
}));
|
|
244
|
+
if (name === "")
|
|
245
|
+
return;
|
|
246
|
+
const profile = {
|
|
247
|
+
platform: options.platform,
|
|
248
|
+
namespace: options.namespace,
|
|
249
|
+
tier: options.tier,
|
|
250
|
+
};
|
|
251
|
+
for (const [key, value] of Object.entries({
|
|
252
|
+
serverUrl: options.serverUrl,
|
|
253
|
+
author: options.author,
|
|
254
|
+
description: options.description,
|
|
255
|
+
defaultBranch: options.defaultBranch,
|
|
256
|
+
codeowner: options.codeowner,
|
|
257
|
+
runner: options.runner,
|
|
258
|
+
})) {
|
|
259
|
+
if (value !== undefined)
|
|
260
|
+
profile[key] = value;
|
|
261
|
+
}
|
|
262
|
+
saveProfile(settings, name, profile);
|
|
263
|
+
write(`${paint("green", `✓ Saved profile '${name}'`)} in ${settings}\n` +
|
|
264
|
+
` ${paint("dim", "Use it with:")} ${paint("cyan", useHint(name, config))}\n`);
|
|
265
|
+
}
|
|
266
|
+
/** A profile's platform and server, for choosing among saved profiles. */
|
|
267
|
+
function summarize(profile) {
|
|
268
|
+
return [profile.platform, profile.serverUrl, profile.namespace].filter(Boolean).join(" · ");
|
|
269
|
+
}
|
|
168
270
|
/** Report an expected failure without a stack trace; rethrow anything else. */
|
|
169
271
|
function failure(error) {
|
|
170
272
|
if (error instanceof PrecastError || isSystemError(error)) {
|
|
@@ -188,9 +290,6 @@ function parse(argv) {
|
|
|
188
290
|
strict: true,
|
|
189
291
|
allowPositionals: false,
|
|
190
292
|
});
|
|
191
|
-
if (values.config !== undefined && values.profile === undefined) {
|
|
192
|
-
throw new UsageError("--config only applies with --profile");
|
|
193
|
-
}
|
|
194
293
|
return values;
|
|
195
294
|
}
|
|
196
295
|
/** The required values from the command line and profile; options given explicitly win. */
|
package/dist/errors.d.ts
CHANGED
|
@@ -6,3 +6,6 @@ export declare class PrecastError extends Error {
|
|
|
6
6
|
export declare function isSystemError(error: unknown): error is NodeJS.ErrnoException & {
|
|
7
7
|
code: string;
|
|
8
8
|
};
|
|
9
|
+
/** Thrown for unusable command lines, which exit with status 2 like other CLIs. */
|
|
10
|
+
export declare class UsageError extends Error {
|
|
11
|
+
}
|
package/dist/errors.js
CHANGED
|
@@ -6,3 +6,6 @@ export class PrecastError extends Error {
|
|
|
6
6
|
export function isSystemError(error) {
|
|
7
7
|
return error instanceof Error && typeof error.code === "string";
|
|
8
8
|
}
|
|
9
|
+
/** Thrown for unusable command lines, which exit with status 2 like other CLIs. */
|
|
10
|
+
export class UsageError extends Error {
|
|
11
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Terminal } from "./prompts.ts";
|
|
2
|
+
export declare function profileUsage(root: string): string;
|
|
3
|
+
/** `precast profile <list|add|remove>`; returns the exit status. */
|
|
4
|
+
export declare function profileCommand(argv: string[], root: string, terminal: Terminal): Promise<number>;
|
|
5
|
+
/** How to use a saved profile, naming the settings file when it is not the default. */
|
|
6
|
+
export declare function useHint(name: string, config: string | undefined): string;
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import { PrecastError, UsageError } from "./errors.js";
|
|
3
|
+
import { platformNames, readPlatform } from "./platforms.js";
|
|
4
|
+
import { checkNewProfileName, checkProfileName, defaultConfigPath, listProfiles, profileNames, removeProfile, saveProfile, validateProfile, } from "./profiles.js";
|
|
5
|
+
import { choosePlatform, chooseTier, questions, shellQuote } from "./prompts.js";
|
|
6
|
+
import { isTier, TIERS } from "./tiers.js";
|
|
7
|
+
const OPTIONS = {
|
|
8
|
+
platform: { type: "string" },
|
|
9
|
+
"server-url": { type: "string" },
|
|
10
|
+
namespace: { type: "string" },
|
|
11
|
+
author: { type: "string" },
|
|
12
|
+
description: { type: "string" },
|
|
13
|
+
"default-branch": { type: "string" },
|
|
14
|
+
codeowner: { type: "string" },
|
|
15
|
+
runner: { type: "string" },
|
|
16
|
+
tier: { type: "string" },
|
|
17
|
+
config: { type: "string" },
|
|
18
|
+
force: { type: "boolean" },
|
|
19
|
+
"no-input": { type: "boolean" },
|
|
20
|
+
help: { type: "boolean", short: "h" },
|
|
21
|
+
};
|
|
22
|
+
export function profileUsage(root) {
|
|
23
|
+
return `Usage:
|
|
24
|
+
precast profile list
|
|
25
|
+
precast profile add <name> --platform <id> [options]
|
|
26
|
+
precast profile add Ask for the name and settings (at a terminal)
|
|
27
|
+
precast profile remove <name>
|
|
28
|
+
|
|
29
|
+
Save the settings you use for a server, such as your own Forgejo or an
|
|
30
|
+
organization's GitLab, and use them with precast --profile <name>.
|
|
31
|
+
|
|
32
|
+
Options for add (each is optional except --platform):
|
|
33
|
+
--platform <id> ${platformNames(root).join(", ")}
|
|
34
|
+
--server-url <url> The server; defaults to the platform's public one
|
|
35
|
+
--namespace <owner> Owner, organization, or GitLab group/subgroup
|
|
36
|
+
--author <name> Display name
|
|
37
|
+
--description <text> Project description
|
|
38
|
+
--default-branch <name> Default branch
|
|
39
|
+
--codeowner <@owner> Code owner for every file
|
|
40
|
+
--runner <label> Actions runner label or GitLab runner tag
|
|
41
|
+
--tier <tier> ${TIERS.join(", ")}
|
|
42
|
+
--force Replace a profile that already exists
|
|
43
|
+
|
|
44
|
+
Options for every subcommand:
|
|
45
|
+
--config <file> Settings file (default: ${defaultConfigPath()})
|
|
46
|
+
--no-input Never ask questions; report missing options instead
|
|
47
|
+
-h, --help Show this help
|
|
48
|
+
`;
|
|
49
|
+
}
|
|
50
|
+
function parse(argv) {
|
|
51
|
+
return parseArgs({ args: argv, options: OPTIONS, strict: true, allowPositionals: true });
|
|
52
|
+
}
|
|
53
|
+
/** `precast profile <list|add|remove>`; returns the exit status. */
|
|
54
|
+
export async function profileCommand(argv, root, terminal) {
|
|
55
|
+
const { values, positionals } = parse(argv);
|
|
56
|
+
const [action, ...names] = positionals;
|
|
57
|
+
if (values.help) {
|
|
58
|
+
process.stdout.write(profileUsage(root));
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
const file = values.config ?? defaultConfigPath();
|
|
62
|
+
const write = (text) => process.stdout.write(text);
|
|
63
|
+
if (names.length > 1) {
|
|
64
|
+
throw new UsageError(`expected one profile name, got: ${names.join(" ")}`);
|
|
65
|
+
}
|
|
66
|
+
const name = names[0];
|
|
67
|
+
if (action === "list") {
|
|
68
|
+
if (name !== undefined)
|
|
69
|
+
throw new UsageError("profile list takes no name");
|
|
70
|
+
const entries = listProfiles(file, root);
|
|
71
|
+
if (entries.length === 0) {
|
|
72
|
+
write(`No profiles in ${file}. Add one with: precast profile add <name>\n`);
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
write(`Profiles in ${file}:\n`);
|
|
76
|
+
const width = Math.max(...entries.map((entry) => entry.name.length));
|
|
77
|
+
for (const entry of entries) {
|
|
78
|
+
const detail = entry.profile ? describe(entry.profile, root) : `invalid: ${entry.error}`;
|
|
79
|
+
write(` ${entry.name.padEnd(width)} ${detail}\n`);
|
|
80
|
+
}
|
|
81
|
+
return 0;
|
|
82
|
+
}
|
|
83
|
+
if (action === "remove") {
|
|
84
|
+
if (name === undefined)
|
|
85
|
+
throw new UsageError("profile remove needs a profile name");
|
|
86
|
+
removeProfile(file, name);
|
|
87
|
+
write(`Removed profile '${name}' from ${file}\n`);
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
if (action === "add") {
|
|
91
|
+
return add(name, values, file, root, terminal, write);
|
|
92
|
+
}
|
|
93
|
+
throw new UsageError(action === undefined
|
|
94
|
+
? "profile needs a subcommand: list, add, or remove"
|
|
95
|
+
: `unknown profile subcommand: ${action}; use list, add, or remove`);
|
|
96
|
+
}
|
|
97
|
+
async function add(given, values, file, root, terminal, write) {
|
|
98
|
+
const replace = values.force === true;
|
|
99
|
+
const existing = new Set(profileNames(file));
|
|
100
|
+
const available = (name) => {
|
|
101
|
+
// Replacing an existing name keeps older names usable; new ones follow the stricter rule.
|
|
102
|
+
if (existing.has(name) && replace)
|
|
103
|
+
return checkProfileName(name);
|
|
104
|
+
checkNewProfileName(name);
|
|
105
|
+
if (existing.has(name)) {
|
|
106
|
+
throw new PrecastError(`Profile '${name}' already exists in ${file}; use --force to replace it`);
|
|
107
|
+
}
|
|
108
|
+
return name;
|
|
109
|
+
};
|
|
110
|
+
if (values.tier !== undefined && !isTier(values.tier)) {
|
|
111
|
+
throw new UsageError(`--tier must be one of: ${TIERS.join(", ")}`);
|
|
112
|
+
}
|
|
113
|
+
if (values.platform !== undefined && !platformNames(root).includes(values.platform)) {
|
|
114
|
+
throw new UsageError(`--platform must be one of: ${platformNames(root).join(", ")}`);
|
|
115
|
+
}
|
|
116
|
+
// Check a given name before asking anything, so answers are not wasted.
|
|
117
|
+
if (given !== undefined)
|
|
118
|
+
available(given);
|
|
119
|
+
// A draft holds unset values as undefined until `toProfile` drops them.
|
|
120
|
+
const profile = {
|
|
121
|
+
platform: values.platform ?? "",
|
|
122
|
+
serverUrl: values["server-url"],
|
|
123
|
+
namespace: values.namespace,
|
|
124
|
+
author: values.author,
|
|
125
|
+
description: values.description,
|
|
126
|
+
defaultBranch: values["default-branch"],
|
|
127
|
+
codeowner: values.codeowner,
|
|
128
|
+
runner: values.runner,
|
|
129
|
+
tier: values.tier !== undefined && isTier(values.tier) ? values.tier : undefined,
|
|
130
|
+
};
|
|
131
|
+
let name = given;
|
|
132
|
+
if (name === undefined || values.platform === undefined) {
|
|
133
|
+
if (!terminal.interactive || values["no-input"]) {
|
|
134
|
+
const missing = [
|
|
135
|
+
name === undefined ? "a profile name" : "",
|
|
136
|
+
values.platform === undefined ? "--platform" : "",
|
|
137
|
+
]
|
|
138
|
+
.filter(Boolean)
|
|
139
|
+
.join(" and ");
|
|
140
|
+
throw new UsageError(`profile add needs ${missing}`);
|
|
141
|
+
}
|
|
142
|
+
await terminal.prompt(async (ask) => {
|
|
143
|
+
const q = questions(ask, write);
|
|
144
|
+
name ??= await q.answer("Profile name", "(letters, digits, - and _)", available);
|
|
145
|
+
// Each answer is checked by validating the profile with it, the same rules
|
|
146
|
+
// as command-line options; Enter leaves an optional value unset.
|
|
147
|
+
const check = (key) => (reply) => {
|
|
148
|
+
validateProfile(toProfile({ ...profile, [key]: reply || undefined }), root);
|
|
149
|
+
return reply;
|
|
150
|
+
};
|
|
151
|
+
if (values.platform === undefined) {
|
|
152
|
+
profile.platform = await choosePlatform(q, root);
|
|
153
|
+
const server = readPlatform(root, profile.platform).server_url;
|
|
154
|
+
profile.serverUrl ??=
|
|
155
|
+
(await q.answer("Server URL", `(Enter for ${server})`, check("serverUrl"))) || undefined;
|
|
156
|
+
profile.namespace ??=
|
|
157
|
+
(await q.answer("Namespace", "(Enter to ask each time)", check("namespace"))) ||
|
|
158
|
+
undefined;
|
|
159
|
+
profile.author ??=
|
|
160
|
+
(await q.answer("Author", "(Enter to use the namespace)", check("author"))) || undefined;
|
|
161
|
+
profile.runner ??=
|
|
162
|
+
(await q.answer("Runner label or tag", "(Enter for the platform's default)", check("runner"))) || undefined;
|
|
163
|
+
profile.tier ??= await chooseTier(q, { label: "none", value: undefined });
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
const saved = validateProfile(toProfile(profile), root);
|
|
168
|
+
saveProfile(file, name, saved, { replace });
|
|
169
|
+
write(`${existing.has(name) ? "Replaced" : "Saved"} profile '${name}' in ${file}\n` +
|
|
170
|
+
`Use it with: ${useHint(name, values.config)}\n`);
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
function toProfile(draft) {
|
|
174
|
+
return Object.fromEntries(Object.entries(draft).filter(([, value]) => value !== undefined));
|
|
175
|
+
}
|
|
176
|
+
/** One line of `profile list`: platform, server, and the defaults it sets. */
|
|
177
|
+
function describe(profile, root) {
|
|
178
|
+
const known = platformNames(root).includes(profile.platform);
|
|
179
|
+
const server = profile.serverUrl ??
|
|
180
|
+
(known ? `${readPlatform(root, profile.platform).server_url} (default)` : "unknown platform");
|
|
181
|
+
const extras = [
|
|
182
|
+
profile.namespace && `namespace ${profile.namespace}`,
|
|
183
|
+
profile.author && `author ${profile.author}`,
|
|
184
|
+
profile.runner && `runner ${profile.runner}`,
|
|
185
|
+
profile.tier && `tier ${profile.tier}`,
|
|
186
|
+
].filter(Boolean);
|
|
187
|
+
return [profile.platform, server, ...extras].join(" · ");
|
|
188
|
+
}
|
|
189
|
+
/** How to use a saved profile, naming the settings file when it is not the default. */
|
|
190
|
+
export function useHint(name, config) {
|
|
191
|
+
return config === undefined
|
|
192
|
+
? `precast --profile ${name}`
|
|
193
|
+
: `precast ${shellQuote(`--config=${config}`)} --profile ${name}`;
|
|
194
|
+
}
|
package/dist/profiles.d.ts
CHANGED
|
@@ -19,5 +19,50 @@ export interface Profile {
|
|
|
19
19
|
* directory on macOS and Linux, and the roaming application data folder on Windows.
|
|
20
20
|
*/
|
|
21
21
|
export declare function defaultConfigPath(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, home?: string): string;
|
|
22
|
-
/**
|
|
22
|
+
/** Profiles by name, in the order the settings file lists them. */
|
|
23
|
+
export type Profiles = Map<string, Profile>;
|
|
24
|
+
/** Reject names that would be awkward on a command line or in JSON. */
|
|
25
|
+
export declare function checkProfileName(name: string): string;
|
|
26
|
+
/** The stricter rule for a name being created: also not only digits. */
|
|
27
|
+
export declare function checkNewProfileName(name: string): string;
|
|
28
|
+
/** The names a settings file holds, valid or not. */
|
|
29
|
+
export declare function profileNames(file: string): string[];
|
|
30
|
+
/** One entry of a settings file: its profile, or why it is invalid. */
|
|
31
|
+
export type ProfileEntry = {
|
|
32
|
+
name: string;
|
|
33
|
+
profile: Profile;
|
|
34
|
+
error?: undefined;
|
|
35
|
+
} | {
|
|
36
|
+
name: string;
|
|
37
|
+
profile?: undefined;
|
|
38
|
+
error: string;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Every entry in file order, each checked on its own so one bad entry hides no
|
|
42
|
+
* others. With `root`, values are also checked as options would be, such as the
|
|
43
|
+
* platform name and server URL.
|
|
44
|
+
*/
|
|
45
|
+
export declare function listProfiles(file: string, root?: string): ProfileEntry[];
|
|
46
|
+
/** Read every profile; any invalid entry is an error. */
|
|
47
|
+
export declare function readProfiles(file: string): Profiles;
|
|
48
|
+
/** Read one named profile, validating only that entry. */
|
|
23
49
|
export declare function readProfile(file: string, name: string): Profile;
|
|
50
|
+
/**
|
|
51
|
+
* Check a profile's values with the same rules as command-line options, by
|
|
52
|
+
* building a project context from them with a placeholder repository.
|
|
53
|
+
*/
|
|
54
|
+
export declare function validateProfile(profile: Profile, root: string): Profile;
|
|
55
|
+
/**
|
|
56
|
+
* Add or replace one profile and write the file in one step, keeping the other
|
|
57
|
+
* entries as they were. Replacing an existing profile needs `replace`.
|
|
58
|
+
*/
|
|
59
|
+
export declare function saveProfile(file: string, name: string, profile: Profile, { replace, lockWaitMs, beforeReplace, }?: {
|
|
60
|
+
replace?: boolean;
|
|
61
|
+
lockWaitMs?: number;
|
|
62
|
+
/** Called with the written temporary file before it replaces the original; for tests. */
|
|
63
|
+
beforeReplace?: (temporary: string) => void;
|
|
64
|
+
}): void;
|
|
65
|
+
/** Remove one profile; it must exist. */
|
|
66
|
+
export declare function removeProfile(file: string, name: string, { lockWaitMs }?: {
|
|
67
|
+
lockWaitMs?: number;
|
|
68
|
+
}): void;
|
package/dist/profiles.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { existsSync } from "node:fs";
|
|
1
|
+
import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { makeContext } from "./context.js";
|
|
4
5
|
import { PrecastError } from "./errors.js";
|
|
5
|
-
import { readJson } from "./platforms.js";
|
|
6
|
+
import { readJson, readPlatform } from "./platforms.js";
|
|
6
7
|
import { isPlainObject, isTier } from "./tiers.js";
|
|
7
8
|
const STRING_FIELDS = [
|
|
8
9
|
"platform",
|
|
@@ -15,6 +16,10 @@ const STRING_FIELDS = [
|
|
|
15
16
|
"runner",
|
|
16
17
|
];
|
|
17
18
|
const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
19
|
+
// New names made only of digits are refused so they cannot be mistaken for
|
|
20
|
+
// list numbers; existing ones still work, so older settings files stay usable.
|
|
21
|
+
const DIGITS = /^[0-9]+$/;
|
|
22
|
+
const LOCK_WAIT_MS = 10_000;
|
|
18
23
|
/**
|
|
19
24
|
* Where profiles live unless `--config` names another file: the XDG config
|
|
20
25
|
* directory on macOS and Linux, and the roaming application data folder on Windows.
|
|
@@ -31,13 +36,25 @@ export function defaultConfigPath(env = process.env, platform = process.platform
|
|
|
31
36
|
: undefined;
|
|
32
37
|
return path.posix.join(xdg ?? path.posix.join(home, ".config"), "precast", "config.json");
|
|
33
38
|
}
|
|
34
|
-
/**
|
|
35
|
-
export function
|
|
39
|
+
/** Reject names that would be awkward on a command line or in JSON. */
|
|
40
|
+
export function checkProfileName(name) {
|
|
36
41
|
if (!PROFILE_NAME.test(name)) {
|
|
37
|
-
throw new PrecastError(`Invalid profile name: '${name}'`);
|
|
42
|
+
throw new PrecastError(`Invalid profile name: '${name}'; use letters, digits, hyphens, and underscores`);
|
|
43
|
+
}
|
|
44
|
+
return name;
|
|
45
|
+
}
|
|
46
|
+
/** The stricter rule for a name being created: also not only digits. */
|
|
47
|
+
export function checkNewProfileName(name) {
|
|
48
|
+
checkProfileName(name);
|
|
49
|
+
if (DIGITS.test(name)) {
|
|
50
|
+
throw new PrecastError(`Invalid profile name: '${name}'; a new name can't be only digits, which would read as a list number`);
|
|
38
51
|
}
|
|
52
|
+
return name;
|
|
53
|
+
}
|
|
54
|
+
/** The raw entries of a settings file, checking only its outer shape; a missing file has none. */
|
|
55
|
+
function readEntries(file) {
|
|
39
56
|
if (!existsSync(file)) {
|
|
40
|
-
|
|
57
|
+
return new Map();
|
|
41
58
|
}
|
|
42
59
|
const settings = readJson(file);
|
|
43
60
|
if (!isPlainObject(settings) || !isPlainObject(settings.profiles)) {
|
|
@@ -48,12 +65,177 @@ export function readProfile(file, name) {
|
|
|
48
65
|
throw new PrecastError(`${file} has an unknown field: ${key}`);
|
|
49
66
|
}
|
|
50
67
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
68
|
+
return new Map(Object.entries(settings.profiles));
|
|
69
|
+
}
|
|
70
|
+
/** The names a settings file holds, valid or not. */
|
|
71
|
+
export function profileNames(file) {
|
|
72
|
+
return [...readEntries(file).keys()];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Every entry in file order, each checked on its own so one bad entry hides no
|
|
76
|
+
* others. With `root`, values are also checked as options would be, such as the
|
|
77
|
+
* platform name and server URL.
|
|
78
|
+
*/
|
|
79
|
+
export function listProfiles(file, root) {
|
|
80
|
+
return [...readEntries(file)].map(([name, value]) => {
|
|
81
|
+
try {
|
|
82
|
+
checkProfileName(name);
|
|
83
|
+
const profile = parseProfile(value, `Profile '${name}'`);
|
|
84
|
+
if (root !== undefined)
|
|
85
|
+
validateProfile(profile, root);
|
|
86
|
+
return { name, profile };
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
if (!(error instanceof PrecastError))
|
|
90
|
+
throw error;
|
|
91
|
+
return { name, error: error.message };
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/** Read every profile; any invalid entry is an error. */
|
|
96
|
+
export function readProfiles(file) {
|
|
97
|
+
return new Map([...readEntries(file)].map(([name, value]) => [
|
|
98
|
+
name,
|
|
99
|
+
parseProfile(value, `Profile '${name}' in ${file}`),
|
|
100
|
+
]));
|
|
101
|
+
}
|
|
102
|
+
/** Read one named profile, validating only that entry. */
|
|
103
|
+
export function readProfile(file, name) {
|
|
104
|
+
checkProfileName(name);
|
|
105
|
+
if (!existsSync(file)) {
|
|
106
|
+
throw new PrecastError(`No settings file at ${file}; create it to use --profile`);
|
|
107
|
+
}
|
|
108
|
+
const entries = readEntries(file);
|
|
109
|
+
if (!entries.has(name)) {
|
|
110
|
+
const known = [...entries.keys()].sort();
|
|
54
111
|
throw new PrecastError(`No profile '${name}' in ${file}${known.length > 0 ? `; it has: ${known.join(", ")}` : ""}`);
|
|
55
112
|
}
|
|
56
|
-
return parseProfile(
|
|
113
|
+
return parseProfile(entries.get(name), `Profile '${name}' in ${file}`);
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Check a profile's values with the same rules as command-line options, by
|
|
117
|
+
* building a project context from them with a placeholder repository.
|
|
118
|
+
*/
|
|
119
|
+
export function validateProfile(profile, root) {
|
|
120
|
+
const platform = readPlatform(root, profile.platform);
|
|
121
|
+
makeContext({
|
|
122
|
+
platform: profile.platform,
|
|
123
|
+
namespace: profile.namespace ?? "example",
|
|
124
|
+
repo: "example",
|
|
125
|
+
serverUrl: profile.serverUrl,
|
|
126
|
+
author: profile.author,
|
|
127
|
+
description: profile.description,
|
|
128
|
+
defaultBranch: profile.defaultBranch,
|
|
129
|
+
codeowner: profile.codeowner,
|
|
130
|
+
runner: profile.runner,
|
|
131
|
+
}, platform);
|
|
132
|
+
return profile;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Add or replace one profile and write the file in one step, keeping the other
|
|
136
|
+
* entries as they were. Replacing an existing profile needs `replace`.
|
|
137
|
+
*/
|
|
138
|
+
export function saveProfile(file, name, profile, { replace = false, lockWaitMs = LOCK_WAIT_MS, beforeReplace, } = {}) {
|
|
139
|
+
checkProfileName(name);
|
|
140
|
+
updateEntries(file, lockWaitMs, beforeReplace, (entries) => {
|
|
141
|
+
if (!entries.has(name))
|
|
142
|
+
checkNewProfileName(name);
|
|
143
|
+
if (entries.has(name) && !replace) {
|
|
144
|
+
throw new PrecastError(`Profile '${name}' already exists in ${file}; use --force to replace it`);
|
|
145
|
+
}
|
|
146
|
+
entries.set(name, normalize(profile));
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
/** Remove one profile; it must exist. */
|
|
150
|
+
export function removeProfile(file, name, { lockWaitMs = LOCK_WAIT_MS } = {}) {
|
|
151
|
+
checkProfileName(name);
|
|
152
|
+
updateEntries(file, lockWaitMs, undefined, (entries) => {
|
|
153
|
+
if (!entries.delete(name)) {
|
|
154
|
+
throw new PrecastError(`No profile '${name}' in ${file}`);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/** Keep fields in a stable order and drop unset ones. */
|
|
159
|
+
function normalize(profile) {
|
|
160
|
+
const result = { platform: profile.platform };
|
|
161
|
+
for (const key of [...STRING_FIELDS.slice(1), "tier"]) {
|
|
162
|
+
const value = profile[key];
|
|
163
|
+
if (value !== undefined)
|
|
164
|
+
result[key] = value;
|
|
165
|
+
}
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Read, change, and write the settings file while holding its lock, so two
|
|
170
|
+
* saves at once cannot each overwrite the other's change. A symlinked file is
|
|
171
|
+
* written at its target, and an existing file keeps its permissions.
|
|
172
|
+
*/
|
|
173
|
+
function updateEntries(file, lockWaitMs, beforeReplace, change) {
|
|
174
|
+
const target = writeTarget(file);
|
|
175
|
+
mkdirSync(path.dirname(target), { recursive: true });
|
|
176
|
+
withLock(`${target}.lock`, lockWaitMs, () => {
|
|
177
|
+
const entries = readEntries(target);
|
|
178
|
+
change(entries);
|
|
179
|
+
const mode = existsSync(target) ? statSync(target).mode & 0o777 : undefined;
|
|
180
|
+
const text = `${JSON.stringify({ profiles: Object.fromEntries(entries) }, null, 2)}\n`;
|
|
181
|
+
// Write beside the target and rename, so an interrupted save cannot leave it half written.
|
|
182
|
+
const temporary = `${target}.${process.pid}.tmp`;
|
|
183
|
+
try {
|
|
184
|
+
// Create the file with the original's permissions before any data goes in,
|
|
185
|
+
// so private settings are never readable more widely, even for a moment.
|
|
186
|
+
// The lock is held, so a leftover temporary file is from a stopped run.
|
|
187
|
+
rmSync(temporary, { force: true });
|
|
188
|
+
writeFileSync(temporary, text, { flag: "wx", mode: mode ?? 0o666 });
|
|
189
|
+
beforeReplace?.(temporary);
|
|
190
|
+
// The umask may have narrowed the mode at creation; restore it exactly.
|
|
191
|
+
if (mode !== undefined)
|
|
192
|
+
chmodSync(temporary, mode);
|
|
193
|
+
renameSync(temporary, target);
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
rmSync(temporary, { force: true });
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
/** The real file behind `file`, following symlinks; a broken symlink is an error. */
|
|
201
|
+
function writeTarget(file) {
|
|
202
|
+
const stats = lstatSync(file, { throwIfNoEntry: false });
|
|
203
|
+
if (!stats?.isSymbolicLink())
|
|
204
|
+
return file;
|
|
205
|
+
try {
|
|
206
|
+
return realpathSync.native(file);
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (error.code !== "ENOENT")
|
|
210
|
+
throw error;
|
|
211
|
+
throw new PrecastError(`${file} is a symlink to a missing file; fix or remove it first`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
function withLock(lock, waitMs, use) {
|
|
215
|
+
const deadline = Date.now() + waitMs;
|
|
216
|
+
for (;;) {
|
|
217
|
+
try {
|
|
218
|
+
closeSync(openSync(lock, "wx"));
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
catch (error) {
|
|
222
|
+
if (error.code !== "EEXIST")
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
225
|
+
// An old lock is never taken over automatically: removing it can race with
|
|
226
|
+
// another run that is taking it over too. The person decides instead.
|
|
227
|
+
if (Date.now() >= deadline) {
|
|
228
|
+
throw new PrecastError(`Another precast is updating ${lock.slice(0, -".lock".length)}, or one stopped while saving. ` +
|
|
229
|
+
`If no precast is running, delete ${lock}`);
|
|
230
|
+
}
|
|
231
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
use();
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
rmSync(lock, { force: true });
|
|
238
|
+
}
|
|
57
239
|
}
|
|
58
240
|
function parseProfile(value, label) {
|
|
59
241
|
if (!isPlainObject(value)) {
|
package/dist/prompts.d.ts
CHANGED
|
@@ -12,10 +12,34 @@ export type Answers = Record<keyof RequiredValues, string> & {
|
|
|
12
12
|
};
|
|
13
13
|
/** Ask one question; resolves undefined when the person cancels or input ends. */
|
|
14
14
|
export type Ask = (question: string) => Promise<string | undefined>;
|
|
15
|
+
/** Where questions are asked; tests replace it with scripted answers. */
|
|
16
|
+
export interface Terminal {
|
|
17
|
+
interactive: boolean;
|
|
18
|
+
prompt<T>(use: (ask: Ask) => Promise<T>): Promise<T>;
|
|
19
|
+
}
|
|
15
20
|
/** Thrown when the person cancels a prompt, so nothing is generated. */
|
|
16
21
|
export declare class Cancelled extends Error {
|
|
17
22
|
constructor();
|
|
18
23
|
}
|
|
24
|
+
/** The questions a session can ask, sharing one terminal and one style. */
|
|
25
|
+
export interface Questions {
|
|
26
|
+
/** Ask until `check` accepts the trimmed reply; it throws `PrecastError` to reject one. */
|
|
27
|
+
answer<T extends string>(label: string, hint: string, check: (value: string) => T): Promise<T>;
|
|
28
|
+
/** Show a numbered list, then accept a number or a name; `empty` is what Enter means. */
|
|
29
|
+
choose<T extends string>(title: string, rows: readonly (readonly [T, string])[], label: string, empty?: {
|
|
30
|
+
label: string;
|
|
31
|
+
value: T | undefined;
|
|
32
|
+
}): Promise<T | undefined>;
|
|
33
|
+
write(text: string): void;
|
|
34
|
+
}
|
|
35
|
+
export declare function questions(ask: Ask, write: (text: string) => void, stream?: NodeJS.WritableStream): Questions;
|
|
36
|
+
/** Ask for a platform from the descriptors in `root`. */
|
|
37
|
+
export declare function choosePlatform(q: Questions, root: string, stream?: NodeJS.WritableStream): Promise<string>;
|
|
38
|
+
/** Ask for a tier; Enter means `empty`, which may be a tier or "none". */
|
|
39
|
+
export declare function chooseTier(q: Questions, empty: {
|
|
40
|
+
label: string;
|
|
41
|
+
value: Tier | undefined;
|
|
42
|
+
}, stream?: NodeJS.WritableStream): Promise<Tier | undefined>;
|
|
19
43
|
/**
|
|
20
44
|
* Ask for each missing required value in turn. Answers go through the same
|
|
21
45
|
* checks as command-line options, and an invalid answer is asked again.
|
package/dist/prompts.js
CHANGED
|
@@ -4,7 +4,7 @@ import { PrecastError } from "./errors.js";
|
|
|
4
4
|
import { checkOutput } from "./generate.js";
|
|
5
5
|
import { platformNames, readPlatform } from "./platforms.js";
|
|
6
6
|
import { paint } from "./style.js";
|
|
7
|
-
import { DEFAULT_TIER,
|
|
7
|
+
import { DEFAULT_TIER, TIERS } from "./tiers.js";
|
|
8
8
|
const TIER_SUMMARIES = {
|
|
9
9
|
slim: "the essentials, for personal projects and experiments",
|
|
10
10
|
regular: "adds policies, templates, pre-commit, and CI",
|
|
@@ -16,11 +16,7 @@ export class Cancelled extends Error {
|
|
|
16
16
|
super("Cancelled; no files were written");
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
-
|
|
20
|
-
* Ask for each missing required value in turn. Answers go through the same
|
|
21
|
-
* checks as command-line options, and an invalid answer is asked again.
|
|
22
|
-
*/
|
|
23
|
-
export async function promptForMissing(values, ask, write, root, { stream, askTier = false } = {}) {
|
|
19
|
+
export function questions(ask, write, stream) {
|
|
24
20
|
const answer = async (label, hint, check) => {
|
|
25
21
|
const shown = hint ? ` ${paint("dim", hint, stream)}` : "";
|
|
26
22
|
const question = `${paint("cyan", "?", stream)} ${paint("bold", label, stream)}${shown} ${paint("dim", "›", stream)} `;
|
|
@@ -38,43 +34,61 @@ export async function promptForMissing(values, ask, write, root, { stream, askTi
|
|
|
38
34
|
}
|
|
39
35
|
}
|
|
40
36
|
};
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
write(` ${paint("cyan", String(index + 1), stream)} ${name}
|
|
37
|
+
const choose = async (title, rows, label, empty) => {
|
|
38
|
+
write(title);
|
|
39
|
+
const width = Math.max(...rows.map(([name]) => name.length));
|
|
40
|
+
for (const [index, [name, summary]] of rows.entries()) {
|
|
41
|
+
const detail = summary ? ` ${paint("dim", summary, stream)}` : "";
|
|
42
|
+
write(` ${paint("cyan", String(index + 1), stream)} ${name.padEnd(width)}${detail}`.trimEnd() +
|
|
43
|
+
"\n");
|
|
47
44
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
45
|
+
const names = rows.map(([name]) => name);
|
|
46
|
+
const hint = `(1-${rows.length} or a name${empty ? `, Enter for ${empty.label}` : ""})`;
|
|
47
|
+
// A sentinel lets Enter mean "none" without widening every answer to undefined.
|
|
48
|
+
const NONE = "\u0000none";
|
|
49
|
+
const chosen = await answer(label, hint, (reply) => {
|
|
50
|
+
if (reply === "" && empty)
|
|
51
|
+
return empty.value ?? NONE;
|
|
52
|
+
// An exact name wins over a row number, so a name can never pick another row.
|
|
53
|
+
const pick = names.includes(reply)
|
|
54
|
+
? reply
|
|
55
|
+
: (names[Number(reply) - 1] ?? reply);
|
|
56
|
+
if (!names.includes(pick)) {
|
|
57
|
+
throw new PrecastError(`Choose 1-${rows.length} or one of: ${names.join(", ")}`);
|
|
52
58
|
}
|
|
53
|
-
return
|
|
59
|
+
return pick;
|
|
54
60
|
});
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
61
|
+
return chosen === NONE ? undefined : chosen;
|
|
62
|
+
};
|
|
63
|
+
return { answer, choose, write };
|
|
64
|
+
}
|
|
65
|
+
/** Ask for a platform from the descriptors in `root`. */
|
|
66
|
+
export async function choosePlatform(q, root, stream) {
|
|
67
|
+
const rows = platformNames(root).map((name) => [name, ""]);
|
|
68
|
+
const chosen = await q.choose(`${paint("bold", "Platforms", stream)}\n`, rows, "Platform");
|
|
69
|
+
return chosen;
|
|
70
|
+
}
|
|
71
|
+
/** Ask for a tier; Enter means `empty`, which may be a tier or "none". */
|
|
72
|
+
export async function chooseTier(q, empty, stream) {
|
|
73
|
+
const title = `${paint("bold", "Tiers", stream)} ${paint("dim", "(each adds to the one before)", stream)}\n`;
|
|
74
|
+
return q.choose(title, TIERS.map((name) => [name, TIER_SUMMARIES[name]]), "Tier", empty);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Ask for each missing required value in turn. Answers go through the same
|
|
78
|
+
* checks as command-line options, and an invalid answer is asked again.
|
|
79
|
+
*/
|
|
80
|
+
export async function promptForMissing(values, ask, write, root, { stream, askTier = false } = {}) {
|
|
81
|
+
const q = questions(ask, write, stream);
|
|
82
|
+
const platform = values.platform ?? (await choosePlatform(q, root, stream));
|
|
83
|
+
const tier = askTier
|
|
84
|
+
? await chooseTier(q, { label: DEFAULT_TIER, value: DEFAULT_TIER }, stream)
|
|
85
|
+
: undefined;
|
|
72
86
|
const nested = readPlatform(root, platform).nested_namespaces;
|
|
73
87
|
const namespace = values.namespace ??
|
|
74
|
-
(await answer("Namespace", nested ? "(owner, organization, or group/subgroup)" : "(owner or organization)", (reply) => checkNamespace(reply, nested)));
|
|
75
|
-
const repo = values.repo ?? (await answer("Repository name", "", checkRepo));
|
|
88
|
+
(await q.answer("Namespace", nested ? "(owner, organization, or group/subgroup)" : "(owner or organization)", (reply) => checkNamespace(reply, nested)));
|
|
89
|
+
const repo = values.repo ?? (await q.answer("Repository name", "", checkRepo));
|
|
76
90
|
const output = values.output ??
|
|
77
|
-
(await answer("Output folder", `(${repo})`, (reply) => {
|
|
91
|
+
(await q.answer("Output folder", `(${repo})`, (reply) => {
|
|
78
92
|
const folder = reply || repo;
|
|
79
93
|
// The generator's own check, so an answer it would refuse is asked again.
|
|
80
94
|
checkOutput(folder, root);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seangalie/precast",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Generate new Forgejo, GitHub, and GitLab projects with documentation, checks, and forge settings in place",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Sean Galie",
|
|
@@ -30,8 +30,8 @@
|
|
|
30
30
|
"typecheck": "tsc -p tsconfig.json",
|
|
31
31
|
"lint": "biome check",
|
|
32
32
|
"format": "biome check --write",
|
|
33
|
-
"test": "node --test
|
|
34
|
-
"check-generated": "node
|
|
33
|
+
"test": "node --test \"test/**/*.test.ts\"",
|
|
34
|
+
"check-generated": "node scripts/check-generated.ts",
|
|
35
35
|
"prepack": "npm run build",
|
|
36
36
|
"prepublishOnly": "npm run build && npm test && node scripts/check-package.ts"
|
|
37
37
|
},
|
|
@@ -11,20 +11,24 @@ Generate with `--tier regular` or `--tier full` for issue templates, CI, and aut
|
|
|
11
11
|
@@TIERS regular@@
|
|
12
12
|
- [ ] Enable the repository units I need under Settings, including Issues and
|
|
13
13
|
Actions. Confirm a runner advertises the selected label from the workflow files.
|
|
14
|
-
The
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
14
|
+
The default `node-latest` label expects an official Node.js image, such as
|
|
15
|
+
`node:26-trixie`, because the checkout action needs Node.js. The Pre-commit job
|
|
16
|
+
runs in that label's job container, so its image must provide Git and Bash, and
|
|
17
|
+
either Python 3.10+ with venv or apt to install it, plus access to the Python
|
|
18
|
+
package index, GitHub hook sources, and Go toolchain/module downloads. Hosted
|
|
19
|
+
runners, such as Codeberg's, may use their own labels instead of `node-latest`;
|
|
20
|
+
generate with `--runner LABEL` to match one.
|
|
19
21
|
@@END_TIERS@@
|
|
20
22
|
@@TIERS full@@
|
|
21
23
|
- [ ] Enable the repository units I need under Settings, including Issues, Actions,
|
|
22
24
|
and Releases. Confirm a runner advertises the selected label from the workflow files.
|
|
23
|
-
The
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
The default `node-latest` label expects an official Node.js image, such as
|
|
26
|
+
`node:26-trixie`, because the checkout action needs Node.js. The Pre-commit job
|
|
27
|
+
runs in that label's job container, so its image must provide Git and Bash, and
|
|
28
|
+
either Python 3.10+ with venv or apt to install it, plus access to the Python
|
|
29
|
+
package index, GitHub hook sources, and Go toolchain/module downloads. Hosted
|
|
30
|
+
runners, such as Codeberg's, may use their own labels instead of `node-latest`;
|
|
31
|
+
generate with `--runner LABEL` to match one.
|
|
28
32
|
- [ ] Run **Actions → Sync labels → Run workflow** once after the first push. It
|
|
29
33
|
uses `.forgejo/labels.yml`; PR Labels needs these labels to exist. Alternatively,
|
|
30
34
|
run `.forgejo/scripts/sync-labels.sh` with `FORGEJO_API`, `FORGEJO_TOKEN`, `OWNER`,
|
|
@@ -45,6 +49,11 @@ Generate with `--tier regular` or `--tier full` for issue templates, CI, and aut
|
|
|
45
49
|
@@TIERS regular full@@
|
|
46
50
|
- [ ] Configure branch protection after checking the actual PR status contexts.
|
|
47
51
|
Contexts can include an event suffix; avoid requiring a push-only context on PRs.
|
|
52
|
+
- [ ] Review `.forgejo/default_merge_message/MERGE_TEMPLATE.md`. It makes a merge
|
|
53
|
+
commit start with the PR's title and reference, such as `feat: add export (#12)`,
|
|
54
|
+
and leaves the body empty. Its second, blank line is what clears Forgejo's default
|
|
55
|
+
body, so keep it. Squash merges keep Forgejo's default message, and the template
|
|
56
|
+
applies once it reaches the default branch.
|
|
48
57
|
@@END_TIERS@@
|
|
49
58
|
@@TIERS full@@
|
|
50
59
|
- [ ] To use Renovate, create a dedicated bot with repository access and supply
|
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
@@END_TIERS@@
|
|
15
15
|
#
|
|
16
16
|
# Tests that need another image belong in a `docker://` step like these, not
|
|
17
|
-
# on a different runner label: plain images such as debian-*
|
|
18
|
-
# the JavaScript checkout action fails before the first step. A `container:`
|
|
17
|
+
# on a different runner label: plain images such as debian-* or ubuntu-* have
|
|
18
|
+
# no node, so the JavaScript checkout action fails before the first step. A `container:`
|
|
19
19
|
# does not help either, since the steps then run inside it.
|
|
20
20
|
|
|
21
21
|
name: Lint
|
|
@@ -39,9 +39,11 @@ jobs:
|
|
|
39
39
|
|
|
40
40
|
# actionlint also runs shellcheck over every `run:` block; the image
|
|
41
41
|
# bundles it. It only discovers .github/workflows by itself, hence the
|
|
42
|
-
# explicit file discovery below. The -ignore covers the
|
|
42
|
+
# explicit file discovery below. The first -ignore covers the
|
|
43
43
|
# full-URL `uses:` that Forgejo needs to reach actions on another host,
|
|
44
|
-
# which actionlint does not know about.
|
|
44
|
+
# which actionlint does not know about. The second covers runner labels:
|
|
45
|
+
# actionlint knows only GitHub's hosted ones, and Forgejo labels are
|
|
46
|
+
# whatever the instance's runners advertise.
|
|
45
47
|
- name: 🎬 actionlint
|
|
46
48
|
uses: docker://rhysd/actionlint:1.7.12@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667
|
|
47
49
|
with:
|
|
@@ -50,7 +52,8 @@ jobs:
|
|
|
50
52
|
-c 'find .forgejo/workflows -maxdepth 1 -type f
|
|
51
53
|
\( -name "*.yml" -o -name "*.yaml" \)
|
|
52
54
|
-exec actionlint -color
|
|
53
|
-
-ignore "specifying action \"https://[^\"]+\" in invalid format"
|
|
55
|
+
-ignore "specifying action \"https://[^\"]+\" in invalid format"
|
|
56
|
+
-ignore "label \"[^\"]+\" is unknown" {} +'
|
|
54
57
|
|
|
55
58
|
# actionlint only reaches shell inside workflows, so standalone scripts
|
|
56
59
|
# get their own pass. Any *.sh or *.bash outside .git is picked up; a
|
|
@@ -15,8 +15,17 @@ jobs:
|
|
|
15
15
|
uses: https://data.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
16
16
|
with:
|
|
17
17
|
persist-credentials: false
|
|
18
|
+
# Official Node.js and Debian images ship Python without venv support,
|
|
19
|
+
# or no Python at all. Install it only when it is missing, so an image
|
|
20
|
+
# that already has it skips the download.
|
|
21
|
+
- name: Make sure Python's venv is available
|
|
22
|
+
run: |
|
|
23
|
+
set -euo pipefail
|
|
24
|
+
python3 -c 'import ensurepip, venv' >/dev/null 2>&1 || {
|
|
25
|
+
apt-get update -qq && apt-get install -y -qq --no-install-recommends python3-venv
|
|
26
|
+
}
|
|
18
27
|
# Runs in the job container, whose image must provide Git, Bash, and
|
|
19
|
-
# Python 3.10+ with venv. See .forgejo/SETUP.md.
|
|
28
|
+
# either apt or Python 3.10+ with venv. See .forgejo/SETUP.md.
|
|
20
29
|
- name: Run pre-commit checks
|
|
21
30
|
env:
|
|
22
31
|
# The digest-pinned Lint job owns these checks in CI. Local hooks run all.
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"server_url": "https://codeberg.org",
|
|
3
3
|
"nested_namespaces": false,
|
|
4
|
-
"runner": "
|
|
4
|
+
"runner": "node-latest",
|
|
5
5
|
"codeowners_pattern": ".*",
|
|
6
6
|
"tiers": {
|
|
7
7
|
"regular": [
|
|
8
8
|
".forgejo/CODEOWNERS",
|
|
9
|
+
".forgejo/default_merge_message/*",
|
|
9
10
|
".forgejo/ISSUE_TEMPLATE/*",
|
|
10
11
|
".forgejo/PULL_REQUEST_TEMPLATE.md",
|
|
11
12
|
".forgejo/workflows/lint.yml",
|
|
@@ -36,6 +37,6 @@
|
|
|
36
37
|
"SECURITY_CHANNEL": "Set a private reporting address below before publishing this project.",
|
|
37
38
|
"LABEL_NOTE": "Run Sync labels once from Actions after the first push. PR Labels requires these labels.",
|
|
38
39
|
"EXTRA_SETUP": "Review Renovate and its bot credentials in `.forgejo/SETUP.md`. Confirm a runner with the chosen label exists before requiring checks.",
|
|
39
|
-
"PRE_COMMIT_WORKFLOW_HOOKS": "\n - repo: https://github.com/rhysd/actionlint\n rev: 914e7df21a07ef503a81201c76d2b11c789d3fca # frozen: v1.7.12\n hooks:\n - id: actionlint\n files: ^\\.forgejo/workflows/.*\\.ya?ml$\n args:\n - -ignore\n - 'specifying action \"https://[^\"]+\" in invalid format'"
|
|
40
|
+
"PRE_COMMIT_WORKFLOW_HOOKS": "\n - repo: https://github.com/rhysd/actionlint\n rev: 914e7df21a07ef503a81201c76d2b11c789d3fca # frozen: v1.7.12\n hooks:\n - id: actionlint\n files: ^\\.forgejo/workflows/.*\\.ya?ml$\n args:\n - -ignore\n - 'specifying action \"https://[^\"]+\" in invalid format'\n - -ignore\n - 'label \"[^\"]+\" is unknown'"
|
|
40
41
|
}
|
|
41
42
|
}
|