-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
117 lines (95 loc) · 2.58 KB
/
index.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
import { clean, inc, valid } from "https://deno.land/x/[email protected]/mod.ts";
import UserError from "./user-error.ts";
import { checkPrerequisites, commitAndTag, GitError } from "./git.ts";
const fileName = "VERSION";
async function readVersion(): Promise<string> {
let content: string;
try {
content = await Deno.readTextFile(fileName);
content = content.replace(/[\n\r\t\s]+/g, "");
} catch (err) {
if (err instanceof Deno.errors.PermissionDenied) {
throw err;
} else {
throw new UserError(
`Could not read ${fileName} file. Run \`version init\` to create one`,
);
}
}
if (!valid(content)) {
throw new UserError(
`${fileName} file contained "${content}", which is not a valid version string`,
);
}
return content;
}
async function writeVersion(versionInput: string): Promise<void> {
const normalizedVersion = clean(versionInput);
if (!normalizedVersion) {
throw new UserError(`${versionInput} is not a valid version string`);
}
await checkPrerequisites();
await Deno.writeTextFile(fileName, normalizedVersion);
await commitAndTag(normalizedVersion, fileName);
console.log(normalizedVersion);
}
enum Actions {
major = "major",
minor = "minor",
patch = "patch",
init = "init",
set = "set",
get = "get",
}
const allowedActions = Object.keys(Actions);
async function run() {
const [action, ...params] = Deno.args;
if (!allowedActions.includes(action)) {
throw new UserError(`Usage: version <${allowedActions.join("|")}>`);
}
switch (action) {
case "init": {
const version = params[0] || "1.0.0";
await writeVersion(version);
break;
}
case "get": {
const currentVersion = await readVersion();
console.log(currentVersion);
break;
}
case "set": {
if (!params[0]) {
throw new UserError(`Usage: version set <version>`);
}
await writeVersion(params[0]);
break;
}
case "major":
case "minor":
case "patch": {
const currentVersion = await readVersion();
const newVersion = inc(
currentVersion,
action as "major" | "minor" | "patch",
);
if (!newVersion) {
throw new Error("Could not increment version");
}
await writeVersion(newVersion);
break;
}
}
}
try {
await run();
} catch (err) {
if (err instanceof Deno.errors.PermissionDenied) {
console.error(err.message);
Deno.exit(1);
} else if (err instanceof UserError || err instanceof GitError) {
console.error(`Error: ${err.message}`);
Deno.exit(1);
}
throw err;
}