forked from ionic-team/ionic-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
296 lines (252 loc) · 7.17 KB
/
Copy pathutils.ts
File metadata and controls
296 lines (252 loc) · 7.17 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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import archiver from 'archiver-promise';
import AWS from 'aws-sdk';
import { SpawnOptions, exec } from 'child_process';
import {
createReadStream,
createWriteStream,
existsSync,
lstatSync,
mkdirSync,
readFileSync,
readdirSync,
rmdirSync,
unlinkSync,
writeFileSync
} from 'fs';
import glob from 'glob';
import { basename, join } from 'path';
import { promisify } from 'util';
import * as semver from 'semver';
import {
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
FRAMEWORK_DOCS_DIR,
VERBOSE
} from './config';
AWS.config.update({
accessKeyId: AWS_ACCESS_KEY_ID,
secretAccessKey: AWS_SECRET_ACCESS_KEY
});
export const execp = promisify(exec);
const globp = promisify(glob);
// copy dir to target
export function copyDirectory(source, target) {
let files = [];
// check if folder needs to be created or integrated
const targetFolder = join(target, basename(source));
if (!existsSync(targetFolder)) {
mkdirSync(targetFolder);
}
// copy
if (lstatSync(source).isDirectory()) {
files = readdirSync(source);
for (let i = 0; i < files.length; i++) {
const curSource = join(source, files[i]);
if (lstatSync(curSource).isDirectory()) {
copyDirectory(curSource, targetFolder);
} else {
// async
copyFile(curSource, join(targetFolder, files[i]));
}
}
}
}
export function copyDirectoryTo(source, target) {
let files = [];
if (!existsSync(target)) {
console.log(target);
mkdirSync(target);
}
// check if folder needs to be created or integrated
const targetFolder = join(target, basename(source));
if (!existsSync(targetFolder)) {
mkdirSync(targetFolder);
}
// copy
if (lstatSync(source).isDirectory()) {
files = readdirSync(source);
files.forEach(file => {
const curSource = join(source, file);
if (lstatSync(curSource).isDirectory()) {
copyDirectoryTo(curSource, targetFolder);
} else {
copyFileSafeSync(curSource, targetFolder);
}
});
}
}
function copyFileSafeSync(source, target) {
let targetFile = target;
// if target is a directory a new file with the same name will be created
if (existsSync(target)) {
if (lstatSync(target).isDirectory()) {
targetFile = join(target, basename(source));
}
}
writeFileSync(targetFile, readFileSync(source));
}
export function copyFileSync(source, dest, hook) {
if (!existsSync(source)) {
vlog('Cannot copy - File does not exist ', source);
return false;
}
vlog('Copying file syncronously ', source);
let fileData = readFileSync(source);
if (typeof hook === 'function') {
// note, changing fileData from buffer to string
// writeFileSync accepts both
fileData = hook(fileData.toString('utf8'));
}
// create parent directory if it doesn't exist
const pathArray = dest.split('/');
pathArray.pop();
const parentDirectory = pathArray.join('/');
// console.log(dest, parentDirectory)
if (!existsSync(parentDirectory)) {
mkdirSync(parentDirectory);
}
writeFileSync(dest, fileData);
return true;
}
export function copyFile(source, target) {
const rd = createReadStream(source);
const wr = createWriteStream(target);
return new Promise((resolve, reject) => {
rd.on('error', reject);
wr.on('error', reject);
wr.on('finish', resolve);
rd.pipe(wr);
}).catch((error) => {
rd.destroy();
wr.end();
throw error;
});
}
export function filterParentDirectory(path) {
const pathArray = path.split('/');
return pathArray[pathArray.length - 2];
}
export async function preCheck() {
if (!existsSync(FRAMEWORK_DOCS_DIR)) {
mkdirSync(FRAMEWORK_DOCS_DIR);
}
return (await validateNPMVersion()) && validateNodeVersion(process.version);
}
// logging function that checks to see if VERBOSE mode is on
export function vlog(message, data = null) {
if (VERBOSE) {
if (data) {
console.log(message, data);
} else {
console.log(message);
}
}
}
export async function validateNPMVersion() {
const { stdout: npmVersion } = await execp('npm -v');
const { major, minor } = semver.parse(npmVersion.trim());
if (major < 5 || (major === 5 && minor < 8)) {
throw new Error(
'Running the CI scripts requires NPM version 5.8 or higher.'
);
}
return true;
}
export function validateNodeVersion(version: string) {
const { major, minor } = semver.parse(version);
if (major < 7 || (major === 7 && minor < 6)) {
throw new Error(
'Running the CI scripts requires Node version 7.6 or higher.'
);
}
return true;
}
export function listDirs(dir) {
return readdirSync(dir).filter(x => lstatSync(join(dir, x)).isDirectory());
}
export function deleteFolderRecursive(path) {
if (!path || path === '/') {
throw(new Error('Refusing to delete system root'));
}
if (existsSync(path)) {
readdirSync(path).forEach((file, index) => {
const curPath = join(path, file);
if (lstatSync(curPath).isDirectory()) { // recurse
deleteFolderRecursive(curPath);
} else { // delete file
unlinkSync(curPath);
}
});
rmdirSync(path);
}
}
/** Apply an intro class to the first set of paragraphs in a markdown file */
export function introify(text, introClass = 'intro') {
if (!text || text.length === 0) {
return text;
}
const lineArray = text.split('\n');
let lastLineEmpty = false;
for (let i = 0; i < lineArray.length; i++) {
if (
(i === 0 && lineArray[i].charAt(0) === '#') || // allow for h1's at the start
lineArray[i].length === 0
) {
lastLineEmpty = true;
continue;
}
// a code sample, table, or heading break out of the loop
if (
['##', '``', '- '].indexOf(lineArray[i].substring(0, 2)) !== -1 ||
['|', '>', '<'].indexOf(lineArray[i].charAt(0)) !== -1
) {
break;
}
if (lastLineEmpty || i === 0) {
// starting a new paragraph
lineArray[i] = `<p class="${introClass}">${lineArray[i]}</p>\n`;
} else {
// if the last line was a heading, move the closing tag down
lineArray[i - 1] = lineArray[i - 1].replace('</p>\n', '');
lineArray[i] = `${lineArray[i]}</p>\n`;
}
lastLineEmpty = false;
}
return lineArray.join('\n');
}
export async function createArchive(name: string, fileGlob: (string | string[])) {
const tmp = '.tmp';
if (!existsSync(tmp)) {
mkdirSync(tmp);
}
const globArray = typeof fileGlob === 'string' ? [fileGlob] : fileGlob;
let files = [];
for (const globStr of globArray) {
const foundFiles = await globp(globStr, {
root: process.cwd()
});
files = files.concat(foundFiles);
}
const zipPath = join(tmp, `${name}.zip`);
const archive = archiver(zipPath, { store: true });
for (const file of files) {
if (lstatSync(file).isDirectory()) {
archive.directory(file, file);
} else {
archive.file(file, { name: basename(file) });
}
}
await archive.finalize();
return zipPath;
}
export async function uploadToS3(filePath) {
const file = readFileSync(filePath);
const s3 = new AWS.S3();
return new Promise((resolve, reject) => {
s3.upload({
Bucket: 'ionic-docs',
Key: basename(filePath),
Body: file
}, resp => resolve(resp));
});
}