-
Notifications
You must be signed in to change notification settings - Fork 86
/
build.ts
executable file
·390 lines (333 loc) · 11.3 KB
/
build.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
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
/* eslint-disable no-sync */
/// <reference path="./globals.d.ts" />
import * as path from 'path'
import * as cp from 'child_process'
import * as fs from 'fs-extra'
import packager, {
OsxNotarizeOptions,
OsxSignOptions,
Options,
} from 'electron-packager'
import frontMatter from 'front-matter'
import { externals } from '../app/webpack.common'
interface IChooseALicense {
readonly title: string
readonly nickname?: string
readonly featured?: boolean
readonly hidden?: boolean
}
export interface ILicense {
readonly name: string
readonly featured: boolean
readonly body: string
readonly hidden: boolean
}
import { getBundleID, getProductName } from '../app/package-info'
import {
getChannel,
getDistRoot,
getExecutableName,
isPublishable,
getIconFileName,
} from './dist-info'
import { isCircleCI, isGitHubActions } from './build-platforms'
import { updateLicenseDump } from './licenses/update-license-dump'
import { verifyInjectedSassVariables } from './validate-sass/validate-all'
const projectRoot = path.join(__dirname, '..')
const entitlementsPath = `${projectRoot}/script/entitlement.plist`
const extendInfoPath = `${projectRoot}/script/info.plist`
const outRoot = path.join(projectRoot, 'out')
const isPublishableBuild = isPublishable()
const isDevelopmentBuild = getChannel() === 'development'
console.log(`Building for ${getChannel()}…`)
console.log('Removing old distribution…')
fs.removeSync(getDistRoot())
console.log('Copying dependencies…')
copyDependencies()
console.log('Packaging emoji…')
copyEmoji()
console.log('Copying static resources…')
copyStaticResources()
console.log('Parsing license metadata…')
generateLicenseMetadata(outRoot)
moveAnalysisFiles()
if (isGitHubActions() && process.platform === 'darwin' && isPublishableBuild) {
console.log('Setting up keychain…')
cp.execSync(path.join(__dirname, 'setup-macos-keychain'))
}
verifyInjectedSassVariables(outRoot)
.catch(err => {
console.error(
'Error verifying the Sass variables in the rendered app. This is fatal for a published build.'
)
if (!isDevelopmentBuild) {
process.exit(1)
}
})
.then(() => {
console.log('Updating our licenses dump…')
return updateLicenseDump(projectRoot, outRoot).catch(err => {
console.error(
'Error updating the license dump. This is fatal for a published build.'
)
console.error(err)
if (!isDevelopmentBuild) {
process.exit(1)
}
})
})
.then(() => {
console.log('Packaging…')
return packageApp()
})
.catch(err => {
console.error(err)
process.exit(1)
})
.then(appPaths => {
console.log(`Built to ${appPaths}`)
})
/**
* The additional packager options not included in the existing typing.
*
* See https://github.com/desktop/desktop/issues/2429 for some history on this.
*/
interface IPackageAdditionalOptions {
readonly protocols: ReadonlyArray<{
readonly name: string
readonly schemes: ReadonlyArray<string>
}>
readonly osxSign: OsxSignOptions & {
readonly hardenedRuntime?: boolean
}
}
function packageApp() {
// get notarization deets, unless we're not going to publish this
const notarizationCredentials = isPublishableBuild
? getNotarizationCredentials()
: undefined
if (
isPublishableBuild &&
(isCircleCI() || isGitHubActions()) &&
process.platform === 'darwin' &&
notarizationCredentials === undefined
) {
// we can't publish a mac build without these
throw new Error(
'Unable to retreive appleId and/or appleIdPassword to notarize macOS build'
)
}
const options: Options & IPackageAdditionalOptions = {
name: getExecutableName(),
platform: 'darwin',
arch: 'x64',
asar: false, // TODO: Probably wanna enable this down the road.
out: getDistRoot(),
icon: path.join(projectRoot, 'app', 'static', 'logos', getIconFileName()),
dir: outRoot,
overwrite: true,
tmpdir: false,
derefSymlinks: false,
prune: false, // We'll prune them ourselves below.
ignore: [
new RegExp('/node_modules/electron($|/)'),
new RegExp('/node_modules/electron-packager($|/)'),
new RegExp('/\\.git($|/)'),
new RegExp('/node_modules/\\.bin($|/)'),
],
appCopyright: 'Copyright © 2019 Mathieu Dutour.',
// macOS
appBundleId: getBundleID(),
appCategoryType: 'public.app-category.developer-tools',
darwinDarkModeSupport: true,
osxSign: {
entitlements: entitlementsPath,
'entitlements-inherit': entitlementsPath,
'gatekeeper-assess': false,
type: isPublishableBuild ? 'distribution' : 'development',
},
osxNotarize: notarizationCredentials,
protocols: [
{
name: getBundleID(),
schemes: [
!isDevelopmentBuild ? 'x-kactus-auth' : 'x-kactus-dev-auth',
'x-kactus-client',
'x-github-client',
'github-mac',
'kactus',
],
},
],
extendInfo: extendInfoPath,
}
return packager(options)
}
function removeAndCopy(source: string, destination: string) {
fs.removeSync(destination)
fs.copySync(source, destination)
}
function copyEmoji() {
const emojiImages = path.join(projectRoot, 'gemoji', 'images', 'emoji')
const emojiImagesDestination = path.join(outRoot, 'emoji')
removeAndCopy(emojiImages, emojiImagesDestination)
const emojiJSON = path.join(projectRoot, 'gemoji', 'db', 'emoji.json')
const emojiJSONDestination = path.join(outRoot, 'emoji.json')
removeAndCopy(emojiJSON, emojiJSONDestination)
}
function copyStaticResources() {
const dirName = process.platform
const platformSpecific = path.join(projectRoot, 'app', 'static', dirName)
const common = path.join(projectRoot, 'app', 'static', 'common')
const destination = path.join(outRoot, 'static')
fs.removeSync(destination)
if (fs.existsSync(platformSpecific)) {
fs.copySync(platformSpecific, destination)
}
fs.copySync(common, destination, { overwrite: false })
}
function moveAnalysisFiles() {
const rendererReport = 'renderer.report.html'
const analysisSource = path.join(outRoot, rendererReport)
if (fs.existsSync(analysisSource)) {
const distRoot = getDistRoot()
const destination = path.join(distRoot, rendererReport)
fs.mkdirpSync(distRoot)
// there's no moveSync API here, so let's do it the old fashioned way
//
// unlinkSync below ensures that the analysis file isn't bundled into
// the app by accident
fs.copySync(analysisSource, destination, { overwrite: true })
fs.unlinkSync(analysisSource)
}
}
function copyDependencies() {
const originalPackage: Package = require(path.join(
projectRoot,
'app',
'package.json'
))
const oldDependencies = originalPackage.dependencies
const newDependencies: PackageLookup = {}
for (const name of Object.keys(oldDependencies)) {
const spec = oldDependencies[name]
if (externals.indexOf(name) !== -1) {
newDependencies[name] = spec
}
}
const oldDevDependencies = originalPackage.devDependencies
const newDevDependencies: PackageLookup = {}
if (isDevelopmentBuild) {
for (const name of Object.keys(oldDevDependencies)) {
const spec = oldDevDependencies[name]
if (externals.indexOf(name) !== -1) {
newDevDependencies[name] = spec
}
}
}
// The product name changes depending on whether it's a prod build or dev
// build, so that we can have them running side by side.
const updatedPackage = Object.assign({}, originalPackage, {
productName: getProductName(),
dependencies: newDependencies,
devDependencies: newDevDependencies,
})
if (!isDevelopmentBuild) {
delete updatedPackage.devDependencies
}
fs.writeFileSync(
path.join(outRoot, 'package.json'),
JSON.stringify(updatedPackage)
)
fs.removeSync(path.resolve(outRoot, 'node_modules'))
if (
Object.keys(newDependencies).length ||
Object.keys(newDevDependencies).length
) {
console.log(' Installing dependencies via npm…')
cp.execSync('npm install', { cwd: outRoot, env: process.env })
}
console.log(' Copying desktop-trampoline…')
const desktopTrampolineDir = path.resolve(outRoot, 'desktop-trampoline')
const desktopTrampolineFile =
process.platform === 'win32'
? 'desktop-trampoline.exe'
: 'desktop-trampoline'
fs.removeSync(desktopTrampolineDir)
fs.mkdirSync(desktopTrampolineDir)
fs.copySync(
path.resolve(
projectRoot,
'app/node_modules/desktop-trampoline/build/Release',
desktopTrampolineFile
),
path.resolve(desktopTrampolineDir, desktopTrampolineFile)
)
console.log(' Copying git environment…')
const gitDir = path.resolve(outRoot, 'git')
fs.removeSync(gitDir)
fs.mkdirpSync(gitDir)
fs.copySync(path.resolve(projectRoot, 'app/node_modules/dugite/git'), gitDir)
console.log(' Copying app-path binary…')
const appPathMain = path.resolve(outRoot, 'main')
fs.removeSync(appPathMain)
fs.copySync(
path.resolve(projectRoot, 'app/node_modules/app-path/main'),
appPathMain
)
}
function generateLicenseMetadata(outRoot: string) {
const chooseALicense = path.join(outRoot, 'static', 'choosealicense.com')
const licensesDir = path.join(chooseALicense, '_licenses')
const files = fs.readdirSync(licensesDir)
const licenses = new Array<ILicense>()
for (const file of files) {
const fullPath = path.join(licensesDir, file)
const contents = fs.readFileSync(fullPath, 'utf8')
const result = frontMatter<IChooseALicense>(contents)
const licenseText = result.body.trim()
// ensure that any license file created in the app does not trigger the
// "no newline at end of file" warning when viewing diffs
const licenseTextWithNewLine = `${licenseText}\n`
const license: ILicense = {
name: result.attributes.nickname || result.attributes.title,
featured: result.attributes.featured || false,
hidden:
result.attributes.hidden === undefined || result.attributes.hidden,
body: licenseTextWithNewLine,
}
if (!license.hidden) {
licenses.push(license)
}
}
const licensePayload = path.join(outRoot, 'static', 'available-licenses.json')
const text = JSON.stringify(licenses)
fs.writeFileSync(licensePayload, text, 'utf8')
// embed the license alongside the generated license payload
const chooseALicenseLicense = path.join(chooseALicense, 'LICENSE.md')
const licenseDestination = path.join(
outRoot,
'static',
'LICENSE.choosealicense.md'
)
const licenseText = fs.readFileSync(chooseALicenseLicense, 'utf8')
const licenseWithHeader = `Kactus uses licensing information provided by choosealicense.com.
The bundle in available-licenses.json has been generated from a source list provided at https://github.com/github/choosealicense.com, which is made available under the below license:
------------
${licenseText}`
fs.writeFileSync(licenseDestination, licenseWithHeader, 'utf8')
// sweep up the choosealicense directory as the important bits have been bundled in the app
fs.removeSync(chooseALicense)
}
function getNotarizationCredentials(): OsxNotarizeOptions | undefined {
const appleId = process.env.APPLE_ID
const appleIdPassword = process.env.APPLE_ID_PASSWORD
if (appleId === undefined || appleIdPassword === undefined) {
return undefined
}
return {
ascProvider: process.env.APPLE_TEAM,
appleId,
appleIdPassword,
}
}