@seangalie/precast 0.1.0 → 0.3.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.
@@ -0,0 +1,261 @@
1
+ import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { makeContext } from "./context.js";
5
+ import { PrecastError } from "./errors.js";
6
+ import { readJson, readPlatform } from "./platforms.js";
7
+ import { isPlainObject, isTier } from "./tiers.js";
8
+ const STRING_FIELDS = [
9
+ "platform",
10
+ "serverUrl",
11
+ "namespace",
12
+ "author",
13
+ "description",
14
+ "defaultBranch",
15
+ "codeowner",
16
+ "runner",
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;
23
+ /**
24
+ * Where profiles live unless `--config` names another file: the XDG config
25
+ * directory on macOS and Linux, and the roaming application data folder on Windows.
26
+ */
27
+ export function defaultConfigPath(env = process.env, platform = process.platform, home = homedir()) {
28
+ // Relative values are ignored, as the XDG base directory specification
29
+ // requires, so a settings file is never read from the working directory.
30
+ if (platform === "win32") {
31
+ const appData = env.APPDATA && path.win32.isAbsolute(env.APPDATA) ? env.APPDATA : undefined;
32
+ return path.win32.join(appData ?? path.win32.join(home, "AppData", "Roaming"), "precast", "config.json");
33
+ }
34
+ const xdg = env.XDG_CONFIG_HOME && path.posix.isAbsolute(env.XDG_CONFIG_HOME)
35
+ ? env.XDG_CONFIG_HOME
36
+ : undefined;
37
+ return path.posix.join(xdg ?? path.posix.join(home, ".config"), "precast", "config.json");
38
+ }
39
+ /** Reject names that would be awkward on a command line or in JSON. */
40
+ export function checkProfileName(name) {
41
+ if (!PROFILE_NAME.test(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`);
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) {
56
+ if (!existsSync(file)) {
57
+ return new Map();
58
+ }
59
+ const settings = readJson(file);
60
+ if (!isPlainObject(settings) || !isPlainObject(settings.profiles)) {
61
+ throw new PrecastError(`${file} must be a JSON object with a "profiles" object`);
62
+ }
63
+ for (const key of Object.keys(settings)) {
64
+ if (key !== "profiles") {
65
+ throw new PrecastError(`${file} has an unknown field: ${key}`);
66
+ }
67
+ }
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();
111
+ throw new PrecastError(`No profile '${name}' in ${file}${known.length > 0 ? `; it has: ${known.join(", ")}` : ""}`);
112
+ }
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
+ }
239
+ }
240
+ function parseProfile(value, label) {
241
+ if (!isPlainObject(value)) {
242
+ throw new PrecastError(`${label} must be an object`);
243
+ }
244
+ for (const [key, field] of Object.entries(value)) {
245
+ if (key === "tier") {
246
+ if (typeof field !== "string" || !isTier(field)) {
247
+ throw new PrecastError(`${label} has an unknown tier: ${JSON.stringify(field)}`);
248
+ }
249
+ }
250
+ else if (!STRING_FIELDS.includes(key)) {
251
+ throw new PrecastError(`${label} has an unknown field: ${key}`);
252
+ }
253
+ else if (typeof field !== "string") {
254
+ throw new PrecastError(`${label} needs a string ${key}`);
255
+ }
256
+ }
257
+ if (typeof value.platform !== "string") {
258
+ throw new PrecastError(`${label} needs a platform`);
259
+ }
260
+ return value;
261
+ }
@@ -0,0 +1,54 @@
1
+ import { type Tier } from "./tiers.ts";
2
+ /** The values every generation needs; any of them may still be missing. */
3
+ export interface RequiredValues {
4
+ platform?: string | undefined;
5
+ namespace?: string | undefined;
6
+ repo?: string | undefined;
7
+ output?: string | undefined;
8
+ }
9
+ /** The answers a prompted session collects; `tier` only when it was asked. */
10
+ export type Answers = Record<keyof RequiredValues, string> & {
11
+ tier?: Tier;
12
+ };
13
+ /** Ask one question; resolves undefined when the person cancels or input ends. */
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
+ }
20
+ /** Thrown when the person cancels a prompt, so nothing is generated. */
21
+ export declare class Cancelled extends Error {
22
+ constructor();
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>;
43
+ /**
44
+ * Ask for each missing required value in turn. Answers go through the same
45
+ * checks as command-line options, and an invalid answer is asked again.
46
+ */
47
+ export declare function promptForMissing(values: RequiredValues, ask: Ask, write: (text: string) => void, root: string, { stream, askTier }?: {
48
+ stream?: NodeJS.WritableStream;
49
+ askTier?: boolean;
50
+ }): Promise<Answers>;
51
+ /** Ask questions on the terminal, treating Ctrl+C and Ctrl+D as cancelling. */
52
+ export declare function withTerminal<T>(input: NodeJS.ReadableStream, output: NodeJS.WritableStream, use: (ask: Ask) => Promise<T>): Promise<T>;
53
+ /** Quote an argument for a POSIX shell only when it needs it. */
54
+ export declare function shellQuote(value: string): string;
@@ -0,0 +1,117 @@
1
+ import { createInterface } from "node:readline/promises";
2
+ import { checkNamespace, checkRepo } from "./context.js";
3
+ import { PrecastError } from "./errors.js";
4
+ import { checkOutput } from "./generate.js";
5
+ import { platformNames, readPlatform } from "./platforms.js";
6
+ import { paint } from "./style.js";
7
+ import { DEFAULT_TIER, TIERS } from "./tiers.js";
8
+ const TIER_SUMMARIES = {
9
+ slim: "the essentials, for personal projects and experiments",
10
+ regular: "adds policies, templates, pre-commit, and CI",
11
+ full: "adds labels, releases, and housekeeping automation",
12
+ };
13
+ /** Thrown when the person cancels a prompt, so nothing is generated. */
14
+ export class Cancelled extends Error {
15
+ constructor() {
16
+ super("Cancelled; no files were written");
17
+ }
18
+ }
19
+ export function questions(ask, write, stream) {
20
+ const answer = async (label, hint, check) => {
21
+ const shown = hint ? ` ${paint("dim", hint, stream)}` : "";
22
+ const question = `${paint("cyan", "?", stream)} ${paint("bold", label, stream)}${shown} ${paint("dim", "›", stream)} `;
23
+ for (;;) {
24
+ const reply = await ask(question);
25
+ if (reply === undefined)
26
+ throw new Cancelled();
27
+ try {
28
+ return check(reply.trim());
29
+ }
30
+ catch (error) {
31
+ if (!(error instanceof PrecastError))
32
+ throw error;
33
+ write(` ${paint("red", `✗ ${error.message}`, stream)}\n`);
34
+ }
35
+ }
36
+ };
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");
44
+ }
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(", ")}`);
58
+ }
59
+ return pick;
60
+ });
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;
86
+ const nested = readPlatform(root, platform).nested_namespaces;
87
+ const namespace = values.namespace ??
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));
90
+ const output = values.output ??
91
+ (await q.answer("Output folder", `(${repo})`, (reply) => {
92
+ const folder = reply || repo;
93
+ // The generator's own check, so an answer it would refuse is asked again.
94
+ checkOutput(folder, root);
95
+ return folder;
96
+ }));
97
+ return tier === undefined
98
+ ? { platform, namespace, repo, output }
99
+ : { platform, namespace, repo, output, tier };
100
+ }
101
+ /** Ask questions on the terminal, treating Ctrl+C and Ctrl+D as cancelling. */
102
+ export async function withTerminal(input, output, use) {
103
+ const terminal = createInterface({ input, output });
104
+ const closed = new Promise((resolve) => terminal.once("close", () => resolve(undefined)));
105
+ terminal.on("SIGINT", () => terminal.close());
106
+ try {
107
+ // Closing the terminal can also reject the pending question; both mean cancel.
108
+ return await use((question) => Promise.race([terminal.question(question).catch(() => undefined), closed]));
109
+ }
110
+ finally {
111
+ terminal.close();
112
+ }
113
+ }
114
+ /** Quote an argument for a POSIX shell only when it needs it. */
115
+ export function shellQuote(value) {
116
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
117
+ }
@@ -0,0 +1,14 @@
1
+ import { styleText } from "node:util";
2
+ type Format = Parameters<typeof styleText>[0];
3
+ /**
4
+ * Whether to color output for `stream`: only a terminal, and never when
5
+ * `NO_COLOR`, `NODE_DISABLE_COLORS`, `FORCE_COLOR=0`, or `TERM=dumb` asks for
6
+ * plain text. `FORCE_COLOR` cannot turn color on for a pipe or file, so logs
7
+ * and tests never contain escape codes.
8
+ */
9
+ export declare function colorEnabled(stream?: NodeJS.WritableStream, env?: NodeJS.ProcessEnv): boolean;
10
+ /** Style text for `stream` when `colorEnabled` allows it; otherwise return it unchanged. */
11
+ export declare function paint(format: Format, text: string, stream?: NodeJS.WritableStream): string;
12
+ /** The banner shown before the first question. */
13
+ export declare function header(version: string, stream?: NodeJS.WritableStream): string;
14
+ export {};
package/dist/style.js ADDED
@@ -0,0 +1,34 @@
1
+ import { styleText } from "node:util";
2
+ /**
3
+ * Whether to color output for `stream`: only a terminal, and never when
4
+ * `NO_COLOR`, `NODE_DISABLE_COLORS`, `FORCE_COLOR=0`, or `TERM=dumb` asks for
5
+ * plain text. `FORCE_COLOR` cannot turn color on for a pipe or file, so logs
6
+ * and tests never contain escape codes.
7
+ */
8
+ export function colorEnabled(stream = process.stdout, env = process.env) {
9
+ if (stream.isTTY !== true)
10
+ return false;
11
+ return !(env.NO_COLOR ||
12
+ env.NODE_DISABLE_COLORS ||
13
+ env.FORCE_COLOR === "0" ||
14
+ env.TERM === "dumb");
15
+ }
16
+ /** Style text for `stream` when `colorEnabled` allows it; otherwise return it unchanged. */
17
+ export function paint(format, text, stream = process.stdout) {
18
+ return colorEnabled(stream) ? styleText(format, text, { validateStream: false }) : text;
19
+ }
20
+ // figlet's Standard font at full width, kept to ASCII so every terminal shows it.
21
+ const WORDMARK = [
22
+ " _",
23
+ " _ __ _ __ ___ ___ __ _ ___ | |_",
24
+ "| '_ \\ | '__| / _ \\ / __| / _` |/ __|| __|",
25
+ "| |_) || | | __/| (__ | (_| |\\__ \\| |_",
26
+ "| .__/ |_| \\___| \\___| \\__,_||___/ \\__|",
27
+ "|_|",
28
+ ];
29
+ /** The banner shown before the first question. */
30
+ export function header(version, stream) {
31
+ const art = WORDMARK.map((line) => ` ${paint("cyan", line, stream)}`).join("\n");
32
+ const tagline = paint("dim", ` Start a new project with its checks in place · v${version}`, stream);
33
+ return `\n${art}\n\n${tagline}\n\n`;
34
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seangalie/precast",
3
- "version": "0.1.0",
3
+ "version": "0.3.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 --experimental-strip-types \"test/**/*.test.ts\"",
34
- "check-generated": "node --experimental-strip-types scripts/check-generated.ts",
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
  },
