-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathinstall.js
More file actions
212 lines (182 loc) · 7.67 KB
/
Copy pathinstall.js
File metadata and controls
212 lines (182 loc) · 7.67 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
/*
Copyright 2023 Adobe. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
const BaseCommand = require('../../BaseCommand')
const { Flags, Args } = require('@oclif/core')
const aioLogger = require('@adobe/aio-lib-core-logging')('@adobe/aio-cli-plugin-app:install', { provider: 'debug' })
const path = require('node:path')
const fs = require('fs-extra')
const execa = require('execa')
const unzipper = require('unzipper')
const { validateJsonWithSchema } = require('../../lib/install-helper')
const jsYaml = require('js-yaml')
const { USER_CONFIG_FILE, DEPLOY_CONFIG_FILE, PACKAGE_LOCK_FILE } = require('../../lib/defaults')
const ora = require('ora')
const libConfig = require('@adobe/aio-cli-lib-app-config')
class InstallCommand extends BaseCommand {
async run () {
const { args, flags } = await this.parse(InstallCommand)
aioLogger.debug(`flags: ${JSON.stringify(flags, null, 2)}`)
aioLogger.debug(`args: ${JSON.stringify(args, null, 2)}`)
// resolve to absolute path before any chdir
args.path = path.resolve(args.path)
aioLogger.debug(`args.path (resolved): ${args.path}`)
let outputPath = flags.output
// change the cwd if necessary
if (outputPath !== '.') {
outputPath = path.resolve(flags.output)
// TODO: confirm if dir exists for overwrite
await fs.ensureDir(outputPath)
process.chdir(outputPath)
aioLogger.debug(`changed current working directory to: ${outputPath}`)
}
try {
await this.validateZipDirectoryStructure(args.path)
await this.unzipFile(args.path, outputPath)
await this.validateAppConfig(outputPath, USER_CONFIG_FILE)
await this.validateDeployConfig(outputPath, DEPLOY_CONFIG_FILE)
const packageLockPath = path.join(outputPath, PACKAGE_LOCK_FILE)
if (fs.existsSync(packageLockPath)) {
try {
await this.npmCI(flags.verbose, flags['allow-scripts'])
} catch (npmCIError) {
// Log the npm ci failure for monitoring
aioLogger.warn(`npm ci failed: ${npmCIError.message}`)
aioLogger.debug('npm ci error details:', npmCIError)
// Fallback to npm install with a warning message
this.warn('npm ci failed (lockfile out of sync). Falling back to npm install.')
await this.npmInstall(flags.verbose, flags['allow-scripts'])
}
} else {
this.warn('No lockfile found, running standard npm install. It is recommended that you include a lockfile with your app bundle.')
await this.npmInstall(flags.verbose, flags['allow-scripts'])
}
if (flags.tests) {
await this.runTests()
}
this.spinner.succeed('Install done.')
} catch (e) {
this.spinner.fail(e.message)
this.error(flags.verbose ? e : e.message)
}
}
get spinner () {
if (!this._spinner) {
this._spinner = ora()
}
return this._spinner
}
diffArray (expected, actual) {
const _expected = expected ?? []
const _actual = actual ?? []
return _expected.filter(item => !_actual.includes(item))
}
async validateZipDirectoryStructure (zipFilePath) {
aioLogger.debug(`validateZipDirectoryStructure: ${zipFilePath}`)
const expectedFiles = [USER_CONFIG_FILE, DEPLOY_CONFIG_FILE, 'package.json']
const foundFiles = []
this.spinner.start(`Validating integrity of app package at ${zipFilePath}...`)
const zip = fs.createReadStream(zipFilePath).pipe(unzipper.Parse({ forceStream: true }))
for await (const entry of zip) {
const fileName = entry.path
if (expectedFiles.includes(fileName)) {
foundFiles.push(fileName)
}
entry.autodrain()
}
const diff = this.diffArray(expectedFiles, foundFiles)
if (diff.length > 0) {
throw new Error(`The app package ${zipFilePath} is missing these files: ${JSON.stringify(diff, null, 2)}`)
}
this.spinner.succeed(`Validated integrity of app package at ${zipFilePath}`)
}
async unzipFile (zipFilePath, destFolderPath) {
aioLogger.debug(`unzipFile: ${zipFilePath} to be extracted to ${destFolderPath}`)
this.spinner.start(`Extracting app package to ${destFolderPath}...`)
return unzipper.Open.file(zipFilePath)
.then((d) => d.extract({ path: destFolderPath }))
.then(() => this.spinner.succeed(`Extracted app package to ${destFolderPath}`))
}
async validateAppConfig (outputPath, configFileName, configFilePath = path.join(outputPath, configFileName)) {
this.spinner.start(`Validating ${configFileName}...`)
aioLogger.debug(`validateConfig: ${configFileName} at ${configFilePath}`)
// first coalesce the app config (resolving $include files), then validate it
const config = (await libConfig.coalesce(configFilePath)).config
await libConfig.validate(config, { throws: true }) // throws on error
this.spinner.succeed(`Validated ${configFileName}`)
}
async validateDeployConfig (outputPath, configFileName, configFilePath = path.join(outputPath, configFileName)) {
this.spinner.start(`Validating ${configFileName}...`)
aioLogger.debug(`validateConfig: ${configFileName} at ${configFilePath}`)
const configFileJson = jsYaml.load(fs.readFileSync(configFilePath).toString())
const { valid, errors } = validateJsonWithSchema(configFileJson, configFileName)
if (!valid) {
throw new Error(`Missing or invalid keys in ${configFileName}: ${JSON.stringify(errors, null, 2)}`)
} else {
this.spinner.succeed(`Validated ${configFileName}`)
}
}
async npmInstall (isVerbose = false, allowScripts = true) {
const ignoreScripts = allowScripts ? undefined : '--ignore-scripts'
this.spinner.start('Running npm install...')
const stdio = isVerbose ? 'inherit' : 'ignore'
return execa('npm', ['install', ignoreScripts], { stdio })
.then(() => {
this.spinner.succeed('Ran npm install')
})
}
async npmCI (isVerbose = false, allowScripts = true) {
const ignoreScripts = allowScripts ? undefined : '--ignore-scripts'
this.spinner.start('Running npm ci...')
const stdio = isVerbose ? 'inherit' : 'ignore'
return execa('npm', ['ci', ignoreScripts], { stdio })
.then(() => {
this.spinner.succeed('Ran npm ci')
})
}
async runTests (isVerbose) {
this.spinner.start('Running app tests...')
return this.config.runCommand('app:test').then((result) => {
if (result === 0) { // success
this.spinner.succeed('App tests passed')
} else {
throw new Error('App tests failed')
}
})
}
}
InstallCommand.description = `This command will support installing apps packaged by '<%= config.bin %> app pack'.
`
InstallCommand.flags = {
...BaseCommand.flags,
'allow-scripts': Flags.boolean({
description: 'Allow post and preinstall scripts during npm install/npm ci',
default: true,
allowNo: true
}),
output: Flags.string({
description: 'The packaged app output folder path',
char: 'o',
default: '.'
}),
tests: Flags.boolean({
description: 'Run packaged app unit tests (e.g. aio app:test)',
default: true,
allowNo: true
})
}
InstallCommand.args =
{
path: Args.string({
description: 'Path to the app package to install',
required: true
})
}
module.exports = InstallCommand