Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
195 lines (161 loc) · 5.32 KB
/
Copy pathindex.js
File metadata and controls
195 lines (161 loc) · 5.32 KB
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
#!/usr/bin/env node
const fs = require('node:fs/promises');
const path = require('node:path');
const { exec } = require('node:child_process');
const { parseArgs, promisify, styleText } = require('node:util');
const execPromise = promisify(exec);
const hasBinary = require('./src/has-binary');
const diffDirectories = require('./src/gen-diff-object');
const isInvalidPath = require('./src/is-invalid-path');
const { version } = require('./package.json');
(async () => {
const has_zip = hasBinary('zip');
const has_diff = hasBinary('diff');
if (!(has_zip && has_diff)) {
// prettier-ignore
console.error(`Could not find both "${styleText('yellow', 'zip')}" and "${styleText('yellow', 'diff')}" binaries, both of which are required. Exiting.`);
process.exit(1);
}
const {
values: argv,
positionals: [build_old, build_new],
} = parseArgs({
args: process.argv.slice(2),
options: {
quiet: { type: 'boolean', short: 'q', default: false },
json: { type: 'boolean', short: 'j', default: false },
output: { type: 'string', short: 'o', default: 'build_for_upload' },
},
allowPositionals: true,
});
// @todo Have options table automatically generated
const usage_message = `
Usage: build-diff [options] <old-build-directory> <new-build-directory>
CLI to compare two folders and copy out the differences between them.
Version ${version}
Options:
-q, --quiet Hides progress as it compares the directories. Defaults to false.
-j, --json Outputs results as JSON. Defaults to false.
-o, --output <name> Name of the output folder and ZIP file. Defaults to "build_for_upload".
`;
if (!build_old || !build_new) {
console.error(usage_message);
process.exit(1);
}
// Check that build folders exist
let build_old_exists = await pathExists(build_old);
let build_new_exists = await pathExists(build_new);
if (!build_old_exists || !build_new_exists) {
console.error(
styleText('red', 'The passed build directories do not exist:', {
stream: process.stderr,
}),
`\n "${build_old}"\n "${build_new}"\n`
);
console.error(usage_message);
process.exit(1);
}
const { quiet, json, output } = argv;
const logger = createLogger(quiet);
if (isInvalidPath(output)) {
console.error(
styleText('red', 'The passed output directory has invalid characters:', {
stream: process.stderr,
}),
`\n "${output}"\n`
);
console.error(usage_message);
process.exit(1);
}
logger.log(
`Comparing "${styleText('magenta', build_old)}" against "${styleText('magenta', build_new)}"...`
);
// If we are here, both directories exist, so let's compute the differences between them
let {
filesAdded: files_added,
filesUpdated: files_updated,
filesDeleted: files_deleted,
} = await diffDirectories(build_old, build_new, { quiet });
if (files_added.length + files_updated + files_deleted.length === 0) {
console.error(`No files were different between "${build_old}" and "${build_new}", exiting`);
process.exit(0);
}
// Concat 'added' and 'updated' since functionally they are no different when uploading to AWS (or other)
let files_changed = files_updated.concat(files_added);
// Sort newly formed `files_changed`; other lists are already sorted
files_changed.sort();
let output_dir = path.resolve(output);
// Create our output directory
try {
await fs.mkdir(output_dir, { recursive: true });
} catch (e) {
console.error(`Unable to create output directory at "${output_dir}"`);
console.error(e);
process.exit(2);
}
// Copy our changed files over to the output directory!
if (files_changed.length) {
logger.write(styleText('yellow', 'Copying over changed files... '));
await Promise.all(
files_changed.map(async (file) => {
const source = path.join(build_new, file);
const destination = path.join(output_dir, file);
await fs.mkdir(path.dirname(destination), { recursive: true });
await fs.cp(source, destination, { recursive: true });
})
);
logger.log(styleText('green', 'Done'));
}
// Zip the files up
// @todo Use a native option
logger.write(styleText('yellow', 'Zipping changed files... '));
let relative_output_dir = path.relative(process.cwd(), output_dir);
await execPromise(
`zip -9 -x "**/.DS_Store" -q -r ${relative_output_dir}.zip ${relative_output_dir}`
);
logger.log(styleText('green', 'Done\n'));
if (json) {
const json_output = {
filesDeleted: files_deleted,
filesChanged: files_changed,
outputDir: relative_output_dir,
outputZip: relative_output_dir + '.zip',
};
console.log(JSON.stringify(json_output));
} else {
if (files_deleted.length) {
console.log(styleText('red', 'The following files were deleted:'));
console.log(' ' + files_deleted.join('\n ') + '\n');
}
if (files_changed.length) {
console.log(styleText('green', '\nThe following files were changed:'));
console.log(' ' + files_changed.join('\n ') + '\n');
}
console.log(
`All changed files have been copied to ${styleText('cyan', relative_output_dir)}, and zipped in ${styleText(
'cyan',
relative_output_dir + '.zip'
)}\n`
);
}
})();
async function pathExists(target) {
try {
await fs.access(target);
return true;
} catch {
return false;
}
}
function createLogger(quiet) {
if (quiet) {
return {
log() {},
write() {},
};
}
return {
log: console.log.bind(console),
write: process.stdout.write.bind(process.stdout),
};
}