-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathantoraSupport.ts
298 lines (273 loc) · 11.9 KB
/
antoraSupport.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
import vscode, { CancellationTokenSource, FileType, Memento, Uri } from 'vscode'
import fs from 'fs'
import yaml from 'js-yaml'
import File from 'vinyl'
import * as path from 'path'
import AntoraCompletionProvider from './antoraCompletionProvider'
import { disposeAll } from '../../util/dispose'
import * as nls from 'vscode-nls'
import ContentCatalog from '@antora/content-classifier/lib/content-catalog'
const localize = nls.loadMessageBundle()
export interface AntoraResourceContext {
component: string;
version: string;
module: string;
}
export class AntoraConfig {
constructor (public fsPath: string, public config: { [key: string]: any }) {
}
}
export class AntoraDocumentContext {
private PERMITTED_FAMILIES = ['attachment', 'example', 'image', 'page', 'partial']
constructor (private antoraContext: AntoraContext, private resourceContext: AntoraResourceContext) {
}
public resolveAntoraResourceIds (id: string, defaultFamily: string): string | undefined {
const resource = this.antoraContext.contentCatalog.resolveResource(id, this.resourceContext, defaultFamily, this.PERMITTED_FAMILIES)
if (resource) {
return resource.src?.abspath
}
return undefined
}
public getComponents () {
return this.antoraContext.contentCatalog.getComponents()
}
public getImages () {
return this.antoraContext.contentCatalog.findBy({ family: 'image' })
}
}
export class AntoraContext {
constructor (public contentCatalog: ContentCatalog) {
}
public async getResource (textDocumentUri: Uri): Promise<AntoraResourceContext | undefined> {
const antoraConfig = await getAntoraConfig(textDocumentUri)
if (antoraConfig === undefined) {
return undefined
}
const contentSourceRootPath = path.dirname(antoraConfig.fsPath)
const config = antoraConfig.config
if (config.name === undefined) {
return undefined
}
const page = this.contentCatalog.getByPath({
component: config.name,
version: config.version,
path: path.relative(contentSourceRootPath, textDocumentUri.path),
})
if (page === undefined) {
return undefined
}
return page.src
}
}
export class AntoraSupportManager implements vscode.Disposable {
// eslint-disable-next-line no-use-before-define
private static instance: AntoraSupportManager
private static workspaceState: Memento
private readonly _disposables: vscode.Disposable[] = []
private constructor () {
}
public static getInstance (workspaceState: Memento) {
if (AntoraSupportManager.instance) {
AntoraSupportManager.workspaceState = workspaceState
return AntoraSupportManager.instance
}
AntoraSupportManager.instance = new AntoraSupportManager()
AntoraSupportManager.workspaceState = workspaceState
const workspaceConfiguration = vscode.workspace.getConfiguration('asciidoc', null)
// look for Antora support setting in workspace state
const isEnableAntoraSupportSettingDefined = workspaceState.get('antoraSupportSetting')
if (isEnableAntoraSupportSettingDefined === true) {
const enableAntoraSupport = workspaceConfiguration.get('antora.enableAntoraSupport')
if (enableAntoraSupport === true) {
AntoraSupportManager.instance.registerFeatures()
}
} else if (isEnableAntoraSupportSettingDefined === undefined) {
// choice has not been made
const onDidOpenAsciiDocFileAskAntoraSupport = vscode.workspace.onDidOpenTextDocument(async (textDocument) => {
if (await antoraConfigFileExists(textDocument.uri)) {
const yesAnswer = localize('antora.activateSupport.yes', 'Yes')
const noAnswer = localize('antora.activateSupport.no', 'No, thanks')
const answer = await vscode.window.showInformationMessage(
localize('antora.activateSupport.message', 'We detect that you are working with Antora. Do you want to active Antora support?'),
yesAnswer,
noAnswer
)
await workspaceState.update('antoraSupportSetting', true)
const enableAntoraSupport = answer === yesAnswer ? true : (answer === noAnswer ? false : undefined)
await workspaceConfiguration.update('antora.enableAntoraSupport', enableAntoraSupport)
if (enableAntoraSupport) {
AntoraSupportManager.instance.registerFeatures()
}
// do not ask again to avoid bothering users
onDidOpenAsciiDocFileAskAntoraSupport.dispose()
}
})
AntoraSupportManager.instance._disposables.push(onDidOpenAsciiDocFileAskAntoraSupport)
}
}
public static async isEnabled (workspaceState: Memento): Promise<Boolean> {
return (await AntoraSupportManager.getInstance(workspaceState)).isEnabled()
}
public async getAttributes (textDocumentUri: Uri): Promise<{ [key: string]: string }> {
const antoraEnabled = this.isEnabled()
if (antoraEnabled) {
return getAttributes(textDocumentUri)
}
return {}
}
public isEnabled (): Boolean {
const workspaceConfiguration = vscode.workspace.getConfiguration('asciidoc', null)
// look for Antora support setting in workspace state
const isEnableAntoraSupportSettingDefined = AntoraSupportManager.workspaceState.get('antoraSupportSetting')
if (isEnableAntoraSupportSettingDefined === true) {
const enableAntoraSupport = workspaceConfiguration.get('antora.enableAntoraSupport')
if (enableAntoraSupport === true) {
return true
}
}
// choice has not been made or Antora is explicitly disabled
return false
}
public async getAntoraDocumentContext (textDocumentUri: Uri): Promise<AntoraDocumentContext | undefined> {
const antoraEnabled = this.isEnabled()
if (antoraEnabled) {
return getAntoraDocumentContext(textDocumentUri, AntoraSupportManager.workspaceState)
}
return undefined
}
private registerFeatures (): void {
const attributesCompletionProvider = vscode.languages.registerCompletionItemProvider({
language: 'asciidoc',
scheme: 'file',
},
new AntoraCompletionProvider(),
'{'
)
this._disposables.push(attributesCompletionProvider)
}
public dispose (): void {
disposeAll(this._disposables)
}
}
export async function findAntoraConfigFile (textDocumentUri: Uri): Promise<Uri | undefined> {
const pathToAsciidocFile = textDocumentUri.toString()
const cancellationToken = new CancellationTokenSource()
cancellationToken.token.onCancellationRequested((e) => {
console.log('Cancellation requested, cause: ' + e)
})
const antoraConfigs = await vscode.workspace.findFiles('**/antora.yml', '/node_modules/', 100, cancellationToken.token)
// check for Antora configuration
for (const antoraConfig of antoraConfigs) {
const modulesUri = antoraConfig.with({ path: path.join(path.dirname(antoraConfig.path), 'modules') })
if (pathToAsciidocFile.startsWith(modulesUri.toString()) && pathToAsciidocFile.slice(modulesUri.toString().length).match(/^\/[^/]+\/pages\/.*/)) {
console.log(`Found an Antora configuration file at ${antoraConfig.toString()} for the AsciiDoc document ${pathToAsciidocFile}`)
return antoraConfig
}
}
console.log(`Unable to find an applicable Antora configuration file in [${antoraConfigs.join(', ')}] for the AsciiDoc document ${pathToAsciidocFile}`)
return undefined
}
export async function antoraConfigFileExists (textDocumentUri: Uri): Promise<boolean> {
return await findAntoraConfigFile(textDocumentUri) !== undefined
}
export async function getAntoraConfigs (): Promise<AntoraConfig[]> {
const cancellationToken = new CancellationTokenSource()
cancellationToken.token.onCancellationRequested((e) => {
console.log('Cancellation requested, cause: ' + e)
})
const antoraConfigUris = await vscode.workspace.findFiles('**/antora.yml', '/node_modules/', 100, cancellationToken.token)
// check for Antora configuration
const antoraConfigs = await Promise.all(antoraConfigUris.map(async (antoraConfigUri) => {
let config = {}
const parentPath = antoraConfigUri.path.slice(0, antoraConfigUri.path.lastIndexOf('/'))
const parentDirectoryStat = await vscode.workspace.fs.stat(antoraConfigUri.with({ path: parentPath }))
if (parentDirectoryStat.type === (FileType.Directory | FileType.SymbolicLink) || parentDirectoryStat.type === FileType.SymbolicLink) {
// ignore!
return undefined
}
try {
config = yaml.load(await vscode.workspace.fs.readFile(antoraConfigUri)) || {}
} catch (err) {
console.log(`Unable to parse ${antoraConfigUri}, cause:` + err.toString())
}
return new AntoraConfig(antoraConfigUri.fsPath, config)
}))
return antoraConfigs.filter((c) => c) // filter undefined
}
export async function getAntoraConfig (textDocumentUri: Uri): Promise<AntoraConfig | undefined> {
const antoraConfigUri = await findAntoraConfigFile(textDocumentUri)
if (antoraConfigUri === undefined) {
return undefined
}
const antoraConfigPath = antoraConfigUri.fsPath
let config = {}
try {
config = yaml.load(fs.readFileSync(antoraConfigPath, 'utf8')) || {}
} catch (err) {
console.log(`Unable to parse ${antoraConfigPath}, cause:` + err.toString())
}
return new AntoraConfig(antoraConfigPath, config)
}
export async function getAttributes (textDocumentUri: Uri): Promise<{ [key: string]: string }> {
const antoraConfig = await getAntoraConfig(textDocumentUri)
if (antoraConfig === undefined) {
return {}
}
return antoraConfig.config.asciidoc?.attributes || {}
}
export async function getAntoraDocumentContext (textDocumentUri: Uri, workspaceState: Memento): Promise<AntoraDocumentContext | undefined> {
const antoraSupportManager = await AntoraSupportManager.getInstance(workspaceState)
if (!antoraSupportManager.isEnabled()) {
return undefined
}
try {
const antoraConfigs = await getAntoraConfigs()
const contentAggregate: { name: string, version: string, files: any[] }[] = (await Promise.all(antoraConfigs
.filter((antoraConfig) => antoraConfig.config !== undefined && 'name' in antoraConfig.config && 'version' in antoraConfig.config)
.map(async (antoraConfig) => {
const contentSourceRootPath = path.dirname(antoraConfig.fsPath)
const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(antoraConfig.fsPath))
const workspaceRelative = path.relative(workspaceFolder.uri.fsPath, contentSourceRootPath)
const files = await Promise.all((await vscode.workspace.findFiles(workspaceRelative + '/modules/**/*')).map(async (file) => {
return new File({
base: contentSourceRootPath,
path: path.relative(contentSourceRootPath, file.path),
contents: Buffer.from((await vscode.workspace.fs.readFile(Uri.file(file.fsPath)))),
extname: path.extname(file.path),
stem: path.basename(file.path, path.extname(file.path)),
src: {
abspath: file.path,
basename: path.basename(file.path),
editUrl: '',
extname: path.extname(file.path),
fileUrl: file.fsPath,
path: file.path,
stem: path.basename(file.path, path.extname(file.path)),
},
})
}))
return {
name: antoraConfig.config.name,
version: antoraConfig.config.version,
...antoraConfig.config,
files,
}
})))
let classifyContent = await import('@antora/content-classifier')
if ('default' in classifyContent) {
classifyContent = classifyContent.default // default export
}
const contentCatalog = await classifyContent({
site: {},
}, contentAggregate)
const antoraContext = new AntoraContext(contentCatalog)
const antoraResourceContext = await antoraContext.getResource(textDocumentUri)
if (antoraResourceContext === undefined) {
return undefined
}
return new AntoraDocumentContext(antoraContext, antoraResourceContext)
} catch (err) {
console.error(`Unable to get Antora context for ${textDocumentUri}`, err)
return undefined
}
}