-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathindex.js
421 lines (386 loc) · 11.5 KB
/
index.js
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
const core = require('@actions/core')
const exec = require('@actions/exec')
const { DefaultArtifactClient } = require('@actions/artifact')
const cache = require('@actions/cache')
const path = require('path')
const fs = require('fs').promises
const yaml = require('js-yaml')
const crypto = require('crypto')
const { spawn } = require('child_process')
// The various paths to cache
const CACHE_PATH = [
'.flatpak-builder'
]
/**
* The options the action can take
*/
class Configuration {
constructor () {
// The flatpak manifest path
this.manifestPath = core.getInput('manifest-path')
// The module where the build should stop
this.stopAtModule = core.getInput('stop-at-module') || null
// Whether to run tests or not
this.runTests = core.getBooleanInput('run-tests')
// The bundle name
this.bundle = core.getInput('bundle') || 'app.flatpak'
this.branch = core.getInput('branch') || 'master'
// Whether to build a bundle or not
this.buildBundle = core.getBooleanInput('build-bundle')
// Whether to restore the cache or not
this.restoreCache = core.getBooleanInput('restore-cache')
// Whether to enable caching the build directory
this.cacheBuildDir = core.getBooleanInput('cache')
// The repository used to install the runtime from
this.repositoryUrl = core.getInput('repository-url')
// The repository name to install the runtime from
this.repositoryName = core.getInput('repository-name')
// The default cache key if there are any
this._cacheKey = core.getInput('cache-key')
// The CPU architecture to build for
this.arch = core.getInput('arch')
// The URL to mirror screenshots
this.mirrorScreenshotsUrl = core.getInput('mirror-screenshots-url')
// The key to sign the package
this.gpgSign = core.getInput('gpg-sign')
// Modified manifest path
this.modifiedManifestPath = path.join(
path.dirname(this.manifestPath),
`flatpak-github-action-modified-${path.basename(this.manifestPath)}`
)
// Computed manifest hash
this._manifestHash = null
// Where to build the application
this.buildDir = 'flatpak_app'
// The flatpak repository name
this.localRepoName = 'repo'
// Verbosity
this.verbose = core.getBooleanInput('verbose')
// Upload the artifact
this.uploadArtifact = core.getBooleanInput('upload-artifact')
}
async cacheKey () {
if (!this._cacheKey) {
try {
if (!this._manifestHash) { this._manifestHash = (await computeHash(this.manifestPath)).substring(0, 20) }
return `flatpak-builder-${this._manifestHash}-${this.arch}`
} catch (err) {
core.setFailed(`Fail to create create cache key based on manifest hash: ${err}`)
}
}
// Ensure the cache key is unique if we're building multiple architectures in the same job
return `${this._cacheKey}-${this.arch}`
}
}
/**
* Start a D-Bus session and return the process and the D-Bus address.
*
* @returns {Promise}
*/
const startDBusSession = () => {
return new Promise((resolve, reject) => {
const dbus = spawn('dbus-daemon', ['--session', '--print-address'])
dbus.stdout.on('data', (data) => {
try {
const decoder = new TextDecoder()
dbus.address = decoder.decode(data).trim()
resolve(dbus)
} catch (e) {
dbus.kill()
reject(e)
}
})
})
}
/**
* Compute a SHA-256 hash of a file.
*
* @param {PathLike} path The file path.
*/
const computeHash = async (path) => {
const hash = crypto.createHash('sha256')
const stream = await fs.readFile(path)
const buffer = Buffer.alloc(stream.byteLength)
for (let i = 0; i < buffer.length; i++) {
buffer[i] = stream[i]
}
hash.update(buffer)
return hash.digest('hex')
}
/**
* Parses a Flatpak manifest
*
* @param {PathLike} manifestPath The path to the manifest
* @returns {object} The manifest
*/
const parseManifest = async (manifestPath) => {
const data = await fs.readFile(manifestPath)
let manifest = null
switch (path.extname(manifestPath)) {
case '.json':
manifest = JSON.parse(data)
break
case '.yaml':
case '.yml':
manifest = yaml.load(data)
break
default:
core.setFailed(
'Unsupported manifest format, please use a YAML or a JSON file'
)
}
return manifest
}
/**
* Saves a manifest as a YAML or JSON file
*
* @param {object} manifest A Flatpak manifest
* @param {PathLike} dest Where to save the flatpak manifest
* @returns {object} The manifest
*/
const saveManifest = async (manifest, dest) => {
let data = null
switch (path.extname(dest)) {
case '.json':
data = JSON.stringify(manifest)
break
case '.yaml':
case '.yml':
data = yaml.dump(manifest)
break
default:
core.setFailed(
'Unsupported manifest format, please use a YAML or a JSON file'
)
}
await fs.writeFile(dest, data)
return manifest
}
/**
* Modify the manifest to prepare it for tests.
*
* Applies the following changes to the original manifest:
* - Add test-args are to enable network & x11 access.
*
* @param {Object} manifest The parsed manifest
* @param {boolean} runTests Whether to run tests or not
* @param {Object} testEnv Dictionary of environment variables
* @returns {object} The modified manifest
*/
const modifyManifest = (manifest, runTests = false, testEnv = {}) => {
if (runTests) {
const buildOptions = manifest['build-options'] || {}
const env = Object.assign({
...(buildOptions.env || {}),
DISPLAY: '0:0'
}, testEnv)
const testArgs = [
'--socket=x11',
'--share=network',
...(buildOptions['test-args'] || [])
]
manifest['build-options'] = {
...buildOptions,
'test-args': testArgs,
env
}
const module = manifest.modules.slice(-1)[0]
module['run-tests'] = runTests
}
return manifest
}
/**
* Build the Flatpak & create a bundle from the build
*
* @param {object} manifest A Flatpak manifest
* @param {PathLike} manifestPath The Flatpak manifest path
* @param {string} cacheHitKey The key used to restore the build directory
* @param {Configuration} config The build configuration
*/
const build = async (manifest, manifestPath, cacheHitKey, config) => {
const appId = manifest['app-id'] || manifest.id
const branch = manifest.branch || config.branch
let cacheKey
if (config.cacheBuildDir) { cacheKey = await config.cacheKey() }
core.info('Building the flatpak...')
const args = [
`--repo=${config.localRepoName}`,
'--disable-rofiles-fuse',
`--install-deps-from=${config.repositoryName}`,
'--force-clean',
`--default-branch=${branch}`,
`--arch=${config.arch}`
]
if (config.cacheBuildDir) {
args.push('--ccache')
}
if (config.mirrorScreenshotsUrl) {
args.push(`--mirror-screenshots-url=${config.mirrorScreenshotsUrl}`)
}
if (config.gpgSign) {
args.push(`--gpg-sign=${config.gpgSign}`)
}
if (config.stopAtModule) {
args.push(`--stop-at=${config.stopAtModule}`)
}
if (config.verbose) {
args.push('--verbose')
}
args.push(config.buildDir, manifestPath)
await exec.exec('xvfb-run --auto-servernum flatpak-builder', args)
if (config.cacheBuildDir && (cacheKey !== cacheHitKey)) {
await cache.saveCache(
[...CACHE_PATH], // TODO: drop once https://github.com/actions/toolkit/pull/1378 is merged
cacheKey
).catch((reason) => {
core.error(`Failed to save cache: ${reason}`)
})
}
if (config.buildBundle && !config.stopAtModule) {
core.info('Creating a bundle...')
const args = [
'build-bundle',
config.localRepoName,
config.bundle,
`--runtime-repo=${config.repositoryUrl}`,
`--arch=${config.arch}`,
appId,
branch
]
if (manifest['build-runtime'] || manifest['build-extension']) {
args.push('--runtime')
}
if (config.verbose) {
args.push('-vv', '--ostree-verbose')
}
await exec.exec('flatpak', args)
}
if (config.mirrorScreenshotsUrl) {
core.info('Committing screenshots...')
const ostreeArgs = [
'commit',
`--repo=${config.localRepoName}`,
'--canonical-permissions',
`--branch=screenshots/${config.arch}`,
`${config.buildDir}/screenshots`
]
if (config.verbose) {
ostreeArgs.push('--verbose')
}
exec.exec(
'ostree',
ostreeArgs
)
}
}
/**
* Initialize the build
*
* Consists of setting up the Flatpak remote if one other than the default is set
* and restoring the cache from the latest build
*
* @param {Configuration} config The build configuration
* @returns {Promise<String>} The cacheHitKey if a cache was hit
*/
const prepareBuild = async (config) => {
/// If the user has set a different runtime source
if (config.repositoryUrl !== 'https://flathub.org/repo/flathub.flatpakrepo') {
const args = [
'remote-add',
'--if-not-exists',
config.repositoryName,
config.repositoryUrl
]
if (config.verbose) {
args.push('-vv', '--ostree-verbose')
}
await exec.exec('flatpak', args)
}
// Restore the cache in case caching is enabled
let cacheHitKey
if (config.cacheBuildDir && config.restoreCache) {
const cacheKey = await config.cacheKey()
cacheHitKey = await cache.restoreCache(
[...CACHE_PATH], // TODO: drop once https://github.com/actions/toolkit/pull/1378 is merged
`${cacheKey}`,
[
'flatpak-builder-',
'flatpak-'
]
)
if (cacheHitKey !== undefined) {
core.info(`Restored cache with key: ${cacheHitKey}`)
} else {
core.info('No cache was found')
}
}
return cacheHitKey
}
/**
* Run a complete build
*
* @param {Configuration} config The build configuration
*/
const run = async (config) => {
if (config.verbose) {
await exec.exec('flatpak --version')
await exec.exec('flatpak-builder --version')
await exec.exec('ostree --version')
}
let cacheHitKey
try {
cacheHitKey = await prepareBuild(config)
} catch (err) {
core.setFailed(`Failed to prepare the build ${err}`)
}
const testEnv = {}
let dbusSession = null
if (config.runTests) {
dbusSession = await startDBusSession()
testEnv.DBUS_SESSION_BUS_ADDRESS = dbusSession.address
}
parseManifest(config.manifestPath)
.then((manifest) => {
const modifiedManifest = modifyManifest(manifest, config.runTests, testEnv)
return saveManifest(modifiedManifest, config.modifiedManifestPath)
})
.then((manifest) => {
return build(manifest, config.modifiedManifestPath, cacheHitKey, config)
})
.then(() => {
if (dbusSession) {
dbusSession.kill()
dbusSession = null
}
if (!config.buildBundle || config.stopAtModule) {
return
}
if (!config.uploadArtifact) {
core.info('Skipping artifact upload!')
return
}
const artifactClient = new DefaultArtifactClient()
core.info('Uploading artifact...')
// Append the arch to the bundle name to prevent conflicts in multi-arch jobs
const bundleName = config.bundle.replace('.flatpak', '') + `-${config.arch}`
return artifactClient.uploadArtifact(bundleName, [config.bundle], '.', {
continueOnError: false
})
})
.catch((error) => {
if (dbusSession) {
dbusSession.kill()
dbusSession = null
}
core.setFailed(`Build failed: ${error}`)
})
}
module.exports = {
computeHash,
parseManifest,
modifyManifest
}
if (require.main === module) {
const config = new Configuration()
run(config)
}