@@ -13,14 +13,18 @@ Generate with `--tier regular` or `--tier full` for issue templates, CI, and aut
13
13
  Actions. Confirm a runner advertises the selected label from the workflow files.
14
14
  The Pre-commit job runs in that label's job container, so its image must provide
15
15
  Git, Bash, and Python 3.10+ with venv, plus access to the Python package index,
16
- GitHub hook sources, and Go toolchain/module downloads.
16
+ GitHub hook sources, and Go toolchain/module downloads. Hosted runners, such as
17
+ Codeberg's, may use their own labels instead of `ubuntu-latest`; generate with
18
+ `--runner LABEL` to match one.
17
19
  @@END_TIERS@@
18
20
  @@TIERS full@@
19
21
  - [ ] Enable the repository units I need under Settings, including Issues, Actions,
20
22
  and Releases. Confirm a runner advertises the selected label from the workflow files.
21
23
  The Pre-commit job runs in that label's job container, so its image must provide
22
24
  Git, Bash, and Python 3.10+ with venv, plus access to the Python package index,
23
- GitHub hook sources, and Go toolchain/module downloads.
25
+ GitHub hook sources, and Go toolchain/module downloads. Hosted runners, such as
26
+ Codeberg's, may use their own labels instead of `ubuntu-latest`; generate with
27
+ `--runner LABEL` to match one.
24
28
  - [ ] Run **Actions → Sync labels → Run workflow** once after the first push. It
