-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
256 lines (221 loc) · 7.93 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
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
import fs from "node:fs";
import path from "node:path";
import { $ } from "bun";
import chalk from "chalk";
import plist, { type PlistObject } from "plist";
import {
DefaultsActionType,
HOME,
ItemType,
SYNCED_DIR_PATH,
args,
config,
defaultsDomainAndConfig,
maxLengths,
symlinkPathAndConfig,
symlinkPathValidateType,
} from "./config";
import utils from "./utils";
if (!args.do) {
console.log(chalk.yellow("DRY RUN...\n"));
}
$.throws(true);
const EMPTY_OBJECT = Object.freeze({});
const bakPaths: Array<string | null> = [];
const typeDirLookup = new Map<string, boolean>();
async function createTypeDirIfNotExists(type: string): Promise<string> {
const dirPath = path.join(SYNCED_DIR_PATH, type);
if (!typeDirLookup.has(dirPath)) {
if (!fs.existsSync(dirPath)) {
console.log(chalk.gray(`Creating ${utils.tilde(dirPath)} directory...`));
if (args.do) {
await utils.mkdirp(dirPath);
}
}
typeDirLookup.set(dirPath, true);
}
return dirPath;
}
for (const group of config.groups) {
const groupName = group.name;
const groupLog = console.log.bind(console, chalk.blue(groupName.padEnd(maxLengths.groupName)));
if (!args.groups.includes(groupName) || args.excludeGroups.includes(groupName)) {
groupLog(chalk.gray(`Skipping ${groupName}...`));
continue;
}
for (const item of group.items) {
const itemType = item.type;
const itemLog = groupLog.bind(console, chalk.magenta(itemType.padEnd(maxLengths.itemType)));
if (!args.types.includes(itemType) || args.excludeTypes.includes(itemType)) {
itemLog(chalk.gray(`Skipping ${itemType}...`));
continue;
}
const typeDir = await createTypeDirIfNotExists(itemType);
switch (itemType) {
case ItemType.Symlink:
for (const pathMeta of item.paths) {
const [itemPath, itemConfig] = symlinkPathAndConfig(pathMeta);
const symlinkLog = itemLog.bind(console, chalk.cyan(itemPath.padEnd(maxLengths.otherInfo)), chalk.gray(">"));
const sourcePath = path.resolve(typeDir, itemPath);
const sourcePathStat = fs.lstatSync(sourcePath, { throwIfNoEntry: false });
const targetPath = path.resolve(HOME, itemPath);
const targetPathStat = fs.lstatSync(targetPath, { throwIfNoEntry: false });
if (!targetPathStat && args.do) {
await utils.mkdirp(path.dirname(targetPath));
}
if (!sourcePathStat && !targetPathStat) {
symlinkLog(`Does not exist. Creating an empty ${itemConfig.type} and creating symlink...`);
if (args.do) {
await utils.symlink(sourcePath, targetPath);
}
continue;
}
sourcePathStat && symlinkPathValidateType(sourcePath, sourcePathStat, itemConfig.type);
targetPathStat && symlinkPathValidateType(targetPath, targetPathStat, itemConfig.type);
if (sourcePathStat && !targetPathStat) {
symlinkLog(`${chalk.green("Only source exists.")} Creating symlink...`);
if (args.do) {
await utils.symlink(sourcePath, targetPath);
}
continue;
}
if (!sourcePathStat && targetPathStat) {
symlinkLog(`${chalk.green("Only target exists.")} Storing and creating symlink...`);
if (args.do) {
await utils.mv(targetPath, sourcePath);
await utils.symlink(sourcePath, targetPath);
}
continue;
}
// compiler not narrowing the type
if (!sourcePathStat || !targetPathStat) utils.unreachable();
if (targetPathStat.isSymbolicLink()) {
const linkTarget = fs.readlinkSync(targetPath);
if (linkTarget === sourcePath) {
symlinkLog(chalk.green("Already symlinked."));
continue;
}
symlinkLog(`${chalk.yellow("Overriding symlink:")} '${linkTarget}'...`);
if (args.do) {
await utils.unlink(targetPath);
await utils.symlink(sourcePath, targetPath);
}
continue;
}
const diff = await utils.diff({ path1: sourcePath, path2: targetPath, quiet: !args.diff });
const isTrackedAndUnmodified = await utils.isTrackedAndUnmodified(sourcePath);
const bakPath = `${sourcePath}.${Date.now()}.bak`;
if (diff && isTrackedAndUnmodified) {
symlinkLog(`${chalk.yellow("Diff found but is tracked.")} Replacing with symlink...`);
bakPaths.push(null);
} else if (diff) {
symlinkLog(
`${chalk.yellow("Diff found.")} Backing up source, replacing it with target, and creating symlink.`,
);
bakPaths.push(bakPath);
} else {
symlinkLog(`${chalk.green("No diff.")} Replacing with symlink...`);
}
if (args.do) {
if (diff) {
isTrackedAndUnmodified || (await utils.mv(sourcePath, bakPath));
await utils.mv(targetPath, sourcePath);
}
await utils.symlink(sourcePath, targetPath);
}
}
break;
case ItemType.Defaults:
for (const domainMeta of item.domains) {
const [itemDomain, itemConfig] = defaultsDomainAndConfig(domainMeta);
const defaultsLog = itemLog.bind(
console,
chalk.cyan(itemDomain.padEnd(maxLengths.otherInfo)),
chalk.gray(">"),
);
const sourcePath = path.resolve(typeDir, `${itemDomain}.plist`);
const sourcePathStat = fs.lstatSync(sourcePath, { throwIfNoEntry: false });
switch (args.defaultsAction) {
case DefaultsActionType.Export: {
if (!sourcePathStat) {
defaultsLog(`${chalk.green("Does not exist.")} Exporting defaults...`);
}
const exported = await $`defaults export ${itemDomain} -`.text();
let plistObject = plist.parse(exported);
if (Bun.deepEquals(plistObject, EMPTY_OBJECT)) {
defaultsLog(chalk.green("Nothing to export."));
break;
}
utils.assert(
typeof plistObject === "object" &&
!Array.isArray(plistObject) &&
!(plistObject instanceof Date) &&
!(plistObject instanceof Buffer),
`Unexpected plist type: ${typeof plistObject}`,
);
if (itemConfig.include) {
plistObject = utils.keep(plistObject, itemConfig.include) as PlistObject;
}
if (itemConfig.exclude) {
plistObject = utils.remove(plistObject, itemConfig.exclude) as PlistObject;
}
const final = plist.build(plistObject, { pretty: true, indent: "\t" }).trim();
if (sourcePathStat) {
const existing = (await Bun.file(sourcePath).text()).trim();
const hasDiff = existing !== final;
if (!hasDiff) {
defaultsLog(chalk.green("No change."));
break;
}
const isTrackedAndUnmodified = await utils.isTrackedAndUnmodified(sourcePath);
if (isTrackedAndUnmodified) {
defaultsLog(`${chalk.yellow("Diff found but is tracked.")} Saving...`);
bakPaths.push(null);
} else {
defaultsLog(`${chalk.yellow("Diff found.")} Backing up existing and saving new...`);
const bakFile = `${sourcePath}.${Date.now()}.bak`;
bakPaths.push(bakFile);
if (args.do) {
await utils.mv(sourcePath, bakFile);
}
}
if (args.diff) {
await utils.diff({ str1: existing, str2: final, quiet: false });
}
}
if (args.do) {
await Bun.write(sourcePath, `${final}\n`);
}
break;
}
case DefaultsActionType.Import: {
if (!sourcePathStat) {
defaultsLog(`${chalk.yellow("Does not exist.")} Skipping...`);
break;
}
defaultsLog(`${chalk.green("Found.")} Importing defaults...`);
if (args.do) {
await $`defaults import ${itemDomain} ${sourcePath}`;
}
break;
}
default:
throw new Error(`Unexpected DefaultsActionType: ${args.defaultsAction}`);
}
}
break;
default:
throw new Error(`Unexpected ItemType: ${itemType}`);
}
}
}
if (bakPaths.length) {
const backedUp = bakPaths.filter(Boolean).map(utils.tilde).join(" ");
if (backedUp) {
console.log(chalk.yellow("\nBacked up paths:"), backedUp);
}
console.log(chalk.yellow("Review and commit."));
}
if (!args.do) {
console.log(chalk.yellow("\nNothing was actually done. Use --do to apply changes."));
}