UNPKG

13.3 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var os = require("os");
4var path_1 = require("path");
5var del = require("del");
6var chek_1 = require("chek");
7var logger = require("./logger");
8var glob = require("glob");
9var clrs = require("colurs");
10var fs_extra_1 = require("fs-extra");
11var _pkg;
12exports.cwd = process.cwd();
13var colurs = clrs.get();
14var log = logger.get();
15/**
16 * Get Parsed
17 *
18 * @param filename the filename to path.parse.
19 */
20function getParsed(filename) {
21 filename = path_1.resolve(exports.cwd, filename);
22 return path_1.parse(filename);
23}
24/**
25 * Get Relative
26 *
27 * @param filename the filename to get relative path for.
28 */
29function getRelative(filename) {
30 var parsed = chek_1.isString(filename) ? getParsed(filename) : filename;
31 return path_1.relative(exports.cwd, path_1.join(parsed.dir, parsed.base || ''));
32}
33/**
34 * Seed
35 * Internal method for seeding examples/templates.
36 *
37 * @param type the type of seed to run.
38 * @param dest the optional destination relative to root.
39 */
40function seed(type, dest) {
41 var source = path_1.resolve(__dirname, path_1.join('blueprints', type));
42 dest = dest ? path_1.resolve(exports.cwd, dest) : path_1.resolve(exports.cwd, type);
43 switch (type) {
44 case 'build':
45 copyAll([source, dest]);
46 break;
47 default:
48 log.warn("seed type " + type + " was not found.");
49 break;
50 }
51}
52exports.seed = seed;
53/**
54 * Clean
55 * Removes file(s) using provided glob(s).
56 *
57 * @param globs glob or array of glob strings.
58 */
59function clean(globs) {
60 globs = chek_1.toArray(globs);
61 globs.forEach(function (g) {
62 try {
63 del.sync(g);
64 // Some files may not exist del doesn't throw
65 // error just continues.
66 // log.info(`successfully cleaned or ignored ${getRelative(g)}.`);
67 }
68 catch (ex) {
69 log.info("failed to clean " + getRelative(g) + ".");
70 }
71 });
72}
73exports.clean = clean;
74/**
75 * Copy
76 * Copies source to target. Does NOT support globs.
77 *
78 * @param src the source path to be copied.
79 * @param dest the destination path to copy to.
80 */
81function copy(src, dest) {
82 if (!src || !dest)
83 return false;
84 var parsedSrc, parsedDest;
85 parsedSrc = getParsed(src);
86 parsedDest = getParsed(dest);
87 try {
88 fs_extra_1.copySync(src, dest);
89 return true;
90 }
91 catch (ex) {
92 log.warn("failed to copy " + colurs.yellow(getRelative(parsedSrc || 'undefined')) + " to " + colurs.red(getRelative(parsedDest || 'undefined')) + ".");
93 return false;
94 }
95}
96exports.copy = copy;
97/**
98 * Copy All
99 * Takes collection and copies to destination.
100 *
101 * @param copies collection of source and destination targets.
102 */
103function copyAll(copies) {
104 var success = 0;
105 var failed = 0;
106 var result;
107 function update(_result) {
108 if (!_result)
109 failed++;
110 else
111 success++;
112 }
113 function logResults() {
114 // only log if something copied or failed.
115 if (success || failed) {
116 if (failed > success) {
117 if (!success)
118 log.error(colurs.red(failed) + " copies " + colurs.red('failed') + " to processes with 0 succeeding.");
119 else
120 log.warn(colurs.red(failed) + " copies " + colurs.red('failed') + " to processes with " + (colurs.green(success) + 'succeeding') + ".");
121 }
122 else {
123 log.info(colurs.green(success) + " items " + colurs.green('successfully') + " copied with " + colurs.yellow(failed) + " copies " + colurs.yellow('failing') + ".");
124 }
125 }
126 }
127 if (chek_1.isPlainObject(copies)) {
128 chek_1.keys(copies).forEach(function (k) {
129 var itm = copies[k];
130 // Check if src is glob.
131 if (itm.src.indexOf('*') !== -1) {
132 var arr = glob.sync(itm.src);
133 arr.forEach(function (str) {
134 result = copy(str, itm.dest);
135 update(result);
136 });
137 }
138 else {
139 result = copy(itm.src, itm.dest);
140 update(result);
141 }
142 });
143 logResults();
144 }
145 else if (chek_1.isArray(copies)) {
146 // If not array of tuples convert.
147 if (chek_1.isString(copies[0]))
148 copies = [copies[0].split('|')];
149 copies.forEach(function (c) {
150 var tuple = c;
151 if (tuple[0].indexOf('*') !== -1) {
152 var arr = glob.sync(tuple[0]);
153 arr.forEach(function (str) {
154 result = copy(str, tuple[1]);
155 update(result);
156 });
157 }
158 else {
159 result = copy(tuple[0], tuple[1]);
160 update(result);
161 }
162 });
163 logResults();
164 }
165 else {
166 log.warn("cannot copy using unknown configuration type of " + typeof copies + ".");
167 }
168}
169exports.copyAll = copyAll;
170/**
171 * Pkg
172 * Loads the package.json file for project or saves package.json.
173 *
174 * @param val the package.json object to be written to file.
175 */
176function pkg(val) {
177 var filename = path_1.resolve(exports.cwd, 'package.json');
178 try {
179 if (!val)
180 return _pkg || (_pkg = fs_extra_1.readJSONSync(filename));
181 fs_extra_1.writeJSONSync(filename, val, { spaces: 2 });
182 }
183 catch (ex) {
184 log.error(ex);
185 }
186}
187exports.pkg = pkg;
188/**
189 * Bump
190 * Bumps project to next version.
191 *
192 * @param filename optional filename defaults to package.json in cwd.
193 */
194function bump() {
195 var semverKeys = ['major', 'minor', 'patch'];
196 var _pkg = pkg();
197 if (!_pkg || !_pkg.version)
198 log.error('failed to load package.json, are you sure this is a valid project?').exit();
199 var origVer = _pkg.version;
200 var splitVer = _pkg.version.split('-');
201 var ver = (splitVer[0] || '').replace(/^(=|v|^|~)/, '');
202 var pre = splitVer[1] || '';
203 var verArr = chek_1.castType(chek_1.split(ver), ['integer'], []);
204 var preArr = [];
205 if (pre && pre.length)
206 preArr = chek_1.castType(chek_1.split(pre), ['string', 'integer'], []);
207 var arr = verArr;
208 var isPre = false;
209 if (preArr.length) {
210 arr = [].slice.call(preArr, 1); // remove first arg.
211 isPre = true;
212 }
213 var i = arr.length;
214 var bump;
215 while (i-- && !bump) {
216 var next = arr[i] + 1;
217 arr[i] = next;
218 bump = {
219 type: !isPre ? semverKeys[i] : 'pre',
220 next: next
221 };
222 if (isPre) {
223 bump.preArr = [preArr[0]].concat(arr);
224 bump.pre = bump.preArr.join('.');
225 bump.ver = ver;
226 bump.verArr = verArr;
227 }
228 else {
229 bump.ver = arr.join('.');
230 bump.verArr = arr;
231 bump.preArr = preArr;
232 bump.pre = pre;
233 }
234 bump.full = bump.pre && bump.pre.length ? bump.ver + '-' + bump.pre : bump.ver;
235 }
236 _pkg.version = bump.full;
237 pkg(_pkg);
238 // log.info(`bumped ${_pkg.name} from ${colurs.magenta(origVer)} to ${colurs.green(bump.full)}.`);
239 return { name: _pkg.name, version: _pkg.version, original: origVer };
240}
241exports.bump = bump;
242/**
243 * Serve
244 * Hook to Browser Sync accepts name and options returning a Browser Sync Server Instance.
245 * @see https://www.browsersync.io/docs/api
246 *
247 * @param name the name of the server or Browser Sync options.
248 * @param options the Browser Sync Options.
249 */
250function serve(name, options, init) {
251 var _pkg = pkg();
252 if (chek_1.isPlainObject(name)) {
253 init = options;
254 options = name;
255 name = undefined;
256 }
257 var defaults = {
258 server: {
259 baseDir: './dist'
260 }
261 };
262 name = name || _pkg.name || 'dev-server';
263 options = chek_1.extend({}, defaults, options);
264 var bsync = chek_1.tryRootRequire('browser-sync');
265 if (!bsync)
266 log.error('failed to load root module browser-sync, ensure the module is installed');
267 var server = bsync.create(name);
268 if (init !== false)
269 server.init(options, function (err) {
270 if (err) {
271 log.error(err);
272 }
273 else {
274 log.info("browser Sync server " + name + " successfully initialized.");
275 }
276 });
277 return server;
278}
279exports.serve = serve;
280/**
281 * Layout
282 * Creates a CLI layout much like creating divs in the terminal.
283 * Supports strings with \t \s \n or IUIOptions object.
284 * @see https://www.npmjs.com/package/cliui
285 *
286 * @param width the width of the layout.
287 * @param wrap if the layout should wrap.
288 */
289// export function layout(width?: number, wrap?: boolean) {
290// // Base width of all divs.
291// width = width || 95;
292// const ui = cliui({ width: width, wrap: wrap });
293// function invalidExit(element, elements) {
294// if (isString(element) && elements.length && isPlainObject(elements[0]))
295// log.error('invalid element(s) cannot mix string element with element options objects.').exit();
296// }
297// function add(type: string, ...elements: any[]) {
298// ui[type](...elements);
299// }
300// /**
301// * Div
302// * Adds Div to the UI.
303// *
304// * @param elements array of string or IUIOptions
305// */
306// function div<T>(...elements: T[]) {
307// add('div', ...elements);
308// }
309// /**
310// * Span
311// * Adds Span to the UI.
312// *
313// * @param elements array of string or IUIOptions
314// */
315// function span<T>(...elements: T[]) {
316// add('span', ...elements);
317// }
318// /**
319// * Join
320// * Simply joins element args separated by space.
321// *
322// * @param elements the elements to be created.
323// */
324// function join(...elements: any[]) {
325// add('div', elements.join(' '));
326// }
327// /**
328// * Get
329// * Gets the defined UI as string.
330// */
331// function getString() {
332// return ui.toString() || '';
333// }
334// /**
335// * Render
336// * Renders out the defined UI.
337// * When passing elements in render they default to "div" layout.
338// *
339// * @param elements optional elements to be defined at render.
340// */
341// function render<T>(...elements: T[]) {
342// if (elements.length)
343// add('div', ...elements);
344// console.log(getString());
345// }
346// // Alias for render.
347// const show = render;
348// return {
349// div,
350// join,
351// span,
352// render,
353// show,
354// ui
355// };
356// }
357/**
358 * String Builder
359 * Builds string then joins by char with optional colorization.
360 *
361 * @param str the base value to build from if any.
362 */
363// export function stringBuilder(str?: any): IStringBuilderMethods {
364// const arr = [];
365// str = str || '';
366// let methods: IStringBuilderMethods;
367// let result;
368// /**
369// * Add
370// * Adds a value to the collection for rendering.
371// *
372// * @param str the string to be added.
373// * @param styles any colurs styles to be applied.
374// */
375// function add(str: any, styles: string | string[]) {
376// if (isString(styles))
377// styles = (styles as string).split('.');
378// styles = toArray(styles, null, []);
379// if (styles.length)
380// str = colurs.applyAnsi(str, styles);
381// arr.push(str);
382// return methods;
383// }
384// /**
385// * Join
386// *
387// * @param char the char used for joining array.
388// */
389// function join(char?: string) {
390// char = char || ' ';
391// result = arr.join(char);
392// return methods;
393// }
394// /**
395// * Format
396// *
397// * @param args arguments used to format string.
398// */
399// function format(...args: any[]) {
400// if (!result)
401// join();
402// result = stringFormat(result, args);
403// return methods;
404// }
405// /**
406// * Render
407// * Joins and renders the built string.
408// *
409// * @param char optional character to join by.
410// */
411// function render(char?: string) {
412// if (result)
413// return result;
414// join();
415// return result;
416// }
417// methods = {
418// add,
419// join,
420// format,
421// render
422// };
423// return methods;
424// }
425/**
426 * String Format
427 * Very simple string formatter by index.
428 * Supports using %s or %n chars.
429 *
430 * @private
431 * @param str the string to be formatted.
432 * @param args arguments used for formatting.
433 */
434// export function stringFormat(str, ...args: any[]) {
435// let ctr = 0;
436// return str.replace(/%(s|n)/g, (cur) => {
437// const val = args[ctr];
438// ctr++;
439// return val || cur;
440// });
441// }
442/**
443 * Platform
444 * Gets information and paths for the current platform.
445 */
446function platform() {
447 var cpus = os.cpus();
448 var cpu = cpus[0];
449 cpu.cores = cpus.length;
450 var tmpPlatform = os.platform();
451 if (/^win/.test(tmpPlatform))
452 tmpPlatform = 'windows';
453 else if (tmpPlatform === 'darwin' || tmpPlatform === 'freebsd')
454 tmpPlatform = 'mac';
455 else if (tmpPlatform === 'linux')
456 tmpPlatform = 'linux';
457 return {
458 platform: tmpPlatform,
459 arch: os.arch(),
460 release: os.release(),
461 hostname: os.hostname(),
462 homedir: os.homedir(),
463 cpu: cpu
464 };
465}
466exports.platform = platform;
467//# sourceMappingURL=utils.js.map
\No newline at end of file