-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
version.ts
301 lines (268 loc) · 8.01 KB
/
version.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
#!/usr/bin/env -S deno run --allow-read --allow-write
/// <reference no-default-lib="true" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.window" />
/// <reference lib="esnext" />
import {
$,
assert,
colors,
type ExpandGlobOptions,
is,
JSONC,
semver,
TOML,
YAML,
} from "./deps.ts";
const ansi = colors();
const DEBUG = !["false", null, undefined].includes(Deno.env.get("DEBUG"));
const preventPublishOnError = false;
export const VERSION = "0.2.0";
export const MODULE = "etag";
/** `prepublish` will be invoked before publish */
export async function prepublish(version: string) {
try {
await bump("./*.{md,ts}", { version });
// and link our nest api key from the environment
const NESTAPIKEY = Deno.env.get("NESTAPIKEY");
const egg = find<{
version: string;
[x: string]: JSONC.JSONValue;
}>("./egg.*");
// sanity check
if (egg?.parsed) {
if (is.nonEmptyStringAndNotWhitespace(NESTAPIKEY)) {
// ensure eggs is installed (implicit latest version)
await exec(
Deno.execPath(),
"install -A https://deno.land/x/eggs/cli.ts",
);
//
await exec("eggs", `link ${NESTAPIKEY}`);
if (semver.lt(egg.parsed.version!, version)) {
egg.parsed.version = version;
const stringify = (egg.path.endsWith("json")
? JSON.stringify
: egg.path.endsWith("toml")
? TOML.stringify
: YAML.stringify);
Deno.writeTextFileSync(
egg.path,
Reflect.apply(
stringify,
undefined,
stringify === JSON.stringify
? [egg.parsed, null, 2]
: [egg.parsed],
),
);
}
await exec("eggs", "publish");
} else {
throw new TypeError(
`Missing environment variable \`NESTAPIKEY\`, which is required to publish on ${
ansi.bold.magenta("nest.land")
}. Please set it and try again.`,
);
}
}
} catch (err) {
console.error(err);
if (preventPublishOnError) return false;
}
if (DEBUG) return false; // return a falsey value to prevent publishing.
}
/** `postpublish` will be invoked after publish */
export function postpublish(version: string) {
console.log(
ansi.bold.brightGreen(
` ✓ published ${ansi.green.underline(`${MODULE}@${version}`)}`,
),
);
}
type Arrayable<T> = T | T[];
interface BumpContext {
version?: string | semver.SemVer;
previous?: string | semver.SemVer;
semver: {
releaseType: semver.ReleaseType;
includePrelease?: boolean;
operator?: semver.Operator;
};
options?: {
failFast?: boolean;
placeholder?: string;
placeholders?: boolean | string | RegExp;
delimiter?: string | RegExp;
jsdoc?: boolean | Arrayable<string | RegExp>;
};
}
const releaseType: semver.ReleaseType = "patch";
const defaultBumpContext: BumpContext = {
version: semver.increment(VERSION ?? "0.0.0", releaseType) ?? "",
semver: {
releaseType: "patch",
},
options: {
delimiter: `[\\/\"\'\\(\\)\\{\\}\\[\\]\\s]`,
placeholder: "VERSION",
placeholders: `\\{<v>\\}|\\{\\{<v>\\}\\}|\\$<v>`,
jsdoc: [
"@version ",
`@module ${MODULE}@`,
],
},
};
async function bump(
pattern: string | URL,
ctx?: Partial<BumpContext>,
): Promise<void>;
async function bump(
pattern: string | URL,
version: string,
ctx?: Partial<BumpContext>,
): Promise<void>;
async function bump(
pattern: string | URL,
version?: string | Partial<BumpContext>,
ctx: Partial<BumpContext> = { ...defaultBumpContext },
): Promise<void> {
const { semver: { releaseType }, options } = {
...defaultBumpContext,
...(ctx || {}),
} as BumpContext;
const previous = ctx?.previous ?? VERSION ?? "0.0.0";
if (is.nullOrUndefined(version) || !is.string(version)) {
version = semver.increment(previous, releaseType) ?? "";
assert.nonEmptyStringAndNotWhitespace(version);
}
let path = String(pattern);
if ($.path.isGlob(path)) {
path = $.path.normalizeGlob(path);
}
for (const file of $.fs.expandGlobSync(path)) {
if (file.isFile) {
try {
const PLACEHOLDER_RE = /[%#]\w+|[<]\w+?[>]/ig;
const PLACEHOLDERS = (
options?.placeholders === true
? defaultBumpContext.options?.placeholders
: options?.placeholders === false
? ""
: is.regExp(options?.placeholders)
? options?.placeholders.source
: [options?.placeholders ?? ""].flat().flatMap((s) =>
s.split(/\b\|\b/)
)
.map((s) =>
s.replaceAll(PLACEHOLDER_RE, options?.placeholder ?? "VERSION")
).join("|")
) as string;
//
// normalize our delimiter
const DELIM = String(options?.delimiter);
const JSDOC = is.nonEmptyArray(options?.jsdoc) ? options?.jsdoc! : [];
const SPECIFIER_RE = new RegExp(
// lookbehind
`(?<=(?:^|${DELIM})(?:${MODULE}[@]${
options?.jsdoc && JSDOC.length
? `|(?:^[\\t ]+\\* |\\s)${JSDOC.join("|")}`
: ""
}))` +
// placeholder tags, literal previous version, or any non-DELIM
`(${
PLACEHOLDERS ? PLACEHOLDERS + "|" : ""
}${VERSION}|(?!${DELIM}).+?)` +
// lookahead
`(?=$|${DELIM})`,
"mig",
);
let content = await Deno.readTextFile(file.path);
if (SPECIFIER_RE.test(content)) {
content = content.replaceAll(SPECIFIER_RE, version),
await Deno.writeTextFile(file.path, content).catch(console.error);
}
} catch (error) {
console.error(
ansi.bold.bgRed(" FAILED "),
`⚠︎ Unable to bump ${ansi.underline.red(file.name)}${
previous ? ` from ${ansi.underline(String(previous))}` : ""
} to ${ansi.bold(version)}!\n\n${error}`,
);
}
}
}
}
interface FindResult<T = { [key: string]: JSONC.JSONValue }> {
source: string;
parsed: T | undefined;
path: string;
}
function find<T = { [key: string]: JSONC.JSONValue }>(
glob: string | URL,
options: Omit<ExpandGlobOptions, "includeDirs" | "caseInsensitive"> = {},
): FindResult<T> | undefined {
glob = $.path.normalizeGlob(String(glob));
const candidates = [
...$.fs.expandGlobSync(glob, {
...options,
includeDirs: false,
caseInsensitive: true,
}),
].filter((f) => f.isFile);
const feelingLucky = candidates.at(0);
try {
const source = Deno.readTextFileSync(String(feelingLucky?.path));
if (!source) return undefined;
const ext = $.path.extname(feelingLucky?.path ?? "").replace(/^\./, "");
let parsed: T | undefined = undefined;
const path = feelingLucky?.path ?? "";
switch (ext) {
case ".json":
parsed = JSONC.parse(source, { allowTrailingComma: true }) as T ??
undefined;
break;
case ".yaml":/* fallthrough */
case ".yml":
parsed = YAML.parse(source) as T ?? undefined;
break;
case ".toml":
parsed = TOML.parse(source) as T ?? undefined;
break;
default:
return undefined;
}
return { source, parsed, path };
} catch (error) {
if (!(error instanceof Deno.errors.NotFound)) throw error;
return undefined;
}
}
function exec<
Env extends Record<string, string>,
Cmd extends string[] = string[],
>(env: Env, ...cmd: Cmd): Promise<string>;
function exec<
Cmd extends string[] = string[],
>(...cmd: Cmd): Promise<string>;
function exec(
env: string | Record<string, string>,
...cmd: string[]
): Promise<string> {
if (is.string(env)) {
cmd.unshift(env);
env = {} as Record<string, string>;
}
assert.plainObject(env);
if (cmd.length === 1) {
cmd = cmd[0].split(/\s+/, 2);
}
return Deno.run({
cmd,
env,
stderr: "null",
stdin: "null",
stdout: "piped",
}).output().then((output) => new TextDecoder().decode(output));
}
export { bump, exec, find };