-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathupdate.js
More file actions
238 lines (227 loc) · 10.8 KB
/
update.js
File metadata and controls
238 lines (227 loc) · 10.8 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
228
229
230
231
232
233
234
235
236
237
238
import chalk from 'chalk'
import { eachOfSeries } from 'async'
import path from 'path'
import Project from '../Project.js'
import { createPromptTask } from '../../util/createPromptTask.js'
import { errorPrinter, packageNamePrinter, versionPrinter, existingVersionPrinter } from './print.js'
import { eachOfLimitProgress, eachOfSeriesProgress } from '../../util/promises.js'
import { update as npmUpdate } from './npm.js'
/** @typedef {import("../Target.js").default} Target */
export default async function update ({
plugins,
// whether to summarise installed plugins without modifying anything
isDryRun = false,
isInteractive = true,
cwd = process.cwd(),
logger = null
}) {
cwd = path.resolve(process.cwd(), cwd)
const project = new Project({ cwd, logger })
project.tryThrowInvalidPath()
logger?.log(chalk.cyan('update adapt dependencies...'))
const targets = await getUpdateTargets({ logger, project, plugins, isDryRun, isInteractive })
if (!targets?.length) return targets
await loadPluginData({ logger, project, targets })
await conflictResolution({ logger, targets, isInteractive })
if (isDryRun) {
await summariseDryRun({ logger, targets })
return targets
}
const updateTargetsToBeUpdated = targets.filter(target => target.isToBeInstalled)
if (updateTargetsToBeUpdated.length) {
await eachOfSeriesProgress(
updateTargetsToBeUpdated,
target => target.update(),
percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Updating plugins ${percentage / (project.isNPM ? 2 : 1)}% complete`)
)
if (project.isNPM) {
// Batch install npm plugins as it's faster
const installArgs = updateTargetsToBeUpdated
.filter(target => target.isNPMUpdate)
.map(target => `${target.packageName}`)
const outputPath = path.join(cwd, 'src')
await npmUpdate({ logger, cwd: outputPath, args: installArgs })
await eachOfSeriesProgress(
updateTargetsToBeUpdated,
target => target.postUpdate(),
percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Updating plugins ${50 + (percentage / 2)}% complete`)
)
}
logger?.log(`${chalk.bold.cyan('<info>')} Updating plugins 100% complete`)
}
await summariseUpdates({ logger, targets })
return targets
}
/**
* @param {Object} options
* @param {Project} options.project
* @param {[string]} options.plugins
*/
async function getUpdateTargets ({ project, plugins, isDryRun, isInteractive }) {
if (typeof plugins === 'string') plugins = [plugins]
if (!plugins) plugins = []
const allowedTypes = ['all', 'components', 'extensions', 'menu', 'theme']
const selectedTypes = [...new Set(plugins.filter(type => allowedTypes.includes(type)))]
const isEmpty = (!plugins.length)
const isAll = (isDryRun || isEmpty || selectedTypes.includes('all'))
const pluginNames = plugins
// remove types
.filter(arg => !allowedTypes.includes(arg))
// split name/version
.map(arg => {
const [name, version = '*'] = arg.split(/[#@]/)
return [name, version]
})
// make sure last applies
.reverse()
/** @type {[Target]} */
let targets = await project.getUpdateTargets()
for (const target of targets) {
await target.fetchProjectInfo()
}
if (!isDryRun && isEmpty && isInteractive) {
const shouldContinue = await createPromptTask({
message: chalk.reset('This command will attempt to update all installed plugins. Do you wish to continue?'),
type: 'confirm'
})
if (!shouldContinue) return
}
if (!isAll) {
const filtered = {}
for (const target of targets) {
const typeFolder = await target.getTypeFolder()
if (!typeFolder) continue
const lastSpecifiedPluginName = pluginNames.find(([name]) => target.isNameMatch(name))
const isPluginNameIncluded = Boolean(lastSpecifiedPluginName)
const isTypeIncluded = selectedTypes.includes(typeFolder)
if (!isPluginNameIncluded && !isTypeIncluded) continue
// Resolve duplicates
filtered[target.packageName] = target
// Set requested version from name
target.requestedVersion = lastSpecifiedPluginName[1] || '*'
}
targets = Object.values(filtered)
}
return targets
}
/**
* @param {Object} options
* @param {Project} options.project
* @param {[Target]} options.targets
*/
async function loadPluginData ({ logger, project, targets }) {
const frameworkVersion = project.version
await eachOfLimitProgress(
targets,
target => target.fetchSourceInfo(),
percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Getting plugin info ${percentage}% complete`)
)
logger?.log(`${chalk.bold.cyan('<info>')} Getting plugin info 100% complete`)
await eachOfLimitProgress(
targets,
target => target.findCompatibleVersion(frameworkVersion),
percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Finding compatible source versions ${percentage}% complete`)
)
logger?.log(`${chalk.bold.cyan('<info>')} Finding compatible source versions 100% complete`)
await eachOfLimitProgress(
targets,
target => target.markUpdateable(),
percentage => logger?.logProgress?.(`${chalk.bold.cyan('<info>')} Marking updateable ${percentage}% complete`)
)
logger?.log(`${chalk.bold.cyan('<info>')} Marking updateable 100% complete`)
}
/**
* @param {Object} options
* @param {[Target]} options.targets
*/
async function conflictResolution ({ logger, targets, isInteractive }) {
/** @param {Target} target */
async function checkVersion (target) {
const canApplyRequested = target.hasValidRequestVersion &&
(target.hasFrameworkCompatibleVersion
? (target.latestCompatibleSourceVersion !== target.matchedVersion)
: (target.latestSourceVersion !== target.matchedVersion))
if (!isInteractive) {
if (target.canApplyRequested) return target.markRequestedForInstallation()
return target.markSkipped()
}
const choices = [
canApplyRequested && { name: `requested version [${target.matchedVersion}]`, value: 'r' },
target.hasFrameworkCompatibleVersion
? { name: `latest compatible version [${target.latestCompatibleSourceVersion}]`, value: 'l' }
: { name: `latest version [${target.latestSourceVersion}]`, value: 'l' },
{ name: 'skip', value: 's' }
].filter(Boolean)
const result = await createPromptTask({ message: chalk.reset(target.packageName), choices, type: 'list', default: 's' })
const installRequested = (result === 'r')
const installLatest = result === 'l'
const skipped = result === 's'
if (installRequested) target.markRequestedForInstallation()
if (installLatest && target.hasFrameworkCompatibleVersion) target.markLatestCompatibleForInstallation()
if (installLatest && !target.hasFrameworkCompatibleVersion) target.markLatestForInstallation()
if (skipped) target.markSkipped()
}
function add (list, header, prompt) {
if (!list.length) return
return {
header: chalk.bold.cyan('<info> ') + header,
list,
prompt
}
}
const preFilteredPlugins = targets.filter(target => !target.isLocalSource)
const allQuestions = [
add(preFilteredPlugins.filter(target => !target.hasFrameworkCompatibleVersion), 'There is no compatible version of the following plugins:', checkVersion),
add(preFilteredPlugins.filter(target => target.hasFrameworkCompatibleVersion && !target.hasValidRequestVersion), 'The version requested is invalid, there are newer compatible versions of the following plugins:', checkVersion),
add(preFilteredPlugins.filter(target => target.hasFrameworkCompatibleVersion && target.hasValidRequestVersion && !target.isApplyLatestCompatibleVersion), 'There are newer compatible versions of the following plugins:', checkVersion)
].filter(Boolean)
if (allQuestions.length === 0) return
for (const question of allQuestions) {
logger?.log(question.header)
await eachOfSeries(question.list, question.prompt)
}
}
/**
* @param {Object} options
* @param {[Target]} options.targets
*/
function summariseDryRun ({ logger, targets }) {
const preFilteredPlugins = targets.filter(target => !target.isLocalSource)
const localSources = targets.filter(target => target.isLocalSource)
const toBeInstalled = preFilteredPlugins.filter(target => target.isToBeUpdated)
const toBeSkipped = preFilteredPlugins.filter(target => !target.isToBeUpdated || target.isSkipped)
const missing = preFilteredPlugins.filter(target => target.isMissing)
summarise(logger, localSources, packageNamePrinter, 'The following plugins were installed from a local source and cannot be updated:')
summarise(logger, toBeSkipped, packageNamePrinter, 'The following plugins will be skipped:')
summarise(logger, missing, packageNamePrinter, 'There was a problem locating the following plugins:')
summarise(logger, toBeInstalled, versionPrinter, 'The following plugins will be updated:')
}
/**
* @param {Object} options
* @param {[Target]} options.targets
*/
function summariseUpdates ({ logger, targets }) {
const preFilteredPlugins = targets.filter(target => !target.isLocalSource)
const localSources = targets.filter(target => target.isLocalSource)
const installSucceeded = preFilteredPlugins.filter(target => target.isUpdateSuccessful)
const installSkipped = preFilteredPlugins.filter(target => target.isSkipped)
const noUpdateAvailable = preFilteredPlugins.filter(target => !target.isToBeUpdated && !target.isSkipped)
const installErrored = preFilteredPlugins.filter(target => target.isUpdateFailure)
const missing = preFilteredPlugins.filter(target => target.isMissing)
const noneInstalled = (installSucceeded.length === 0)
const allInstalledSuccessfully = (installErrored.length === 0 && missing.length === 0)
const someInstalledSuccessfully = (!noneInstalled && !allInstalledSuccessfully)
summarise(logger, localSources, existingVersionPrinter, 'The following plugins were installed from a local source and cannot be updated:')
summarise(logger, installSkipped, existingVersionPrinter, 'The following plugins were skipped:')
summarise(logger, noUpdateAvailable, existingVersionPrinter, 'The following plugins had no update available:')
summarise(logger, missing, packageNamePrinter, 'There was a problem locating the following plugins:')
summarise(logger, installErrored, errorPrinter, 'The following plugins could not be updated:')
if (noneInstalled) logger?.log(chalk.cyanBright('None of the requested plugins could be updated'))
else if (allInstalledSuccessfully) summarise(logger, installSucceeded, existingVersionPrinter, 'All requested plugins were successfully updated. Summary of installation:')
else if (someInstalledSuccessfully) summarise(logger, installSucceeded, existingVersionPrinter, 'The following plugins were successfully updated:')
}
function summarise (logger, list, iterator, header) {
if (!list || !iterator || list.length === 0) return
logger?.log(chalk.cyanBright(header))
list.forEach(item => iterator(item, logger))
}