1 | #!/usr/bin/env node
|
2 |
|
3 | const program = require('commander');
|
4 | const request = require('request');
|
5 | const fs = require('fs');
|
6 | const path = require('path');
|
7 | const { mkdir, mv, rm, pwd } = require('shelljs');
|
8 | const extract = require('extract-zip');
|
9 | const logger = require('./lib/logger');
|
10 | const validate = require('./lib/validators');
|
11 | const version = require('./package.json').version;
|
12 |
|
13 | const DEFAULT_REPO = 'https://github.com/mdyd-dev/directory-structure';
|
14 | const DEFAULT_BRANCH = 'master';
|
15 |
|
16 | const TMP_DIR = path.normalize(path.resolve(process.cwd(), '.tmp'));
|
17 | const TMP_PATH = path.normalize(path.resolve(TMP_DIR, 'directory-structure.zip'));
|
18 |
|
19 | const emptyTemp = () => rm('-rf', `${TMP_DIR}/*`);
|
20 | const createTemp = () => mkdir('-p', TMP_DIR);
|
21 | const removeTemp = () => rm('-rf', TMP_DIR);
|
22 | const repoNameFrom = () => program.url.split('/').pop();
|
23 | const dirExists = dir => fs.existsSync(path.join(process.cwd(), dir));
|
24 | const moveStructureToDestination = branch => {
|
25 | const EXTRACTED_STRUCTURE = path.normalize(path.resolve(TMP_DIR, `${repoNameFrom()}-${branch}`, '*'));
|
26 | return mv('-f', EXTRACTED_STRUCTURE, pwd());
|
27 | };
|
28 |
|
29 | const downloadZip = ({ url, branch }) => {
|
30 | logger.Info(`Downloading ${branch} branch from ${url} repository`);
|
31 | const zipfileUrl = `${url}/archive/${branch}.zip`;
|
32 | return request(zipfileUrl).pipe(fs.createWriteStream(TMP_PATH));
|
33 | };
|
34 |
|
35 | const extractZip = ({ branch }) => {
|
36 | extract(TMP_PATH, { dir: TMP_DIR }, error => {
|
37 | if (error) {
|
38 | logger.Error('Zip extraction failed. ', error);
|
39 | }
|
40 |
|
41 | moveStructureToDestination(branch);
|
42 |
|
43 | logger.Info('Directory structure created in your file system.');
|
44 |
|
45 | removeTemp();
|
46 | });
|
47 | };
|
48 |
|
49 | const init = () => {
|
50 | validate.url(program.url);
|
51 | createTemp();
|
52 | emptyTemp();
|
53 |
|
54 | if (dirExists('marketplace_builder') || dirExists('modules')) {
|
55 | logger.Error('Diretory structure already exists. Operation aborted.');
|
56 | }
|
57 |
|
58 | downloadZip(program).on('close', () => extractZip(program));
|
59 | };
|
60 |
|
61 | program
|
62 | .version(version)
|
63 | .option('--url <url>', 'theme github repository url', DEFAULT_REPO)
|
64 | .option('--branch <branch>', 'branch where the theme is located', DEFAULT_BRANCH);
|
65 |
|
66 | program.parse(process.argv);
|
67 |
|
68 | init();
|