-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathutil.ts
More file actions
227 lines (202 loc) · 6.07 KB
/
util.ts
File metadata and controls
227 lines (202 loc) · 6.07 KB
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
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'fs';
import { posix } from 'path';
import * as path from 'path';
import * as Archiver from 'archiver';
import {
parseGcloudIgnore,
parseKVString,
toPlatformPath,
} from '@google-github-actions/actions-utils';
import ignore from 'ignore';
import { EventFilter, SecretEnvVar, SecretVolume } from './client';
import { SecretName } from './secret';
/**
* OnZipEntryFunction is a function that is called for each entry in the
* archive.
*/
export type OnZipEntryFunction = (entry: Archiver.EntryData) => void;
/**
* ZipOptions is used as input to the zip function.
*/
export type ZipOptions = {
/**
* onZipAddEntry is called when an entry is added to the archive.
*/
onZipAddEntry?: OnZipEntryFunction;
/**
* onZipIgnoreEntry is called when an entry is ignored due to an ignore
* specification.
*/
onZipIgnoreEntry?: OnZipEntryFunction;
};
/**
* Zip a directory.
*
* @param dirPath Directory to zip.
* @param outputPath Path to output file.
* @param opts Options with which to invoke the zip.
* @returns filepath of the created zip file.
*/
export async function zipDir(
dirPath: string,
outputPath: string,
opts?: ZipOptions,
): Promise<string> {
// Check dirpath
if (!fs.existsSync(dirPath)) {
throw new Error(`Unable to find ${dirPath}`);
}
// Create output file stream
const output = fs.createWriteStream(outputPath);
// Process gcloudignore
const ignoreFile = toPlatformPath(path.join(dirPath, '.gcloudignore'));
const ignores = await parseGcloudIgnore(ignoreFile);
const ignorer = ignore().add(ignores);
const ignoreFn = (entry: Archiver.EntryData): false | Archiver.EntryData => {
if (ignorer.ignores(entry.name)) {
if (opts?.onZipIgnoreEntry) opts.onZipIgnoreEntry(entry);
return false;
}
return entry;
};
return new Promise((resolve, reject) => {
// Initialize archive
const archive = Archiver.create('zip', { zlib: { level: 7 } });
archive.on('entry', (entry) => {
// For some reason, TypeScript complains if this guard is outside the
// closure. It would be more performant just not create this listener, but
// alas...
if (opts?.onZipAddEntry) opts.onZipAddEntry(entry);
});
archive.on('warning', (err) => reject(err));
archive.on('error', (err) => reject(err));
output.on('finish', () => resolve(outputPath));
// Pipe all archive data to be written
archive.pipe(output);
// Add files in dir to archive iff file not ignored
archive.directory(dirPath, false, ignoreFn);
// Finish writing files
archive.finalize();
});
}
/**
* RealEntryData is an extended form of entry data.
*/
type RealEntryData = Archiver.EntryData & {
sourcePath?: string;
type?: string;
};
/**
* formatEntry formats the given entry data into a single-line string.
* @returns string
*/
export function formatEntry(entry: RealEntryData): string {
const name = entry.name;
const mode = entry.mode || '000';
const sourcePath = entry.sourcePath || 'unknown';
const type = (entry.type || 'unknown').toUpperCase()[0];
return `[${type}] (${mode}) ${name} => ${sourcePath}`;
}
/**
* stringToInt is a helper that converts the given string into an integer. If
* the given string is empty, it returns undefined. If the string is not empty
* and parseInt fails (returns NaN), it throws an error. Otherwise, it returns
* the integer value.
*
* @param str String to parse as an int.
* @returns Parsed integer or undefined if the input was the empty string.
*/
export function stringToInt(str: string): number | undefined {
str = (str || '').trim().replace(/[_,]/g, '');
if (str === '') {
return undefined;
}
const result = parseInt(str);
if (isNaN(result)) {
throw new Error(`input "${str}" is not a number`);
}
return result;
}
/**
* parseEventTriggerFilters is a helper that parses the inputs into a list of event
* filters.
*/
export function parseEventTriggerFilters(val: string): EventFilter[] | undefined {
const kv = parseKVString(val);
if (kv === undefined) {
return undefined;
}
const result: EventFilter[] = [];
for (const [key, value] of Object.entries(kv)) {
if (value.startsWith('PATTERN:')) {
result.push({
attribute: key,
value: value.slice(8),
operator: 'match-path-pattern',
});
} else {
result.push({
attribute: key,
value: value,
});
}
}
return result;
}
/**
* parseSecrets parses the input as environment variable and volume mounted
* secrets.
*/
export function parseSecrets(
val: string,
): [SecretEnvVar[] | undefined, SecretVolume[] | undefined] {
const kv = parseKVString(val);
if (kv === undefined) {
return [undefined, undefined];
}
const secretEnvVars: SecretEnvVar[] = [];
const secretVolumes: SecretVolume[] = [];
for (const [key, value] of Object.entries(kv)) {
const secretRef = new SecretName(value);
if (key.startsWith('/')) {
// SecretVolume
const mountPath = posix.dirname(key);
const pth = posix.basename(key);
secretVolumes.push({
mountPath: mountPath,
projectId: secretRef.project,
secret: secretRef.name,
versions: [
{
path: pth,
version: secretRef.version,
},
],
});
} else {
// SecretEnvVar
secretEnvVars.push({
key: key,
projectId: secretRef.project,
secret: secretRef.name,
version: secretRef.version,
});
}
}
return [secretEnvVars, secretVolumes];
}