forked from withastro/astro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy.js
85 lines (77 loc) · 2.22 KB
/
copy.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
import arg from 'arg';
import { globby as glob } from 'globby';
import { promises as fs, readFileSync } from 'node:fs';
import { posix } from 'node:path';
import * as tar from 'tar/create';
const { resolve, dirname, sep, join } = posix;
/** @type {import('arg').Spec} */
const spec = {
'--tgz': Boolean,
};
export default async function copy() {
let { _: patterns, ['--tgz']: isCompress } = arg(spec);
patterns = patterns.slice(1);
if (isCompress) {
const files = await glob(patterns, { gitignore: true });
const rootDir = resolveRootDir(files);
const destDir = rootDir.replace(/^[^/]+/, 'dist');
const templates = files.reduce((acc, curr) => {
const name = curr.replace(rootDir, '').slice(1).split(sep)[0];
if (acc[name]) {
acc[name].push(resolve(curr));
} else {
acc[name] = [resolve(curr)];
}
return acc;
}, {});
let meta = {};
return Promise.all(
Object.entries(templates).map(([template, files]) => {
const cwd = resolve(join(rootDir, template));
const dest = join(destDir, `${template}.tgz`);
const metafile = files.find((f) => f.endsWith('meta.json'));
if (metafile) {
files = files.filter((f) => f !== metafile);
meta[template] = JSON.parse(readFileSync(metafile).toString());
}
return fs.mkdir(dirname(dest), { recursive: true }).then(() =>
tar.create(
{
gzip: true,
portable: true,
file: dest,
cwd,
},
files.map((f) => f.replace(cwd, '').slice(1))
)
);
})
).then(() => {
if (Object.keys(meta).length > 0) {
return fs.writeFile(resolve(destDir, 'meta.json'), JSON.stringify(meta, null, 2));
}
});
}
const files = await glob(patterns);
await Promise.all(
files.map((file) => {
const dest = resolve(file.replace(/^[^/]+/, 'dist'));
return fs
.mkdir(dirname(dest), { recursive: true })
.then(() => fs.copyFile(resolve(file), dest, fs.constants.COPYFILE_FICLONE));
})
);
}
function resolveRootDir(files) {
return files
.reduce((acc, curr) => {
const currParts = curr.split(sep);
if (acc.length === 0) return currParts;
const result = [];
currParts.forEach((part, i) => {
if (acc[i] === part) result.push(part);
});
return result;
}, [])
.join(sep);
}