-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPersist.js
107 lines (85 loc) · 2.47 KB
/
Persist.js
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
import { GitHubPublisher } from "github-publish";
import { Logger } from "./Logger.js";
class Persist {
static SUPPORTED_TYPES = ["github"];
static READABLE_TYPES = {
github: "GitHub"
};
static parseTarget(target = "") {
let [type, remainder] = target.split(":");
let [username, repository] = remainder.split("/");
let [repositoryName, repositoryBranch] = repository.split("#");
return {
type,
username,
repository: repositoryName,
branch: repositoryBranch || undefined,
}
}
#publisher;
#verboseMode = true;
#dryRun = false;
constructor() {
this.counts = {
persist: 0
};
}
getCounts() {
return this.counts;
}
setVerbose(isVerbose) {
this.#verboseMode = Boolean(isVerbose);
}
setDryRun(dryRun) {
this.#dryRun = Boolean(dryRun);
}
// has setTarget been successful?
canPersist() {
return Boolean(this.type && this.username && this.repository);
}
setTarget(target) {
// Must have a token to use this feature
if(!process.env.GITHUB_TOKEN) {
throw new Error("Missing GITHUB_TOKEN environment variable.");
}
let { type, username, repository, branch } = Persist.parseTarget(target);
if(!Persist.SUPPORTED_TYPES.includes(type)) {
throw new Error("Invalid persist type: " + type);
}
this.type = type;
this.username = username;
this.repository = repository;
this.branch = branch;
}
get publisher() {
if(!this.canPersist()) {
throw new Error("Missing Persist target. Have you called setTarget()?");
}
if(!this.#publisher) {
this.#publisher = new GitHubPublisher(process.env.GITHUB_TOKEN, this.username, this.repository, this.branch);
}
return this.#publisher;
}
persistFile(filePath, content, metadata = {}) {
// safeMode is handled upstream, otherwise the file will always exist on the file system (because writes happen before persistence)
if(this.#dryRun) {
// Skipping, don’t log the skip
return;
}
let options = {
// Persist should not happen if safe mode is enabled and the file already exists
force: true,
message: `@11ty/import ${metadata.url ? `via ${metadata.url}` : ""}`,
// sha: undefined // required for updating
}
this.counts.persist++;
if(this.#verboseMode) {
let readableType = Persist.READABLE_TYPES[this.type] || this.type;
Logger.persisting(`${metadata.type ? `${metadata.type} ` : ""}to ${readableType}`, filePath, metadata.url, {
size: content.length,
});
}
return this.publisher.publish(filePath, content, options);
}
}
export { Persist };