Skip to content

Commit ebe0daa

Browse files
committed
untested: refactored existing code and moved it to engine.ts
1 parent df7d476 commit ebe0daa

File tree

9 files changed

+95
-278
lines changed

9 files changed

+95
-278
lines changed

angular-cli-ghpages

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
#!/usr/bin/env node
22

3-
var index = require('../index'),
3+
var engine = require('../engine/engine'),
44
pjson = require('../package.json'),
5-
defaults = require('../defaults'),
6-
program = require('commander');
5+
defaults = require('../engine/defaults'),
6+
commander = require('commander');
77

8-
program
8+
commander
99
.version(pjson.version)
1010
.description(pjson.description)
1111
.option('-d, --dir <dir>', 'Directory for all published sources, relative to the project-root.', defaults.dir)
@@ -20,7 +20,19 @@ program
2020
.option('--dry-run', 'For testing: Run through without making any changes.', defaults.dryRun)
2121
.parse(process.argv);
2222

23-
index.run(program)
23+
var consoleLogger = {
24+
createChild: () => consoleLogger,
25+
log: console.log,
26+
debug: console.debug,
27+
info: console.info,
28+
warn: console.warn,
29+
error: console.error,
30+
fatal: console.error,
31+
};
32+
33+
var dir = path.join(process.cwd(), options.dir);
34+
35+
engine.run(dir, commander, consoleLogger)
2436
.catch(function (error) {
2537
process.exit(1);
2638
})

deploy/actions.ts

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,30 @@
11
import { BuilderContext } from '@angular-devkit/architect';
2-
import { GHPages } from '../interfaces';
32
import { Schema as RealDeployOptions } from './schema';
4-
import { json } from '@angular-devkit/core';
3+
import { json, logging } from '@angular-devkit/core';
4+
import { run } from '../engine/engine';
5+
56
type DeployOptions = RealDeployOptions & json.JsonObject;
67