25
29
  uses `.forgejo/labels.yml`; PR Labels needs these labels to exist. Alternatively,
26
30
  run `.forgejo/scripts/sync-labels.sh` with `FORGEJO_API`, `FORGEJO_TOKEN`, `OWNER`,
@@ -41,6 +45,11 @@ Generate with `--tier regular` or `--tier full` for issue templates, CI, and aut
41
45
  @@TIERS regular full@@
42
46
  - [ ] Configure branch protection after checking the actual PR status contexts.
43
47
  Contexts can include an event suffix; avoid requiring a push-only context on PRs.
48
+ - [ ] Review `.forgejo/default_merge_message/MERGE_TEMPLATE.md`. It makes a merge
49
+ commit start with the PR's title and reference, such as `feat: add export (#12)`,
50
+ and leaves the body empty. Its second, blank line is what clears Forgejo's default
51
+ body, so keep it. Squash merges keep Forgejo's default message, and the template
52
+ applies once it reaches the default branch.
44
53
  @@END_TIERS@@
45
54
  @@TIERS full@@
46
55
  - [ ] To use Renovate, create a dedicated bot with repository access and supply
@@ -0,0 +1,2 @@
1
+ ${PullRequestTitle} (${PullRequestReference})
2
+
@@ -1,11 +1,12 @@
1
1
  {
2
- "server_url": "https://git.galie.io",
2
+ "server_url": "https://codeberg.org",
3
3
  "nested_namespaces": false,
4
4
  "runner": "ubuntu-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",
@@ -1,7 +1,8 @@
1
1
  # GitLab setup
2
2
 
3
- I target GitLab 19.5 on PPPL's instance. The version was confirmed through the
4
- desktop UI; runner, subscription, and project policy checks remain outstanding.
3
+ This starter does not assume a GitLab version, subscription tier, or runner
4
+ setup. On a self-managed instance, check its runners and policies before relying
5
+ on the checks below.
5
6
 
6
7
  - [ ] Confirm the destination project is in the intended namespace. Subgroups are supported.
7
8
  @@TIERS regular full@@
@@ -11,11 +12,12 @@ desktop UI; runner, subscription, and project policy checks remain outstanding.
11
12
  index (normally `pypi.org` and `files.pythonhosted.org`), GitHub hook repositories,
12
13
  and Go toolchain/module services such as `go.dev`, `dl.google.com`,
13
14
  `proxy.golang.org`, and `sum.golang.org`. Confirm outbound access or approved
14
- mirrors/proxies; these are not assumed available on PPPL's runners.
15
+ mirrors/proxies; these are not assumed available on every instance's runners.
15
16
  The default `tags: []`
16
17
  requires a runner that accepts untagged jobs. Generate with `--runner TAG` to select
17
- a tagged runner instead. For Docker/Kubernetes executors, set an approved default
18
- image on the runner or add an institutional image to `.gitlab-ci.yml`.
18
+ a tagged runner instead. Projects generated for GitLab.com set a public Python
19
+ image in `.gitlab-ci.yml`. On other instances with Docker/Kubernetes executors,
20
+ set an approved default image on the runner or add one to `.gitlab-ci.yml`.
19
21
  @@END_TIERS@@
20
22
  @@TIERS regular@@
21
23
  - [ ] Add real build and test jobs to `.gitlab-ci.yml`. `project-tests` is a manual placeholder.
@@ -30,10 +32,10 @@ desktop UI; runner, subscription, and project policy checks remain outstanding.
30
32
  @@END_TIERS@@
31
33
  - [ ] Set protected branches, review requirements, visibility, and institutional policies.
32
34
  @@TIERS slim@@
33
- - [ ] Give a private security contact in `README.md` according to PPPL requirements.
35
+ - [ ] Give a private security contact in `README.md` according to your organization's requirements.
34
36
  @@END_TIERS@@
35
37
  @@TIERS regular full@@
36
- - [ ] Set a private security contact in `docs/SECURITY.md` according to PPPL requirements.
38
+ - [ ] Set a private security contact in `docs/SECURITY.md` according to your organization's requirements.
37
39
  @@END_TIERS@@
38
40
  @@TIERS full@@
39
41
  - [ ] Configure labels using `.gitlab/labels.json` manually, or explicitly run the command
@@ -52,11 +54,12 @@ desktop UI; runner, subscription, and project policy checks remain outstanding.
52
54
  notes, including for prerelease tags. It does not build or attach artifacts.
53
55
  @@END_TIERS@@
54
56
  - [ ] Add dependency updates and issue triage automation if needed. This starter does
55
- not assume that PPPL permits external bots, GitHub CodeQL, or scheduled API writes.
57
+ not assume that your instance permits external bots, GitHub CodeQL, or scheduled
58
+ API writes.
56
59
 
57
60
  @@TIERS slim@@
58
61
  Generate with `--tier regular` or `--tier full` for templates, CI, labels, and releases.
59
62
 
60
63
  @@END_TIERS@@
61
- GitLab project creation, label synchronization, release publishing, and runner
62
- execution have not been tested against PPPL by this generator.
64
+ Precast does not create the GitLab project, synchronize labels, publish releases, or
65
+ run CI for you. Check each of those on your instance before relying on it.
@@ -3,8 +3,9 @@
3
3
  # GitHub hook sources, and Go toolchain/module services (including go.dev,
4
4
  # dl.google.com, proxy.golang.org, and sum.golang.org), or approved mirrors.
5
5
  # See .gitlab/SETUP.md before using this on a restricted runner.
6
- # For a Docker or Kubernetes executor, configure a suitable default image or
7
- # add an approved `image:` here. No executor or institutional image is assumed.
6
+ # Projects generated for GitLab.com use a public Python image. On other instances,
7
+ # a Docker or Kubernetes executor needs a suitable default image on the runner or
8
+ # an approved `image:` below; no executor or institutional image is assumed.
8
9
  @@TIERS regular@@
9
10
  stages: [validate, test]
10
11
  @@END_TIERS@@
@@ -22,6 +23,7 @@ workflow:
22
23
 
23
24
  default:
24
25
  tags: @@RUNNER_TAGS_YAML@@
26
+ @@CI_IMAGE@@
25
27
 
26
28
  pre-commit:
27
29
  stage: validate
@@ -1,5 +1,5 @@
1
1
  {
2
- "server_url": "https://git.pppl.gov",
2
+ "server_url": "https://gitlab.com",
3
3
  "nested_namespaces": true,
4
4
  "runner": "",
5
5
  "codeowners_pattern": "*",
@@ -28,7 +28,11 @@
28
28
  "AUTOMATION_NOTE": "Use GitLab CI, CI_API_V4_URL and CI_PROJECT_ID. Namespaces can contain subgroups; do not split them into only owner/repository.",
29
29
  "SECURITY_CHANNEL": "Set a private reporting address below and follow institutional reporting requirements before publishing this project.",
30
30
  "LABEL_NOTE": "Labels and merge-request policies are configured in GitLab settings; `.gitlab/labels.json` contains the starting label definitions.",
31
- "EXTRA_SETUP": "Review `.gitlab/SETUP.md` for runner requirements, releases and PPPL-specific checks. This template does not assume a GitLab subscription tier.",
32
- "PRE_COMMIT_WORKFLOW_HOOKS": "# GitLab CI is checked by the shared YAML hook above."
31
+ "EXTRA_SETUP": "Review `.gitlab/SETUP.md` for runner requirements, releases and organization-specific checks. This template does not assume a GitLab subscription tier.",
32
+ "PRE_COMMIT_WORKFLOW_HOOKS": "# GitLab CI is checked by the shared YAML hook above.",
33
+ "CI_IMAGE": " # image: an approved image with Git, Bash, and Python 3.10+ with venv, if the runner has no suitable default"
34
+ },
35
+ "default_server_context": {
36
+ "CI_IMAGE": " # GitLab.com's hosted runners default to an image without Python's venv.\n image: python:3.14-trixie"
33
37
  }
34
38
  }