Skip to content

Commit

Permalink
untested: refactored existing code and moved it to engine.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
JohannesHoppe committed Aug 2, 2019
1 parent df7d476 commit ebe0daa
Show file tree
Hide file tree
Showing 9 changed files with 95 additions and 278 deletions.
22 changes: 17 additions & 5 deletions angular-cli-ghpages
@@ -1,11 +1,11 @@
#!/usr/bin/env node

var index = require('../index'),
var engine = require('../engine/engine'),
pjson = require('../package.json'),
defaults = require('../defaults'),
program = require('commander');
defaults = require('../engine/defaults'),
commander = require('commander');

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

index.run(program)
var consoleLogger = {
createChild: () => consoleLogger,
log: console.log,
debug: console.debug,
info: console.info,
warn: console.warn,
error: console.error,
fatal: console.error,
};

var dir = path.join(process.cwd(), options.dir);

engine.run(dir, commander, consoleLogger)
.catch(function (error) {
process.exit(1);
})
22 changes: 7 additions & 15 deletions deploy/actions.ts
@@ -1,38 +1,30 @@
import { BuilderContext } from '@angular-devkit/architect';
import { GHPages } from '../interfaces';
import { Schema as RealDeployOptions } from './schema';
import { json } from '@angular-devkit/core';
import { json, logging } from '@angular-devkit/core';
import { run } from '../engine/engine';

type DeployOptions = RealDeployOptions & json.JsonObject;

export default async function deploy(
ghPages: GHPages,
context: BuilderContext,
projectRoot: string,
options: DeployOptions
) {

if (!context.target) {
throw new Error('Cannot execute the build target');
}

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

// TODO: check if it's possible to override production via --configuration=xxx
const run = await context.scheduleTarget(
{
const build = await context.scheduleTarget({
target: 'build',
project: context.target.project,
configuration: 'production'
},
options
);
await run.result;

try {
await ghPages.publish(projectRoot, {});
await build.result;

context.logger.info(`🚀 Your application is now deployed. Have a nice day!`);

} catch (e) {
context.logger.error(e);
}
await run(projectRoot, options, context.logger as unknown as logging.LoggerApi);
}
3 changes: 0 additions & 3 deletions deploy/builder.ts
Expand Up @@ -9,8 +9,6 @@ import { experimental, join, normalize, json } from '@angular-devkit/core';
import { Schema as RealDeployOptions } from './schema';
type DeployOptions = RealDeployOptions & json.JsonObject;

const ghpages = require('gh-pages');

// Call the createBuilder() function to create a builder. This mirrors
// createJobHandler() but add typings specific to Architect Builders.
export default createBuilder<any>(
Expand Down Expand Up @@ -45,7 +43,6 @@ export default createBuilder<any>(

try {
await deploy(
ghpages,
context,
join(workspace.root, targets.build.options.outputPath),
options
Expand Down
File renamed without changes.
146 changes: 71 additions & 75 deletions engine.ts → engine/engine.ts
@@ -1,33 +1,61 @@
import * as denodeify from 'denodeify';
import * as path from 'path';
import * as fs from 'fs';
import * as fse from 'fs-extra';

import { GHPages } from './interfaces';
import { Schema as RealDeployOptions } from './deploy/schema';
import { logging } from '@angular-devkit/core';
import { defaults } from './defaults';
import { GHPages } from '../interfaces';
import { Schema as RealDeployOptions } from '../deploy/schema';

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

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

options = options || {};
options = prepareOptions(options, logger);

// always clean the cache directory.
// avoids "Error: Remote url mismatch."
if (options.dryRun) {
logger.info('*** Dry-run / SKIPPED: cleaning of the cache directory');
} else {
ghpages.clean();
}

try {
checkIfDistFolderExists(dir);
await createNotFoundPage(dir, options, logger);
await createCnameFile(dir, options, logger);
await publishViaGhPages(ghpages, dir, options, logger);

logger.info('*** 🚀 Successfully published! Have a nice day!');
}
catch (error) {
logger.error('*** An error occurred!', error);
throw error;
}
};


function prepareOptions(options: RealDeployOptions, logger: logging.LoggerApi) {

options = {
...defaults,
options
};

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

if (options.name && options.email) {
options.user = {
name: options.name,
email: options.email
}
};
};

// gh-pages: forwards messages to console
options.logger = function (message) { console.log(message + "\n"); }

var dir = path.join(process.cwd(), options.dir);
// gh-pages internal: forwards messages to logger
options.logger = function (message) { logger.info(message); };

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

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

// always clean the cache directory.
// avoids "Error: Remote url mismatch."
if (options.dryRun) {
console.info('*** Dry-run / SKIPPED: cleaning of the cache directory');
} else {
ghpages.clean();
}


var publish = denodeify(ghpages.publish);


return Promise.resolve()
.then(() => checkIfDistFolderExists(dir))
.catch((error) => handleMissingDistFolder(error))
.then(() => createNotFoundPage(dir, options))
.then(() => createCnameFile(dir, options))
.then(() => publishViaGhPages(ghpages, dir, options))
.then(() => showSuccess())
.catch((error) => showError(error));
};


function checkIfDistFolderExists(dir: string) {
const flag = fs['F_OK'];
return access(dir, flag);
return options;
}

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

function createNotFoundPage(dir: string, options: RealDeployOptions) {
async function createNotFoundPage(dir: string, options: RealDeployOptions, logger: logging.LoggerApi) {

if (options.dryRun) {
console.info('*** Dry-run / SKIPPED: copying of index.html to 404.html');
logger.info('*** Dry-run / SKIPPED: copying of index.html to 404.html');
return;
}

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

return fse.copy(indexHtml, notFoundPage).
catch(function (err) {
console.info('index.html could not be copied to 404.html. Continuing without an error.');
console.info('(Hint: are you sure that you have setup the --dir parameter correctly?)');
console.dir(err);
return;
})
try {
return fse.copy(indexHtml, notFoundPage);
}
catch (err) {
logger.info('index.html could not be copied to 404.html. This does not look like an angular project?!');
logger.info('(Hint: are you sure that you have setup the directory correctly?)');
logger.debug('Diagnostic info', err);
return;
}
}

function createCnameFile(dir: string, options: RealDeployOptions) {
async function createCnameFile(dir: string, options: RealDeployOptions, logger: logging.LoggerApi) {

if (!options.cname) {
return;
}

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

return fse.writeFile(cnameFile, options.cname)
.then(function () {
console.log('*** CNAME file created');
})
.catch(function (err) {
console.info('*** CNAME file could not be created. Stopping execution.');
throw err;
})
try {
await fse.writeFile(cnameFile, options.cname);
logger.info('*** CNAME file created');
}
catch (err) {
logger.error('*** CNAME file could not be created. Stopping execution.');
throw err;
}
}


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

return await ghPages.publish(dir, options)
}

function showSuccess() {
console.log('*** Successfully published!\n');
}

function showError(error) {
console.error('*** An error occurred!\n');
console.dir(error);
return Promise.reject(error);
}

0 comments on commit ebe0daa

Please sign in to comment.