78
export default async function deploy(
8-
ghPages: GHPages,
99
context: BuilderContext,
1010
projectRoot: string,
1111
options: DeployOptions
1212
) {
13+
1314
if (!context.target) {
1415
throw new Error('Cannot execute the build target');
1516
}
1617

1718
context.logger.info(`📦 Building "${context.target.project}"`);
1819

19-
// TODO: check if it's possible to override production via --configuration=xxx
20-
const run = await context.scheduleTarget(
21-
{
20+
const build = await context.scheduleTarget({
2221
target: 'build',
2322
project: context.target.project,
2423
configuration: 'production'
2524
},
2625
options
2726
);
28-
await run.result;
29-
30-
try {
31-
await ghPages.publish(projectRoot, {});
27+
await build.result;
3228

33-
context.logger.info(`🚀 Your application is now deployed. Have a nice day!`);
34-
35-
} catch (e) {
36-
context.logger.error(e);
37-
}
29+
await run(projectRoot, options, context.logger as unknown as logging.LoggerApi);
3830
}

deploy/builder.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ import { experimental, join, normalize, json } from '@angular-devkit/core';
99
import { Schema as RealDeployOptions } from './schema';
1010
type DeployOptions = RealDeployOptions & json.JsonObject;
1111

12-
const ghpages = require('gh-pages');
13-
1412
// Call the createBuilder() function to create a builder. This mirrors
1513
// createJobHandler() but add typings specific to Architect Builders.
1614
export default createBuilder<any>(
@@ -45,7 +43,6 @@ export default createBuilder<any>(
4543

4644
try {
4745
await deploy(
48-
ghpages,
4946
context,
5047
join(workspace.root, targets.build.options.outputPath),
5148
options
File renamed without changes.
Lines changed: 71 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,61 @@
1-
import * as denodeify from 'denodeify';
21
import * as path from 'path';
32
import * as fs from 'fs';
43
import * as fse from 'fs-extra';
54

6-
import { GHPages } from './interfaces';
7-
import { Schema as RealDeployOptions } from './deploy/schema';
5+
import { logging } from '@angular-devkit/core';
6+
import { defaults } from './defaults';
7+
import { GHPages } from '../interfaces';
8+
import { Schema as RealDeployOptions } from '../deploy/schema';
89

910
const ghpages = require('gh-pages');
10-
var access = denodeify(fs.access);
1111

12-
function run(options: RealDeployOptions) {
12+
export async function run(dir: string, options: RealDeployOptions, logger: logging.LoggerApi) {
1313

14-
options = options || {};
14+
options = prepareOptions(options, logger);
15+
16+
// always clean the cache directory.
17+
// avoids "Error: Remote url mismatch."
18+
if (options.dryRun) {
19+
logger.info('*** Dry-run / SKIPPED: cleaning of the cache directory');
20+
} else {
21+
ghpages.clean();
22+
}
23+
24+
try {
25+
checkIfDistFolderExists(dir);
26+
await createNotFoundPage(dir, options, logger);
27+
await createCnameFile(dir, options, logger);
28+
await publishViaGhPages(ghpages, dir, options, logger);
29+
30+
logger.info('*** 🚀 Successfully published! Have a nice day!');
31+
}
32+
catch (error) {
33+
logger.error('*** An error occurred!', error);
34+
throw error;
35+
}
36+
};
37+
38+
39+
function prepareOptions(options: RealDeployOptions, logger: logging.LoggerApi) {
40+
41+
options = {
42+
...defaults,
43+
options
44+
};
1545

1646
if (options.dryRun) {
17-
console.log('*** Dry-run: No changes are applied at all.')
47+
logger.info('*** Dry-run: No changes are applied at all.');
1848
}
1949

2050
if (options.name && options.email) {
2151
options.user = {
2252
name: options.name,
2353
email: options.email
24-
}
54+
};
2555
};
2656

27-
// gh-pages: forwards messages to console
28-
options.logger = function (message) { console.log(message + "\n"); }
29-
30-
var dir = path.join(process.cwd(), options.dir);
57+
// gh-pages internal: forwards messages to logger
58+
options.logger = function (message) { logger.info(message); };
3159

3260
if (process.env.TRAVIS) {
3361
options.message += ' -- ' + process.env.TRAVIS_COMMIT_MESSAGE + ' \n\n' +
@@ -36,7 +64,7 @@ function run(options: RealDeployOptions) {
3664
}
3765

3866
if (process.env.CIRCLECI) {
39-
options.message += ' -- \n\n' +
67+
options.message += '\n\n' +
4068
'Triggered by commit: https://github.com/' + process.env.CIRCLE_PROJECT_USERNAME + '/' + process.env.CIRCLE_PROJECT_REPONAME + '/commit/' + process.env.CIRCLE_SHA1 + '\n' +
4169
'CircleCI build: ' + process.env.CIRCLE_BUILD_URL;
4270
}
@@ -46,87 +74,65 @@ function run(options: RealDeployOptions) {
4674
options.repo = options.repo.replace('GH_TOKEN', process.env.GH_TOKEN);
4775
}
4876

49-
// always clean the cache directory.
50-
// avoids "Error: Remote url mismatch."
51-
if (options.dryRun) {
52-
console.info('*** Dry-run / SKIPPED: cleaning of the cache directory');
53-
} else {
54-
ghpages.clean();
55-
}
56-
57-
58-
var publish = denodeify(ghpages.publish);
59-
60-
61-
return Promise.resolve()
62-
.then(() => checkIfDistFolderExists(dir))
63-
.catch((error) => handleMissingDistFolder(error))
64-
.then(() => createNotFoundPage(dir, options))
65-
.then(() => createCnameFile(dir, options))
66-
.then(() => publishViaGhPages(ghpages, dir, options))
67-
.then(() => showSuccess())
68-
.catch((error) => showError(error));
69-
};
70-
71-
72-
function checkIfDistFolderExists(dir: string) {
73-
const flag = fs['F_OK'];
74-
return access(dir, flag);
77+
return options;
7578
}
7679

77-
function handleMissingDistFolder(error) {
78-
console.error('*** Dist folder does not exist. Check the dir --dir parameter or build the project first!\n');
79-
return Promise.reject(error);
80+
function checkIfDistFolderExists(dir: string) {
81+
if (!fs.existsSync(dir)) {
82+
throw new Error('*** Dist folder does not exist. Check the dir --dir parameter or build the project first!');
83+
}
8084
}
8185

82-
function createNotFoundPage(dir: string, options: RealDeployOptions) {
86+
async function createNotFoundPage(dir: string, options: RealDeployOptions, logger: logging.LoggerApi) {
8387

8488
if (options.dryRun) {
85-
console.info('*** Dry-run / SKIPPED: copying of index.html to 404.html');
89+
logger.info('*** Dry-run / SKIPPED: copying of index.html to 404.html');
8690
return;
8791
}
8892

8993
// Note:
9094
// There is no guarantee that there will be an index.html file,
9195
// as the developer may specify a custom index file.
96+
// TODO: respect setting in angular.json
9297
const indexHtml = path.join(dir, 'index.html');
9398
const notFoundPage = path.join(dir, '404.html');
9499

95-
return fse.copy(indexHtml, notFoundPage).
96-
catch(function (err) {
97-
console.info('index.html could not be copied to 404.html. Continuing without an error.');
98-
console.info('(Hint: are you sure that you have setup the --dir parameter correctly?)');
99-
console.dir(err);
100-
return;
101-
})
100+
try {
101+
return fse.copy(indexHtml, notFoundPage);
102+
}
103+
catch (err) {
104+
logger.info('index.html could not be copied to 404.html. This does not look like an angular project?!');
105+
logger.info('(Hint: are you sure that you have setup the directory correctly?)');
106+
logger.debug('Diagnostic info', err);
107+
return;
108+
}
102109
}
103110

104-
function createCnameFile(dir: string, options: RealDeployOptions) {
111+
async function createCnameFile(dir: string, options: RealDeployOptions, logger: logging.LoggerApi) {
105112

106113
if (!options.cname) {
107114
return;
108115
}
109116

110117
const cnameFile = path.join(dir, 'CNAME');
111118
if (options.dryRun) {
112-
console.info('*** Dry-run / SKIPPED: creating of CNAME file with content: ' + options.cname);
119+
logger.info('*** Dry-run / SKIPPED: creating of CNAME file with content: ' + options.cname);
113120
return;
114121
}
115122

116-
return fse.writeFile(cnameFile, options.cname)
117-
.then(function () {
118-
console.log('*** CNAME file created');
119-
})
120-
.catch(function (err) {
121-
console.info('*** CNAME file could not be created. Stopping execution.');
122-
throw err;
123-
})
123+
try {
124+
await fse.writeFile(cnameFile, options.cname);
125+
logger.info('*** CNAME file created');
126+
}
127+
catch (err) {
128+
logger.error('*** CNAME file could not be created. Stopping execution.');
129+
throw err;
130+
}
124131
}
125132

126-
127-
async function publishViaGhPages(ghPages: GHPages, dir: string, options: RealDeployOptions) {
133+
async function publishViaGhPages(ghPages: GHPages, dir: string, options: RealDeployOptions, logger: logging.LoggerApi) {
128134
if (options.dryRun) {
129-
console.info('*** Dry-run / SKIPPED: publishing to "' + dir + '" with the following options:', {
135+
logger.info('*** Dry-run / SKIPPED: publishing folder "' + dir + '" with the following options:', {
130136
dir: dir,
131137
repo: options.repo || 'undefined: current working directory (which must be a git repo in this case) will be used to commit & push',
132138
message: options.message,
@@ -136,19 +142,9 @@ async function publishViaGhPages(ghPages: GHPages, dir: string, options: RealDep
136142
noDotfiles: options.noDotfiles || 'undefined: dotfiles are included by default',
137143
dryRun: options.dryRun,
138144
cname: options.cname || 'undefined: no CNAME file will be created',
139-
});
145+
} as any);
140146
return;
141147
}
142148

143149
return await ghPages.publish(dir, options)
144150
}
145-
146-
function showSuccess() {
147-
console.log('*** Successfully published!\n');
148-
}
149-
150-
function showError(error) {
151-
console.error('*** An error occurred!\n');
152-
console.dir(error);
153-
return Promise.reject(error);
154-
}

0 commit comments

Comments
 (0)