@mark1russell7/workflow-github 0.0.0-stage → 0.1.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,374 @@
1
+ import { isEnvelope, isRecord } from "@mark1russell7/coeval";
2
+
3
+ /**
4
+ * The GitHub expression grammar, as documents of the formula kit.
5
+ *
6
+ * The add-on has its own parser until W8. The syntax kit of the kernel has no index step, no `-` in a name, no
7
+ * function names without case and no filter step `.*`. The roadmap row W8 adds them, and then this grammar becomes a
8
+ * profile of the syntax kit.
9
+ */
10
+
11
+ /** A problem of an expression text: its offset in the text, and a message. */
12
+ export interface ExpressionIssue {
13
+ readonly offset: number;
14
+ readonly message: string;
15
+ }
16
+
17
+ /** The result of `parseExpression`. */
18
+ export type ExpressionResult = { readonly ok: true; readonly doc: unknown } | { readonly ok: false; readonly issue: ExpressionIssue };
19
+
20
+ /** The functions of GitHub, by their names in lower case. The value is the name of the operation. */
21
+ export const GITHUB_FUNCTIONS: Readonly<Record<string, string>> = {
22
+ contains: "contains",
23
+ startswith: "startsWith",
24
+ endswith: "endsWith",
25
+ format: "format",
26
+ join: "join",
27
+ tojson: "toJSON",
28
+ fromjson: "fromJSON",
29
+ hashfiles: "hashFiles",
30
+ success: "success",
31
+ always: "always",
32
+ cancelled: "cancelled",
33
+ failure: "failure",
34
+ };
35
+
36
+ const BINARY: Readonly<Record<string, { readonly prec: number; readonly kind: string }>> = {
37
+ "||": { prec: 1, kind: "or" },
38
+ "&&": { prec: 2, kind: "and" },
39
+ "==": { prec: 3, kind: "eq" },
40
+ "!=": { prec: 3, kind: "ne" },
41
+ "<": { prec: 4, kind: "lt" },
42
+ "<=": { prec: 4, kind: "le" },
43
+ ">": { prec: 4, kind: "gt" },
44
+ ">=": { prec: 4, kind: "ge" },
45
+ };
46
+ const SYMBOL_OF: Readonly<Record<string, string>> = Object.fromEntries(Object.entries(BINARY).map(([symbol, { kind }]) => [kind, symbol]));
47
+ const PREC_NOT = 5;
48
+ const PREC_POSTFIX = 6;
49
+
50
+ type Token =
51
+ | { readonly t: "num"; readonly v: number; readonly at: number }
52
+ | { readonly t: "str"; readonly v: string; readonly at: number }
53
+ | { readonly t: "id"; readonly v: string; readonly at: number }
54
+ | { readonly t: "op"; readonly v: string; readonly at: number }
55
+ | { readonly t: "end"; readonly at: number };
56
+
57
+ class Stop extends Error {
58
+ readonly issue: ExpressionIssue;
59
+ constructor(issue: ExpressionIssue) {
60
+ super(issue.message);
61
+ this.issue = issue;
62
+ }
63
+ }
64
+
65
+ const NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;
66
+
67
+ function tokenize(text: string): Token[] {
68
+ const out: Token[] = [];
69
+ let i = 0;
70
+ while (i < text.length) {
71
+ const c = text[i] as string;
72
+ if (/\s/.test(c)) {
73
+ i++;
74
+ continue;
75
+ }
76
+ const rest = text.slice(i);
77
+ const number = /^(0x[0-9a-fA-F]+|-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?)/.exec(rest);
78
+ if (number !== null && (c !== "-" || /^-[\d.]/.test(rest))) {
79
+ out.push({ t: "num", v: Number(number[0]), at: i });
80
+ i += number[0].length;
81
+ continue;
82
+ }
83
+ if (c === "'") {
84
+ let value = "";
85
+ let j = i + 1;
86
+ for (;;) {
87
+ if (j >= text.length) throw new Stop({ offset: i, message: "A text has no end quote." });
88
+ if (text[j] === "'") {
89
+ if (text[j + 1] === "'") {
90
+ value += "'";
91
+ j += 2;
92
+ continue;
93
+ }
94
+ break;
95
+ }
96
+ value += text[j];
97
+ j++;
98
+ }
99
+ out.push({ t: "str", v: value, at: i });
100
+ i = j + 1;
101
+ continue;
102
+ }
103
+ const name = /^[A-Za-z_][A-Za-z0-9_-]*/.exec(rest);
104
+ if (name !== null) {
105
+ out.push({ t: "id", v: name[0], at: i });
106
+ i += name[0].length;
107
+ continue;
108
+ }
109
+ const op = ["&&", "||", "==", "!=", "<=", ">=", "<", ">", "!", "(", ")", "[", "]", ".", ",", "*"].find((symbol) => rest.startsWith(symbol));
110
+ if (op === undefined) throw new Stop({ offset: i, message: `The character ${JSON.stringify(c)} is not part of an expression.` });
111
+ out.push({ t: "op", v: op, at: i });
112
+ i += op.length;
113
+ }
114
+ out.push({ t: "end", at: text.length });
115
+ return out;
116
+ }
117
+
118
+ const refDoc = (path: readonly unknown[]): unknown => ({ type: "ref", value: ["names", ...path] });
119
+ const op = (name: string, args: readonly unknown[]): unknown => ({ type: ["ops", name], value: args });
120
+ const isRef = (doc: unknown): doc is { type: "ref"; value: unknown[] } => isEnvelope(doc) && doc.type === "ref" && Array.isArray(doc.value);
121
+
122
+ class Parser {
123
+ private i = 0;
124
+ private readonly tokens: readonly Token[];
125
+ constructor(tokens: readonly Token[]) {
126
+ this.tokens = tokens;
127
+ }
128
+
129
+ private peek(): Token {
130
+ return this.tokens[this.i] as Token;
131
+ }
132
+ private next(): Token {
133
+ return this.tokens[this.i++] as Token;
134
+ }
135
+ private isOp(symbol: string): boolean {
136
+ const token = this.peek();
137
+ return token.t === "op" && token.v === symbol;
138
+ }
139
+ private expect(symbol: string): void {
140
+ const token = this.next();
141
+ if (token.t !== "op" || token.v !== symbol) throw new Stop({ offset: token.at, message: `The expression needs ${symbol} here.` });
142
+ }
143
+
144
+ parse(): unknown {
145
+ const doc = this.binary(1);
146
+ const token = this.peek();
147
+ if (token.t !== "end") throw new Stop({ offset: token.at, message: "The expression has more text after its end." });
148
+ return doc;
149
+ }
150
+
151
+ private binary(min: number): unknown {
152
+ let left = this.unary();
153
+ for (;;) {
154
+ const token = this.peek();
155
+ const info = token.t === "op" ? BINARY[token.v] : undefined;
156
+ if (info === undefined || info.prec < min) return left;
157
+ this.next();
158
+ const right = this.binary(info.prec + 1);
159
+ if (info.kind === "and" || info.kind === "or") {
160
+ // A chain of one logical operator is one document with each term.
161
+ const terms = isEnvelope(left) && left.type === info.kind && Array.isArray(left.value) && !(left as { group?: true }).group ? [...left.value, right] : [left, right];
162
+ left = { type: info.kind, value: terms };
163
+ } else left = op(info.kind, [left, right]);
164
+ }
165
+ }
166
+
167
+ private unary(): unknown {
168
+ if (this.isOp("!")) {
169
+ this.next();
170
+ return op("not", [this.unary()]);
171
+ }
172
+ return this.postfix(this.primary());
173
+ }
174
+
175
+ private postfix(start: unknown): unknown {
176
+ let doc = start;
177
+ let pluck: unknown[] | undefined;
178
+ for (;;) {
179
+ if (this.isOp(".")) {
180
+ this.next();
181
+ const token = this.next();
182
+ if (token.t === "op" && token.v === "*") {
183
+ pluck = [doc];
184
+ doc = op("pluck", pluck);
185
+ continue;
186
+ }
187
+ if (token.t !== "id") throw new Stop({ offset: token.at, message: "A name or * comes after a dot." });
188
+ doc = this.step(doc, token.v, pluck);
189
+ continue;
190
+ }
191
+ if (this.isOp("[")) {
192
+ this.next();
193
+ const index = this.binary(1);
194
+ this.expect("]");
195
+ pluck = undefined;
196
+ doc = typeof index === "string" || typeof index === "number" ? this.step(doc, index, undefined) : op("at", [doc, index]);
197
+ continue;
198
+ }
199
+ return doc;
200
+ }
201
+ }
202
+
203
+ private step(doc: unknown, key: string | number, pluck: unknown[] | undefined): unknown {
204
+ if (pluck !== undefined) {
205
+ pluck.push(key);
206
+ return doc;
207
+ }
208
+ if (isRef(doc)) return { type: "ref", value: [...doc.value, key] };
209
+ return op("at", [doc, key]);
210
+ }
211
+
212
+ private primary(): unknown {
213
+ const token = this.next();
214
+ switch (token.t) {
215
+ case "num":
216
+ case "str":
217
+ return token.v;
218
+ case "id": {
219
+ if (this.isOp("(")) {
220
+ const name = GITHUB_FUNCTIONS[token.v.toLowerCase()];
221
+ if (name === undefined) throw new Stop({ offset: token.at, message: `GitHub has no function ${token.v}.` });
222
+ this.next();
223
+ const args: unknown[] = [];
224
+ if (!this.isOp(")")) {
225
+ args.push(this.binary(1));
226
+ while (this.isOp(",")) {
227
+ this.next();
228
+ args.push(this.binary(1));
229
+ }
230
+ }
231
+ this.expect(")");
232
+ return op(name, args);
233
+ }
234
+ if (token.v === "true") return true;
235
+ if (token.v === "false") return false;
236
+ if (token.v === "null") return null;
237
+ return refDoc([token.v]);
238
+ }
239
+ case "op":
240
+ if (token.v === "(") {
241
+ const doc = this.binary(1);
242
+ this.expect(")");
243
+ // A group stops the merge of a chain: (a && b) && c keeps its group in the text.
244
+ return isEnvelope(doc) && (doc.type === "and" || doc.type === "or") ? Object.defineProperty({ ...doc }, "group", { value: true, enumerable: false }) : doc;
245
+ }
246
+ throw new Stop({ offset: token.at, message: `The expression cannot start with ${token.v} here.` });
247
+ default:
248
+ throw new Stop({ offset: token.at, message: "The expression has no term here." });
249
+ }
250
+ }
251
+ }
252
+
253
+ /** This function changes a reference `secrets.NAME` into a secret document, at each depth of a document. */
254
+ function secretsOf(doc: unknown): unknown {
255
+ if (Array.isArray(doc)) return doc.map(secretsOf);
256
+ if (!isRecord(doc)) return doc;
257
+ if (isRef(doc) && doc.value.length === 3 && doc.value[1] === "secrets" && typeof doc.value[2] === "string") return { type: "secret", value: doc.value[2] };
258
+ if (isEnvelope(doc)) return { type: doc.type, value: secretsOf(doc.value) };
259
+ return doc;
260
+ }
261
+
262
+ /**
263
+ * This function reads a GitHub expression, the text between `${{` and `}}`, into a document of the formula kit.
264
+ *
265
+ * - A context is a reference from `names`, for example `inputs.version` gives `["names", "inputs", "version"]`.
266
+ * - `secrets.NAME` gives the secret document `{ type: "secret", value: "NAME" }`.
267
+ * - The operators give `and`, `or` and the operations `not`, `eq`, `ne`, `lt`, `le`, `gt` and `ge`.
268
+ * - An index of a value that is not a reference gives the operation `at`, and `.*` gives the operation `pluck`.
269
+ * - A literal at the top gives a `lit` document, thus a text part of a template stays different from a literal.
270
+ *
271
+ * @param text - The text of the expression.
272
+ * @returns The document, or the problem with its offset.
273
+ */
274
+ export function parseExpression(text: string): ExpressionResult {
275
+ try {
276
+ const doc = secretsOf(new Parser(tokenize(text)).parse());
277
+ return { ok: true, doc: isEnvelope(doc) ? doc : { type: "lit", value: doc } };
278
+ } catch (error) {
279
+ if (error instanceof Stop) return { ok: false, issue: error.issue };
280
+ throw error;
281
+ }
282
+ }
283
+
284
+ function literal(value: unknown): string {
285
+ if (typeof value === "string") return `'${value.replace(/'/g, "''")}'`;
286
+ if (typeof value === "number" || typeof value === "boolean" || value === null) return String(value);
287
+ throw new TypeError(`The value ${JSON.stringify(value)} has no text in a GitHub expression.`);
288
+ }
289
+
290
+ function pathKeyText(key: unknown): string {
291
+ return typeof key === "string" && NAME.test(key) ? `.${key}` : `[${literal(key)}]`;
292
+ }
293
+
294
+ function printGitHubExpr(doc: unknown, min: number): string {
295
+ if (!isEnvelope(doc)) return literal(doc);
296
+ const type = Array.isArray(doc.type) ? doc.type.join(".") : String(doc.type);
297
+ const args = Array.isArray(doc.value) ? doc.value : [];
298
+ const group = (prec: number, text: string): string => (prec < min ? `(${text})` : text);
299
+ switch (type) {
300
+ case "lit":
301
+ return literal(doc.value);
302
+ case "ref": {
303
+ const [, root, ...steps] = args;
304
+ return `${String(root)}${steps.map(pathKeyText).join("")}`;
305
+ }
306
+ case "secret":
307
+ return `secrets${pathKeyText(doc.value)}`;
308
+ case "and":
309
+ case "or": {
310
+ const prec = type === "and" ? 2 : 1;
311
+ return group(prec, args.map((arg) => printGitHubExpr(arg, prec + 1)).join(type === "and" ? " && " : " || "));
312
+ }
313
+ case "ops.not":
314
+ return group(PREC_NOT, `!${printGitHubExpr(args[0], PREC_NOT)}`);
315
+ case "ops.at":
316
+ return `${printGitHubExpr(args[0], PREC_POSTFIX)}${isEnvelope(args[1]) ? `[${printGitHubExpr(args[1], 1)}]` : pathKeyText(args[1])}`;
317
+ case "ops.pluck":
318
+ return `${printGitHubExpr(args[0], PREC_POSTFIX)}.*${args.slice(1).map(pathKeyText).join("")}`;
319
+ default: {
320
+ const kind = type.startsWith("ops.") ? type.slice(4) : type;
321
+ const symbol = SYMBOL_OF[kind];
322
+ if (symbol !== undefined) {
323
+ const prec = (BINARY[symbol] as { prec: number }).prec;
324
+ return group(prec, `${printGitHubExpr(args[0], prec)} ${symbol} ${printGitHubExpr(args[1], prec + 1)}`);
325
+ }
326
+ if (type.startsWith("ops.")) return `${kind}(${args.map((arg) => printGitHubExpr(arg, 1)).join(", ")})`;
327
+ throw new TypeError(`The kind ${type} has no text in a GitHub expression.`);
328
+ }
329
+ }
330
+ }
331
+
332
+ /**
333
+ * This function writes a document of the formula kit as a GitHub expression, without `${{` and `}}`. The text is
334
+ * the canonical text: one space around each operator, and the GitHub names of the functions.
335
+ *
336
+ * @param doc - The document.
337
+ * @returns The text.
338
+ */
339
+ export function printExpression(doc: unknown): string {
340
+ return printGitHubExpr(doc, 1);
341
+ }
342
+
343
+ /** One part of a text with expressions: a text part, or an expression with its source text. */
344
+ export type TextPart = { readonly text: string } | { readonly source: string; readonly offset: number };
345
+
346
+ /**
347
+ * This function splits a text at each `${{ ... }}`. The end of an expression is the first `}}` outside a quoted text.
348
+ *
349
+ * @param text - The text.
350
+ * @returns The parts, or `undefined` when an expression has no end.
351
+ */
352
+ export function splitText(text: string): TextPart[] | undefined {
353
+ const parts: TextPart[] = [];
354
+ let i = 0;
355
+ while (i < text.length) {
356
+ const start = text.indexOf("${{", i);
357
+ if (start < 0) {
358
+ parts.push({ text: text.slice(i) });
359
+ break;
360
+ }
361
+ if (start > i) parts.push({ text: text.slice(i, start) });
362
+ let j = start + 3;
363
+ let quoted = false;
364
+ while (j < text.length) {
365
+ if (text[j] === "'") quoted = !quoted;
366
+ else if (!quoted && text.startsWith("}}", j)) break;
367
+ j++;
368
+ }
369
+ if (j >= text.length) return undefined;
370
+ parts.push({ source: text.slice(start + 3, j), offset: start + 3 });
371
+ i = j + 2;
372
+ }
373
+ return parts;
374
+ }
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { type WorkflowCheckOptions, type WorkflowIssue, checkWorkflow } from "@mark1russell7/workflow";
2
+ import { scriptInjections } from "./inject.ts";
3
+ import { GITHUB_CALLS, GITHUB_NAMES, githubMachine } from "./language.ts";
4
+
5
+ export { type ReadTrust, moveToEnv, readTrust, scriptInjections } from "./inject.ts";
6
+ export { GITHUB_FUNCTIONS, parseExpression, printExpression, splitText } from "./expression.ts";
7
+ export type { ExpressionIssue, ExpressionResult, TextPart } from "./expression.ts";
8
+ export { GITHUB_CALLS, GITHUB_CONTEXT_CHOICES, GITHUB_LANGUAGE, GITHUB_NAMES, GITHUB_OPS, GITHUB_VERSION, githubMachine } from "./language.ts";
9
+ export { GITHUB_LAYER, fromGitHub, readText, sameJson, toGitHub, toGitHubObject } from "./yaml.ts";
10
+ export type { ImportIssue, ImportOptions, ImportResult, TextValue } from "./yaml.ts";
11
+
12
+ /**
13
+ * This function checks a workflow from GitHub with the machine of the add-on. The contexts of GitHub are names, an
14
+ * input of a `github` call can hold a secret, and the secrets of the repository need no declaration. A script that
15
+ * reads an untrusted value with `${{ }}` is an error (`scriptInjections`).
16
+ *
17
+ * @param doc - The workflow document.
18
+ * @param options - More options of `checkWorkflow`.
19
+ * @returns The problems.
20
+ */
21
+ export function checkGitHub(doc: unknown, options: WorkflowCheckOptions = {}): readonly WorkflowIssue[] {
22
+ const issues = checkWorkflow(doc, {
23
+ machine: githubMachine(),
24
+ openSecrets: true,
25
+ ...options,
26
+ hostNames: [...GITHUB_NAMES, ...(options.hostNames ?? [])],
27
+ callNamespaces: [...GITHUB_CALLS, ...(options.callNamespaces ?? [])],
28
+ });
29
+ return [...issues, ...scriptInjections(doc)];
30
+ }