forked from facebook/docusaurus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deploy.ts
293 lines (263 loc) · 9.71 KB
/
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
291
292
293
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import fs from 'fs-extra';
import shell from 'shelljs';
import chalk from 'chalk';
import {loadContext} from '../server';
import build from './build';
import {BuildCLIOptions} from '@docusaurus/types';
import path from 'path';
import os from 'os';
// GIT_PASS env variable should not appear in logs
function obfuscateGitPass(str: string) {
const gitPass = process.env.GIT_PASS;
return gitPass ? str.replace(gitPass, 'GIT_PASS') : str;
}
// Log executed commands so that user can figure out mistakes on his own
// for example: https://github.com/facebook/docusaurus/issues/3875
function shellExecLog(cmd: string) {
try {
const result = shell.exec(cmd);
console.log(
`${chalk.cyan('CMD:')} ${obfuscateGitPass(cmd)} ${chalk.cyan(
`(code: ${result.code})`,
)}`,
);
return result;
} catch (e) {
console.log(`${chalk.red('CMD:')} ${obfuscateGitPass(cmd)}`);
throw e;
}
}
export function buildSshUrl(
githubHost: string,
organizationName: string,
projectName: string,
githubPort?: string,
): string {
if (githubPort) {
return `ssh://git@${githubHost}:${githubPort}/${organizationName}/${projectName}.git`;
}
return `git@${githubHost}:${organizationName}/${projectName}.git`;
}
export function buildHttpsUrl(
gitCredentials: string,
githubHost: string,
organizationName: string,
projectName: string,
githubPort?: string,
): string {
if (githubPort) {
return `https://${gitCredentials}@${githubHost}:${githubPort}/${organizationName}/${projectName}.git`;
}
return `https://${gitCredentials}@${githubHost}/${organizationName}/${projectName}.git`;
}
export function hasSSHProtocol(sourceRepoUrl: string): boolean {
try {
if (new URL(sourceRepoUrl).protocol === 'ssh:') {
return true;
}
return false;
} catch {
// Fails when there isn't a protocol
return /^([\w-]+@)?[\w.-]+:[\w./_-]+(\.git)?/.test(sourceRepoUrl); // git@github.com:facebook/docusaurus.git
}
}
export default async function deploy(
siteDir: string,
cliOptions: Partial<BuildCLIOptions> = {},
): Promise<void> {
const {outDir, siteConfig, siteConfigPath} = await loadContext(siteDir, {
customConfigFilePath: cliOptions.config,
customOutDir: cliOptions.outDir,
});
if (typeof siteConfig.trailingSlash === 'undefined') {
console.warn(
chalk.yellow(`
Docusaurus recommendation:
When deploying to GitHub Pages, it is better to use an explicit "trailingSlash" site config.
Otherwise, GitHub Pages will add an extra trailing slash to your site urls only on direct-access (not when navigation) with a server redirect.
This behavior can have SEO impacts and create relative link issues.
`),
);
}
console.log('Deploy command invoked...');
if (!shell.which('git')) {
throw new Error('Git not installed or on the PATH!');
}
// Source repo is the repo from where the command is invoked
const sourceRepoUrl = shell
.exec('git config --get remote.origin.url', {silent: true})
.stdout.trim();
// The source branch; defaults to the currently checked out branch
const sourceBranch =
process.env.CURRENT_BRANCH ||
shell.exec('git rev-parse --abbrev-ref HEAD', {silent: true}).stdout.trim();
const gitUser = process.env.GIT_USER;
let useSSH =
process.env.USE_SSH !== undefined &&
process.env.USE_SSH.toLowerCase() === 'true';
if (!gitUser && !useSSH) {
// If USE_SSH is unspecified: try inferring from repo URL
if (process.env.USE_SSH === undefined && hasSSHProtocol(sourceRepoUrl)) {
useSSH = true;
} else {
throw new Error(
'Please set the GIT_USER environment variable, or explicitly specify USE_SSH instead!',
);
}
}
const organizationName =
process.env.ORGANIZATION_NAME ||
process.env.CIRCLE_PROJECT_USERNAME ||
siteConfig.organizationName;
if (!organizationName) {
throw new Error(
`Missing project organization name. Did you forget to define "organizationName" in ${siteConfigPath}? You may also export it via the ORGANIZATION_NAME environment variable.`,
);
}
console.log(`${chalk.cyan('organizationName:')} ${organizationName}`);
const projectName =
process.env.PROJECT_NAME ||
process.env.CIRCLE_PROJECT_REPONAME ||
siteConfig.projectName;
if (!projectName) {
throw new Error(
`Missing project name. Did you forget to define "projectName" in ${siteConfigPath}? You may also export it via the PROJECT_NAME environment variable.`,
);
}
console.log(`${chalk.cyan('projectName:')} ${projectName}`);
// We never deploy on pull request.
const isPullRequest =
process.env.CI_PULL_REQUEST || process.env.CIRCLE_PULL_REQUEST;
if (isPullRequest) {
shell.echo('Skipping deploy on a pull request.');
shell.exit(0);
}
// github.io indicates organization repos that deploy via default branch. All others use gh-pages.
// Organization deploys looks like:
// - Git repo: https://github.com/<organization>/<organization>.github.io
// - Site url: https://<organization>.github.io
const isGitHubPagesOrganizationDeploy = projectName.includes('.github.io');
if (
isGitHubPagesOrganizationDeploy &&
!process.env.DEPLOYMENT_BRANCH &&
!siteConfig.deploymentBranch
) {
throw new Error(`For GitHub pages organization deployments, 'docusaurus deploy' does not assume anymore that 'master' is your default Git branch.
Please provide the branch name to deploy to as an environment variable, for example DEPLOYMENT_BRANCH=main or DEPLOYMENT_BRANCH=master .
You can also set the deploymentBranch property in docusaurus.config.js .`);
}
const deploymentBranch =
process.env.DEPLOYMENT_BRANCH || siteConfig.deploymentBranch || 'gh-pages';
console.log(`${chalk.cyan('deploymentBranch:')} ${deploymentBranch}`);
const githubHost =
process.env.GITHUB_HOST || siteConfig.githubHost || 'github.com';
const githubPort = process.env.GITHUB_PORT || siteConfig.githubPort;
let deploymentRepoURL: string;
if (useSSH) {
deploymentRepoURL = buildSshUrl(
githubHost,
organizationName,
projectName,
githubPort,
);
} else {
const gitPass = process.env.GIT_PASS;
const gitCredentials = gitPass ? `${gitUser!}:${gitPass}` : gitUser!;
deploymentRepoURL = buildHttpsUrl(
gitCredentials,
githubHost,
organizationName,
projectName,
githubPort,
);
}
console.log(
`${chalk.cyan('Remote repo URL:')} ${obfuscateGitPass(deploymentRepoURL)}`,
);
// Check if this is a cross-repo publish.
const crossRepoPublish = !sourceRepoUrl.endsWith(
`${organizationName}/${projectName}.git`,
);
// We don't allow deploying to the same branch unless it's a cross publish.
if (sourceBranch === deploymentBranch && !crossRepoPublish) {
throw new Error(
`You cannot deploy from this branch (${sourceBranch}).` +
'\nYou will need to checkout to a different branch!',
);
}
// Save the commit hash that triggers publish-gh-pages before checking
// out to deployment branch.
const currentCommit = shellExecLog('git rev-parse HEAD').stdout.trim();
const runDeploy = async (outputDirectory: string) => {
const fromPath = outputDirectory;
const toPath = await fs.mkdtemp(
path.join(os.tmpdir(), `${projectName}-${deploymentBranch}`),
);
shell.cd(toPath);
// Check out deployment branch when cloning repository, and then remove all
// the files in the directory. If the 'clone' command fails, assume that
// the deployment branch doesn't exist, and initialize git in an empty
// directory, check out a clean deployment branch and add remote.
if (
shellExecLog(
`git clone --depth 1 --branch ${deploymentBranch} ${deploymentRepoURL} ${toPath}`,
).code === 0
) {
shellExecLog('git rm -rf .');
} else {
shellExecLog('git init');
shellExecLog(`git checkout -b ${deploymentBranch}`);
shellExecLog(`git remote add origin ${deploymentRepoURL}`);
}
try {
await fs.copy(fromPath, toPath);
} catch (error) {
throw new Error(
`Copying build assets from "${fromPath}" to "${toPath}" failed with error "${error}".`,
);
}
shellExecLog('git add --all');
const commitMessage =
process.env.CUSTOM_COMMIT_MESSAGE ||
`Deploy website - based on ${currentCommit}`;
const commitResults = shellExecLog(`git commit -m "${commitMessage}"`);
if (
shellExecLog(`git push --force origin ${deploymentBranch}`).code !== 0
) {
throw new Error(
'Running "git push" command failed. Does the GitHub user account you are using have push access to the repository?',
);
} else if (commitResults.code === 0) {
// The commit might return a non-zero value when site is up to date.
let websiteURL = '';
if (githubHost === 'github.com') {
websiteURL = projectName.includes('.github.io')
? `https://${organizationName}.github.io/`
: `https://${organizationName}.github.io/${projectName}/`;
} else {
// GitHub enterprise hosting.
websiteURL = `https://${githubHost}/pages/${organizationName}/${projectName}/`;
}
shell.echo(`Website is live at "${websiteURL}".`);
shell.exit(0);
}
};
if (!cliOptions.skipBuild) {
// Build static html files, then push to deploymentBranch branch of specified repo.
try {
await runDeploy(await build(siteDir, cliOptions, false));
} catch (buildError) {
console.error(buildError);
process.exit(1);
}
} else {
// Push current build to deploymentBranch branch of specified repo.
await runDeploy(outDir);
}
}