-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup.ts
executable file
·220 lines (187 loc) · 5.42 KB
/
backup.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
#!/usr/bin/env -S deno run --ext=ts --allow-run --allow-read --allow-sys
import {
ArgumentValue,
Command,
Type,
ValidationError,
} from "jsr:@cliffy/[email protected]";
import * as hex from "jsr:@std/[email protected]/hex";
import * as fs from "jsr:@std/[email protected]";
import * as path from "jsr:@std/[email protected]";
import * as semver from "jsr:@std/[email protected]";
function command(name: string, ...args: string[]): Promise<Deno.CommandOutput> {
return new Deno.Command(name, { args }).output();
}
function print(encoded: Uint8Array): void {
console.log(new TextDecoder().decode(encoded));
}
class KeepType extends Type<string> {
private readonly units = ["h", "d", "w", "m", "y"];
public parse({ label, name, value }: ArgumentValue): string {
const [end, ...rest] = value.split("").reverse();
const start = rest.reverse().join("");
if (!this.units.includes(end)) {
throw new ValidationError(
`${label} "${name}" has an invalid unit. Allowed values are: ${
this.units.join(", ")
}`,
);
}
const num = Number.parseInt(start, 10);
if (Number.isNaN(num)) {
throw new ValidationError(`${label} "${name}" is invalid.`);
}
const unit = end.replace("h", "H");
return `${num}${unit}`;
}
}
const cli = new Command()
.name("backup")
.type("keep", new KeepType())
.option("-v --verbose", "Enable verbose logging")
.option(
"--no-init",
"Don't automatically init borg repo if it doesn't already exist",
)
.option("-N --name <name:string>", "Name for backups unique to the repo", {
required: true,
})
.option("-R --repo <path:file>", "Path to borg repo", { required: true })
.option("--no-compact", "Disable automatic archive compacting")
.option("--no-prune", "Disable automatic archive pruning")
.option("-K --keep <value:keep>", "Timeframe to keep backups for (eg: 7d)", {
required: true,
})
.option("-S --sync", "Sync repo using rclone", {
depends: ["rclone-remote", "rclone-root"],
})
.option("--rclone-remote <remote:string>", "Rclone remote name")
.option("--rclone-root <root:string>", "Rclone remote root directory", {
default: ".",
})
.arguments("<...PATHS>")
.action(async (args, ...paths) => {
const borg = (...args: string[]) => command("borg", ...args);
const rclone = (...args: string[]) => command("rclone", ...args);
let canCompact = false;
try {
const resp = await borg("-V");
if (!resp.success) throw new Error();
const version = new TextDecoder().decode(resp.stdout).replace(
"borg ",
"",
);
const parsed = semver.parse(version);
const isOneDotFour = semver.greaterOrEqual(parsed, semver.parse("1.4.0"));
if (isOneDotFour) canCompact = true;
} catch {
console.log("missing `borg` binary");
console.log(
"https://borgbackup.readthedocs.io/en/stable/installation.html",
);
Deno.exit(1);
}
// TODO: Dry-run
const {
verbose,
init,
name,
repo,
compact,
prune,
keep,
sync,
} = args;
if (sync) {
try {
await rclone("-V");
} catch {
console.log("missing `rclone` binary");
console.log("https://rclone.org/install/");
Deno.exit(1);
}
}
const exists = await fs.exists(repo, {
isReadable: true,
isDirectory: true,
});
if (!exists) {
if (!init) {
console.log("backup repo does not exist and `--no-init` was passed");
Deno.exit(1);
}
await Deno.mkdir(repo, { recursive: true });
const resp = await borg("init", "-e=none", repo);
if (!resp.success) {
console.log("failed to init repo");
if (verbose) print(resp.stderr);
Deno.exit(1);
}
if (verbose) console.log(`created repo at ${path.resolve(repo)}`);
}
const bytes = new Uint8Array(6);
crypto.getRandomValues(bytes);
const hash = hex.encodeHex(bytes);
const resp = await borg(
"create",
"--stats",
`${repo}::${name}-${hash}`,
...paths,
);
if (!resp.success) {
console.log("failed to create backup");
if (verbose) print(resp.stderr);
Deno.exit(1);
}
if (verbose) {
console.log("backup info");
print(resp.stderr);
}
if (prune) {
const resp = await borg(
"prune",
repo,
"--stats",
`--prefix=${name}-`,
"--keep-last=1",
`--keep-within=${keep}`,
);
if (!resp.success) {
console.log("failed to prune backups");
if (verbose) print(resp.stderr);
Deno.exit(1);
}
if (verbose) {
console.log("prune info");
print(resp.stderr);
}
if (compact && canCompact) {
const resp = await borg(
"compact",
"--cleanup-commits",
repo,
);
if (!resp.success) {
console.log("failed to compact backups");
if (verbose) print(resp.stderr);
}
}
}
if (sync) {
const { rcloneRoot, rcloneRemote } = args;
const resp = await rclone(
"sync",
repo,
`${rcloneRemote}:${rcloneRoot}/${name}`,
);
if (!resp.success) {
console.log("failed to sync");
if (verbose) print(resp.stderr);
Deno.exit(1);
}
if (verbose) console.log("synced successfully");
}
});
if (import.meta.main) {
await cli.parse(Deno.args);
}