-
-
Notifications
You must be signed in to change notification settings - Fork 374
/
git-utils.ts
240 lines (213 loc) · 6.47 KB
/
git-utils.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
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as glob from '@actions/glob';
import path from 'path';
import fs from 'fs';
import {URL} from 'url';
import {Inputs, CmdResult} from './interfaces';
import {createDir} from './utils';
import {cp, rm} from 'shelljs';
export async function createBranchForce(branch: string): Promise<void> {
await exec.exec('git', ['init']);
await exec.exec('git', ['checkout', '--orphan', branch]);
return;
}
export function getServerUrl(): URL {
return new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
}
export async function deleteExcludedAssets(destDir: string, excludeAssets: string): Promise<void> {
if (excludeAssets === '') return;
core.info(`[INFO] delete excluded assets`);
const excludedAssetNames: Array<string> = excludeAssets.split(',');
const excludedAssetPaths = ((): Array<string> => {
const paths: Array<string> = [];
for (const pattern of excludedAssetNames) {
paths.push(path.join(destDir, pattern));
}
return paths;
})();
const globber = await glob.create(excludedAssetPaths.join('\n'));
const files = await globber.glob();
for await (const file of globber.globGenerator()) {
core.info(`[INFO] delete ${file}`);
}
rm('-rf', files);
return;
}
export async function copyAssets(
publishDir: string,
destDir: string,
excludeAssets: string
): Promise<void> {
core.info(`[INFO] prepare publishing assets`);
if (!fs.existsSync(destDir)) {
core.info(`[INFO] create ${destDir}`);
await createDir(destDir);
}
const dotGitPath = path.join(publishDir, '.git');
if (fs.existsSync(dotGitPath)) {
core.info(`[INFO] delete ${dotGitPath}`);
rm('-rf', dotGitPath);
}
core.info(`[INFO] copy ${publishDir} to ${destDir}`);
cp('-RfL', [`${publishDir}/*`, `${publishDir}/.*`], destDir);
await deleteExcludedAssets(destDir, excludeAssets);
return;
}
export async function setRepo(inps: Inputs, remoteURL: string, workDir: string): Promise<void> {
const publishDir = path.isAbsolute(inps.PublishDir)
? inps.PublishDir
: path.join(`${process.env.GITHUB_WORKSPACE}`, inps.PublishDir);
if (path.isAbsolute(inps.DestinationDir)) {
throw new Error('destination_dir should be a relative path');
}
const destDir = ((): string => {
if (inps.DestinationDir === '') {
return workDir;
} else {
return path.join(workDir, inps.DestinationDir);
}
})();
core.info(`[INFO] ForceOrphan: ${inps.ForceOrphan}`);
if (inps.ForceOrphan) {
await createDir(destDir);
core.info(`[INFO] chdir ${workDir}`);
process.chdir(workDir);
await createBranchForce(inps.PublishBranch);
await copyAssets(publishDir, destDir, inps.ExcludeAssets);
return;
}
const result: CmdResult = {
exitcode: 0,
output: ''
};
const options = {
listeners: {
stdout: (data: Buffer): void => {
result.output += data.toString();
}
}
};
try {
result.exitcode = await exec.exec(
'git',
['clone', '--depth=1', '--single-branch', '--branch', inps.PublishBranch, remoteURL, workDir],
options
);
if (result.exitcode === 0) {
await createDir(destDir);
if (inps.KeepFiles) {
core.info('[INFO] Keep existing files');
} else {
core.info(`[INFO] clean up ${destDir}`);
core.info(`[INFO] chdir ${destDir}`);
process.chdir(destDir);
await exec.exec('git', ['rm', '-r', '--ignore-unmatch', '*']);
}
core.info(`[INFO] chdir ${workDir}`);
process.chdir(workDir);
await copyAssets(publishDir, destDir, inps.ExcludeAssets);
return;
} else {
throw new Error(`Failed to clone remote branch ${inps.PublishBranch}`);
}
} catch (error) {
if (error instanceof Error) {
core.info(`[INFO] first deployment, create new branch ${inps.PublishBranch}`);
core.info(`[INFO] ${error.message}`);
await createDir(destDir);
core.info(`[INFO] chdir ${workDir}`);
process.chdir(workDir);
await createBranchForce(inps.PublishBranch);
await copyAssets(publishDir, destDir, inps.ExcludeAssets);
return;
} else {
throw new Error('unexpected error');
}
}
}
export function getUserName(userName: string): string {
if (userName) {
return userName;
} else {
return `${process.env.GITHUB_ACTOR}`;
}
}
export function getUserEmail(userEmail: string): string {
if (userEmail) {
return userEmail;
} else {
return `${process.env.GITHUB_ACTOR}@users.noreply.github.com`;
}
}
export async function setCommitAuthor(userName: string, userEmail: string): Promise<void> {
if (userName && !userEmail) {
throw new Error('user_email is undefined');
}
if (!userName && userEmail) {
throw new Error('user_name is undefined');
}
await exec.exec('git', ['config', 'user.name', getUserName(userName)]);
await exec.exec('git', ['config', 'user.email', getUserEmail(userEmail)]);
}
export function getCommitMessage(
msg: string,
fullMsg: string,
extRepo: string,
baseRepo: string,
hash: string
): string {
const msgHash = ((): string => {
if (extRepo) {
return `${baseRepo}@${hash}`;
} else {
return hash;
}
})();
const subject = ((): string => {
if (fullMsg) {
return fullMsg;
} else if (msg) {
return `${msg} ${msgHash}`;
} else {
return `deploy: ${msgHash}`;
}
})();
return subject;
}
export async function commit(allowEmptyCommit: boolean, msg: string): Promise<void> {
try {
if (allowEmptyCommit) {
await exec.exec('git', ['commit', '--allow-empty', '-m', `${msg}`]);
} else {
await exec.exec('git', ['commit', '-m', `${msg}`]);
}
} catch (error) {
if (error instanceof Error) {
core.info('[INFO] skip commit');
core.debug(`[INFO] skip commit ${error.message}`);
} else {
throw new Error('unexpected error');
}
}
}
export async function push(branch: string, forceOrphan: boolean): Promise<void> {
if (forceOrphan) {
await exec.exec('git', ['push', 'origin', '--force', branch]);
} else {
await exec.exec('git', ['push', 'origin', branch]);
}
}
export async function pushTag(tagName: string, tagMessage: string): Promise<void> {
if (tagName === '') {
return;
}
let msg = '';
if (tagMessage) {
msg = tagMessage;
} else {
msg = `Deployment ${tagName}`;
}
await exec.exec('git', ['tag', '-a', `${tagName}`, '-m', `${msg}`]);
await exec.exec('git', ['push', 'origin', `${tagName}`]);
}