-
-
Notifications
You must be signed in to change notification settings - Fork 959
/
Copy pathindex.ts
363 lines (331 loc) · 12.2 KB
/
index.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
'use strict'
import commands from '../commands'
import { ConfigurationUpdateTarget } from '../configuration/types'
import { createLogger } from '../logger'
import type { OutputChannel } from '../types'
import { concurrent } from '../util'
import { distinct, isFalsyOrEmpty } from '../util/array'
import { dataHome, VERSION } from '../util/constants'
import { isUrl } from '../util/is'
import { fs, path, which } from '../util/node'
import { executable } from '../util/processes'
import { Event } from '../util/protocol'
import window from '../window'
import workspace from '../workspace'
import { IInstaller, Installer } from './installer'
import { API, Extension, ExtensionInfo, ExtensionItem, ExtensionManager, ExtensionState, ExtensionToLoad } from './manager'
import { checkExtensionRoot, ExtensionStat, loadExtensionJson, loadGlobalJsonAsync } from './stat'
import { InstallBuffer, InstallChannel, InstallUI } from './ui'
const logger = createLogger('extensions-index')
export interface PropertyScheme {
type: string
default: any
description: string
enum?: string[]
items?: any
[key: string]: any
}
const EXTENSIONS_FOLDER = path.join(dataHome, 'extensions')
// global local file native
export class Extensions {
public readonly manager: ExtensionManager
public readonly states: ExtensionStat
public modulesFolder = path.join(EXTENSIONS_FOLDER, 'node_modules')
private globalPromise: Promise<ExtensionToLoad[]>
constructor() {
checkExtensionRoot(EXTENSIONS_FOLDER)
this.states = new ExtensionStat(EXTENSIONS_FOLDER)
this.manager = new ExtensionManager(this.states, EXTENSIONS_FOLDER)
commands.register({
id: 'extensions.forceUpdateAll',
execute: async () => {
let arr = await this.manager.cleanExtensions()
logger.info(`Force update extensions: ${arr}`)
await this.installExtensions(arr)
}
}, false, 'remove all global extensions and install them')
this.globalPromise = this.globalExtensions()
commands.register({
id: 'extensions.toggleAutoUpdate',
execute: async () => {
let config = workspace.getConfiguration('coc.preferences', null)
let interval = config.get<string>('extensionUpdateCheck', 'daily')
let target = ConfigurationUpdateTarget.Global
if (interval == 'never') {
await config.update('extensionUpdateCheck', 'daily', target)
void window.showInformationMessage('Extension auto update enabled.')
} else {
await config.update('extensionUpdateCheck', 'never', target)
void window.showInformationMessage('Extension auto update disabled.')
}
}
}, false, 'toggle auto update of extensions.')
}
public async init(runtimepath: string): Promise<void> {
if (process.env.COC_NO_PLUGINS == '1') return
let stats = await this.globalPromise
this.manager.registerExtensions(stats)
let localStats = this.runtimeExtensionStats(runtimepath)
this.manager.registerExtensions(localStats)
void this.manager.loadFileExtensions()
}
public async activateExtensions(): Promise<void> {
await this.manager.activateExtensions()
if (process.env.COC_NO_PLUGINS == '1') return
let names = this.states.filterGlobalExtensions(workspace.env.globalExtensions)
void this.installExtensions(names)
// check extensions need watch & install
let config = workspace.initialConfiguration.get('coc.preferences') as any
let interval = config.extensionUpdateCheck
let silent = config.silentAutoupdate
if (this.states.shouldUpdate(interval)) {
this.outputChannel.appendLine('Start auto update...')
this.updateExtensions(silent).catch(e => {
this.outputChannel.appendLine(`Error on updateExtensions ${e}`)
})
}
}
public get onDidLoadExtension(): Event<Extension<API>> {
return this.manager.onDidLoadExtension
}
public get onDidActiveExtension(): Event<Extension<API>> {
return this.manager.onDidActiveExtension
}
public get onDidUnloadExtension(): Event<string> {
return this.manager.onDidUnloadExtension
}
private get outputChannel(): OutputChannel {
return window.createOutputChannel('extensions')
}
/**
* Get all loaded extensions.
*/
public get all(): Extension<API>[] {
return this.manager.all
}
public has(id: string): boolean {
return this.manager.has(id)
}
public getExtension(id: string): ExtensionItem | undefined {
return this.manager.getExtension(id)
}
public getExtensionById(extensionId: string): Extension<API> | undefined {
let item = this.manager.getExtension(extensionId)
return item ? item.extension : undefined
}
/**
* @deprecated Used by old version coc-json.
*/
public get schemes(): { [key: string]: PropertyScheme } {
return {}
}
/**
* @deprecated Used by old version coc-json.
*/
public addSchemeProperty(key: string, def: PropertyScheme): void {
// workspace.configurations.extendsDefaults({ [key]: def.default }, id)
}
/**
* @public Get state of extension
*/
public getExtensionState(id: string): ExtensionState {
return this.manager.getExtensionState(id)
}
public isActivated(id: string): boolean {
let item = this.manager.getExtension(id)
return item != null && item.extension.isActive
}
public async call(id: string, method: string, args: any[]): Promise<any> {
return await this.manager.call(id, method, args)
}
public get npm(): string {
let npm = workspace.initialConfiguration.get<string>('npm.binPath')
npm = workspace.expand(npm)
for (let exe of [npm, 'npm']) {
if (executable(exe)) return which.sync(exe)
}
void window.showErrorMessage(`Can't find ${npm} or npm in your $PATH`)
return null
}
private createInstallerUI(isUpdate: boolean, silent: boolean): InstallUI {
return silent ? new InstallChannel(isUpdate, this.outputChannel) : new InstallBuffer(isUpdate)
}
public createInstaller(npm: string, def: string): IInstaller {
return new Installer(this.modulesFolder, npm, def)
}
/**
* Install extensions, can be called without initialize.
*/
public async installExtensions(list: string[]): Promise<void> {
if (isFalsyOrEmpty(list) || !this.npm) return
let { npm } = this
list = distinct(list)
let installBuffer = this.createInstallerUI(false, false)
await Promise.resolve(installBuffer.start(list))
let fn = async (key: string): Promise<void> => {
try {
installBuffer.startProgress(key)
let installer = this.createInstaller(npm, key)
installer.on('message', (msg, isProgress) => {
installBuffer.addMessage(key, msg, isProgress)
})
let result = await installer.install()
installBuffer.finishProgress(key, true)
this.states.addExtension(result.name, result.url ? result.url : `>=${result.version}`)
let ms = key.match(/@[\d.]+$/)
if (ms != null) this.states.setLocked(result.name, true)
await this.manager.loadExtension(result.folder)
} catch (err: any) {
installBuffer.addMessage(key, err.message)
installBuffer.finishProgress(key, false)
void window.showErrorMessage(`Error on install ${key}: ${err}`)
logger.error(`Error on install ${key}`, err)
}
}
await concurrent(list, fn)
}
/**
* Update global extensions
*/
public async updateExtensions(silent = false): Promise<void> {
let { npm } = this
if (!npm) return
let stats = this.globalExtensionStats()
stats = stats.filter(s => {
if (s.isLocked || s.state === 'disabled') {
this.outputChannel.appendLine(`Skipped update for ${s.isLocked ? 'locked' : 'disabled'} extension "${s.id}"`)
return false
}
return true
})
this.states.setLastUpdate()
this.cleanModulesFolder()
let installBuffer = this.createInstallerUI(true, silent)
await Promise.resolve(installBuffer.start(stats.map(o => o.id)))
let fn = async (stat: ExtensionInfo): Promise<void> => {
let { id } = stat
try {
installBuffer.startProgress(id)
let url = stat.exotic ? stat.uri : null
let installer = this.createInstaller(npm, id)
installer.on('message', (msg, isProgress) => {
installBuffer.addMessage(id, msg, isProgress)
})
let directory = await installer.update(url)
installBuffer.finishProgress(id, true)
if (directory) await this.manager.loadExtension(directory)
} catch (err: any) {
installBuffer.addMessage(id, err.message)
installBuffer.finishProgress(id, false)
void window.showErrorMessage(`Error on update ${id}: ${err}`)
logger.error(`Error on update ${id}`, err)
}
}
await concurrent(stats, fn, silent ? 1 : 3)
}
/**
* Get all extension states
*/
public async getExtensionStates(): Promise<ExtensionInfo[]> {
let runtimepath = await workspace.nvim.eval('join(globpath(&runtimepath, "", 0, 1), ",")') as string
let localStats = this.runtimeExtensionStats(runtimepath)
let globalStats = this.globalExtensionStats()
return localStats.concat(globalStats)
}
public async globalExtensions(): Promise<ExtensionToLoad[]> {
if (process.env.COC_NO_PLUGINS == '1') return []
let res: ExtensionToLoad[] = []
for (let key of this.states.activated()) {
let root = path.join(this.modulesFolder, key)
try {
let json = await loadGlobalJsonAsync(root, VERSION)
res.push({ root, isLocal: false, packageJSON: json })
} catch (err) {
logger.error(`Error on load package.json of ${key}`, err)
}
}
return res
}
public globalExtensionStats(): ExtensionInfo[] {
let dependencies = this.states.dependencies
let lockedExtensions = this.states.lockedExtensions
let infos: ExtensionInfo[] = []
Object.entries(dependencies).map(([key, val]) => {
let root = path.join(this.modulesFolder, key)
let errors: string[] = []
let obj = loadExtensionJson(root, VERSION, errors)
if (errors.length > 0) {
this.outputChannel.appendLine(`Error on load ${key} at ${root}: ${errors.join('\n')}`)
return
}
obj.name = key
infos.push({
id: key,
root,
isLocal: false,
version: obj.version,
description: obj.description ?? '',
isLocked: lockedExtensions.includes(key),
exotic: /^https?:/.test(val),
uri: toUrl(val),
state: this.getExtensionState(key),
packageJSON: obj
})
})
logger.debug('globalExtensionStats:', infos.length)
return infos
}
public runtimeExtensionStats(runtimepath: string): ExtensionInfo[] {
let lockedExtensions = this.states.lockedExtensions
let paths = runtimepath.split(',')
let infos: ExtensionInfo[] = []
let localIds: Set<string> = new Set()
paths.map(root => {
let errors: string[] = []
let obj = loadExtensionJson(root, workspace.version, errors)
if (errors.length > 0) return
let { name } = obj
if (!name || this.states.hasExtension(name) || localIds.has(name)) return
this.states.addLocalExtension(name, root)
localIds.add(name)
infos.push(({
id: obj.name,
isLocal: true,
isLocked: lockedExtensions.includes(name),
version: obj.version,
description: obj.description ?? '',
exotic: false,
root,
state: this.getExtensionState(obj.name),
packageJSON: Object.freeze(obj)
}))
})
return infos
}
/**
* Remove unnecessary folders in node_modules
*/
public cleanModulesFolder(): void {
let globalIds = this.states.globalIds
let folders = globalIds.map(s => s.replace(/\/.*$/, ''))
if (!fs.existsSync(this.modulesFolder)) return
let files = fs.readdirSync(this.modulesFolder)
for (let file of files) {
if (folders.includes(file)) continue
let p = path.join(this.modulesFolder, file)
let stat = fs.lstatSync(p)
if (stat.isSymbolicLink()) {
fs.unlinkSync(p)
} else if (stat.isDirectory()) {
fs.rmSync(p, { recursive: true, force: true })
}
}
}
public dispose(): void {
this.manager.dispose()
}
}
export function toUrl(val: string): string {
return isUrl(val) ? val.replace(/\.git(#master|#main)?$/, '') : ''
}
export default new Extensions()