-
Notifications
You must be signed in to change notification settings - Fork 12k
/
github-pages-deploy.ts
290 lines (257 loc) · 9.1 KB
/
github-pages-deploy.ts
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
const Command = require('../ember-cli/lib/models/command');
const SilentError = require('silent-error');
import denodeify = require('denodeify');
import { exec } from 'child_process';
import * as chalk from 'chalk';
import * as fs from 'fs';
import * as fse from 'fs-extra';
import * as path from 'path';
import WebpackBuild from '../tasks/build-webpack';
import CreateGithubRepo from '../tasks/create-github-repo';
import { CliConfig } from '../models/config';
import { oneLine } from 'common-tags';
const fsReadDir = <any>denodeify(fs.readdir);
const fsCopy = <any>denodeify(fse.copy);
interface GithubPagesDeployOptions {
message?: string;
target?: string;
environment?: string;
userPage?: boolean;
skipBuild?: boolean;
ghToken?: string;
ghUsername?: string;
baseHref?: string;
}
const githubPagesDeployCommand = Command.extend({
name: 'github-pages:deploy',
aliases: ['gh-pages:deploy'],
description: oneLine`
Build the test app for production, commit it into a git branch,
setup GitHub repo and push to it
`,
works: 'insideProject',
availableOptions: [
{
name: 'message',
type: String,
default: 'new gh-pages version',
description: 'The commit message to include with the build, must be wrapped in quotes.'
}, {
name: 'target',
type: String,
default: 'production',
aliases: ['t', { 'dev': 'development' }, { 'prod': 'production' }]
}, {
name: 'environment',
type: String,
default: '',
aliases: ['e']
}, {
name: 'user-page',
type: Boolean,
default: false,
description: 'Deploy as a user/org page'
}, {
name: 'skip-build',
type: Boolean,
default: false,
description: 'Skip building the project before deploying'
}, {
name: 'gh-token',
type: String,
default: '',
description: 'Github token'
}, {
name: 'gh-username',
type: String,
default: '',
description: 'Github username'
}, {
name: 'base-href',
type: String,
default: null,
aliases: ['bh']
}],
run: function(options: GithubPagesDeployOptions, rawArgs: string[]) {
const ui = this.ui;
const root = this.project.root;
const execOptions = {
cwd: root
};
if (options.environment === '') {
if (options.target === 'development') {
options.environment = 'dev';
}
if (options.target === 'production') {
options.environment = 'prod';
}
}
const projectName = this.project.pkg.name;
const outDir = CliConfig.fromProject().config.apps[0].outDir;
const indexFilename = CliConfig.fromProject().config.apps[0].index;
let ghPagesBranch = 'gh-pages';
let destinationBranch = options.userPage ? 'master' : ghPagesBranch;
let initialBranch: string;
let branchErrMsg = ' You might also need to return to the initial branch manually.';
// declared here so that tests can stub exec
const execPromise = <(cmd: string, options?: any) => Promise<string>>denodeify(exec);
const buildTask = new WebpackBuild({
ui: this.ui,
analytics: this.analytics,
cliProject: this.project,
target: options.target,
environment: options.environment,
outputPath: outDir
});
/**
* BaseHref tag setting logic:
* First, use --base-href flag value if provided.
* Else if --user-page is true, then keep baseHref default as declared in index.html.
* Otherwise auto-replace with `/${projectName}/`.
*/
const baseHref = options.baseHref || (options.userPage ? null : `/${projectName}/`);
const buildOptions = {
target: options.target,
environment: options.environment,
outputPath: outDir,
baseHref: baseHref,
};
const createGithubRepoTask = new CreateGithubRepo({
ui: this.ui,
analytics: this.analytics,
project: this.project
});
const createGithubRepoOptions = {
projectName,
ghUsername: options.ghUsername,
ghToken: options.ghToken
};
return checkForPendingChanges()
.then(build)
.then(saveStartingBranchName)
.then(createGitHubRepoIfNeeded)
.then(checkoutGhPages)
.then(cleanGhPagesBranch)
.then(copyFiles)
.then(createNotFoundPage)
.then(addAndCommit)
.then(returnStartingBranch)
.then(pushToGitRepo)
.then(printProjectUrl)
.catch(failGracefully);
function checkForPendingChanges() {
return execPromise('git status --porcelain')
.then((stdout: string) => {
if (/\w+/m.test(stdout)) {
let msg = 'Uncommitted file changes found! Please commit all changes before deploying.';
return Promise.reject(new SilentError(msg));
}
});
}
function build() {
if (options.skipBuild) { return Promise.resolve(); }
return buildTask.run(buildOptions);
}
function saveStartingBranchName() {
return execPromise('git rev-parse --abbrev-ref HEAD')
.then((stdout: string) => initialBranch = stdout.replace(/\s/g, ''));
}
function createGitHubRepoIfNeeded() {
return execPromise('git remote -v')
.then(function(stdout) {
if (!/origin\s+(https:\/\/|git@)github\.com/m.test(stdout)) {
return createGithubRepoTask.run(createGithubRepoOptions)
.then(() => {
// only push starting branch if it's not the destinationBranch
// this happens commonly when using github user pages, since
// they require the destination branch to be 'master'
if (destinationBranch !== initialBranch) {
execPromise(`git push -u origin ${initialBranch}`);
}
});
}
});
}
function checkoutGhPages() {
return execPromise(`git checkout ${ghPagesBranch}`)
.catch(createGhPagesBranch);
}
function createGhPagesBranch() {
return execPromise(`git checkout --orphan ${ghPagesBranch}`)
.then(() => execPromise('git rm --cached -r .', execOptions))
.then(() => execPromise('git add .gitignore', execOptions))
.then(() => execPromise('git clean -f -d', execOptions))
.then(() => execPromise(`git commit -m \"initial ${ghPagesBranch} commit\"`));
}
function cleanGhPagesBranch() {
return execPromise('git ls-files')
.then(function(stdout) {
let files = '';
stdout.split(/\n/).forEach(function(f) {
// skip .gitignore & 404.html
if (( f != '') && (f != '.gitignore') && (f != '404.html')) {
files = files.concat(`"${f}" `);
}
});
return execPromise(`git rm -r ${files}`)
.catch(() => {
// Ignoring errors when trying to erase files.
});
});
}
function copyFiles() {
return fsReadDir(outDir)
.then((files: string[]) => Promise.all(files.map((file) => {
if (file === '.gitignore') {
// don't overwrite the .gitignore file
return Promise.resolve();
}
return fsCopy(path.join(outDir, file), path.join('.', file));
})));
}
function createNotFoundPage() {
const indexHtml = path.join(root, indexFilename);
const notFoundPage = path.join(root, '404.html');
return fsCopy(indexHtml, notFoundPage);
}
function addAndCommit() {
return execPromise('git add .', execOptions)
.then(() => execPromise(`git commit -m "${options.message}"`))
.catch(() => {
let msg = 'No changes found. Deployment skipped.';
return returnStartingBranch()
.then(() => Promise.reject(new SilentError(msg)))
.catch(() => Promise.reject(new SilentError(msg.concat(branchErrMsg))));
});
}
function returnStartingBranch() {
return execPromise(`git checkout ${initialBranch}`);
}
function pushToGitRepo() {
return execPromise(`git push origin ${ghPagesBranch}:${destinationBranch}`)
.catch((err) => returnStartingBranch()
.catch(() => Promise.reject(err) ));
}
function printProjectUrl() {
return execPromise('git remote -v')
.then((stdout) => {
let match = stdout.match(/origin\s+(?:https:\/\/|git@)github\.com(?:\:|\/)([^\/]+)/m);
let userName = match[1].toLowerCase();
let url = `https://${userName}.github.io/${options.userPage ? '' : (baseHref + '/')}`;
ui.writeLine(chalk.green(`Deployed! Visit ${url}`));
ui.writeLine('Github pages might take a few minutes to show the deployed site.');
});
}
function failGracefully(error: Error) {
if (error && (/git clean/.test(error.message) || /Permission denied/.test(error.message))) {
ui.writeLine(error.message);
let msg = 'There was a permissions error during git file operations, ' +
'please close any open project files/folders and try again.';
return Promise.reject(new SilentError(msg.concat(branchErrMsg)));
} else {
return Promise.reject(error);
}
}
}
});
export default githubPagesDeployCommand;