-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathbeautifier.ts
655 lines (608 loc) · 16.6 KB
/
beautifier.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import { Language } from "./language";
import { LanguageManager, LanguageQuery } from "./LanguageManager";
import { OptionsRegistry } from "./options";
import { OptionsManager, optionKeys } from "./OptionsManager";
import { InlineFlagManager } from "./InlineFlagManager";
import {
DependencyDefinition,
DependencyManager,
Badge,
} from "./DependencyManager";
import { zipObject, unique } from "./utils";
/**
New name to rename the option (key) to.
Name of an option to configure for a beautifier.
*/
export type BeautifierOptionName = string;
/**
Function to process the given options and return a final option value.
*/
export type BeautifierOptionTransformFunction = (options: OptionValues) => any;
/**
Option that transforms one or more required options into a single value.
*/
export type BeautifyOptionTransform = [
BeautifierOptionName[],
BeautifierOptionTransformFunction
];
/**
Option that transforms a single option value with the same name.
*/
export type BeautifyOptionTransformSingleFunction = (optionValue: any) => any;
/**
Option for Beautifier given the Language.
*/
export type BeautifierLanguageOption =
| boolean
| BeautifierOptionName
| BeautifyOptionTransformSingleFunction
| BeautifyOptionTransform;
/**
*/
export interface BeautifierLanguageOptionComplex {
[outOptionName: string]: BeautifierLanguageOption | undefined;
}
/**
true = supports language, enable all options
false = supports language, disable all options
complex = supports language with specific options
*/
export type BeautifierLanguageOptions =
| boolean
| BeautifierLanguageOptionComplex;
/**
Options for Beautifier.
Keys are the names of Languages.
*/
export interface BeautifierOptions {
[languageName: string]: BeautifierLanguageOptions;
}
/**
Data given to Beautifier's Beautify function.
*/
export interface BeautifierBeautifyData {
/**
Text to beautify
*/
text: string;
/**
Language of text.
*/
language: Language;
/**
Option values for given Language.
*/
options: { [outOptionName: string]: any };
/**
File path.
*/
filePath?: string;
/**
Project directory path.
*/
projectPath?: string;
/**
* Dependencies
*/
dependencies: DependencyManager;
/**
* Beautifier-specific configuration
*/
beautifierConfig?: ResolvedConfig;
}
export interface LanguageOptionValues {
[languageName: string]: OptionValues;
}
export interface OptionValues {
[optionName: string]: any;
}
/**
Data given to Unibeautify to perform beautification with.
*/
export interface BeautifyData {
/**
Text to beautify.
*/
text: string;
/**
Name of language to use for beautification.
*/
languageName?: string;
/**
File extension.
*/
fileExtension?: string;
/**
Atom editor grammar.
*/
atomGrammar?: string;
/**
Sublime Text editor syntax.
*/
sublimeSyntax?: string;
/**
* VSCode Document Selector
*/
vscodeLanguage?: string;
/**
File path.
*/
filePath?: string;
/**
Project path.
*/
projectPath?: string;
/**
Option values.
*/
options: LanguageOptionValues;
}
export type BeautifierName = string;
/**
Beautifier
*/
export interface Beautifier {
/**
Unique identifying name of the beautifier.
*/
name: BeautifierName;
/**
Supports options of the beautifier.
*/
options: BeautifierOptions;
/**
* Parsed Package.json file as JSON.
*/
// tslint:disable-next-line:no-reserved-keywords
package?: object;
/**
* Runtime dependencies of the beautifier.
*/
dependencies?: DependencyDefinition[];
/**
* Function to retrieve beautifier-specific configuration file and/or parsed value.
*/
resolveConfig?(resolveConfigData: ResolveConfigData): Promise<ResolvedConfig>;
/**
Beautify the given code with the beautifier.
*/
beautify(data: BeautifierBeautifyData): Promise<string>;
/**
* Badges to display in automatically generated documentation.
*/
badges?: Badge[];
}
export interface ResolveConfigData {
dependencies: DependencyManager;
filePath?: string;
projectPath?: string;
}
export interface ResolvedConfig {
/**
* The parsed configuration object
*/
config?: any;
/**
* The path to the config file that was found
*/
filePath?: string;
}
/**
Beautifier
*/
export class Unibeautify {
private options: OptionsRegistry = {};
private languages: Language[] = [];
private beautifiers: Beautifier[] = [];
private languageManager: LanguageManager = new LanguageManager(
this.languages
);
private optionsManager: OptionsManager = new OptionsManager(this.options);
/**
* Get loaded languages which have a loaded beautifier supporting the given option
*/
public getLanguagesSupportingOption(
optionName: BeautifierOptionName
): Language[] {
return this.supportedLanguages.filter(
language =>
this.beautifiers.findIndex(beautifier =>
this.doesBeautifierSupportOptionForLanguage({
beautifier,
language,
optionName,
})
) !== -1
);
}
/**
* Get options supported for language and all loaded beautifiers
*/
public getOptionsSupportedForLanguage(language: Language): OptionsRegistry {
return this.beautifiers.reduce(
(options, beautifier) => ({
...options,
...this.getOptionsSupportedByBeautifierForLanguage({
beautifier,
language,
}),
}),
{}
);
}
/**
* Get options supported by beautifier for a language.
*/
public getOptionsSupportedByBeautifierForLanguage({
beautifier,
language,
}: {
beautifier: Beautifier;
language: Language;
}): OptionsRegistry {
const keys: BeautifierOptionName[] = optionKeys(beautifier, language);
const allOptions = this.optionsManager.options;
return keys.reduce((options, key) => {
const option = allOptions[key];
if (!option) {
return options;
}
return {
...options,
[key]: option,
};
}, {});
}
/**
* Get all loaded languages which have at least one supporting beautifier.
*/
public get supportedLanguages(): Language[] {
return this.getLoadedLanguages().filter(language =>
Boolean(this.getBeautifierForLanguage(language))
);
}
/**
Beautify code
*/
public beautify(data: BeautifyData): Promise<string> {
const lang: Language | null = this.languageManager.getLanguage(data);
if (lang == null) {
return Promise.reject(new Error("Cannot find language."));
}
const langOptions: OptionValues = Unibeautify.getOptionsForLanguage(
lang,
data.options
);
const {
selectedBeautifiers,
missingBeautifierName,
} = this.beautifiersForLanguageAndOptions(lang, langOptions);
if (selectedBeautifiers.length === 0) {
return Promise.reject(
new Error(`Beautifiers not found for Language: ${lang.name}`)
);
}
if (missingBeautifierName) {
return Promise.reject(
new Error(`Beautifier not found: ${missingBeautifierName}`)
);
}
return this.beautifyWithBeautifiers({
beautifiers: selectedBeautifiers as Beautifier[],
fileExtension: data.fileExtension,
filePath: data.filePath,
langOptions,
language: lang,
projectPath: data.projectPath,
text: data.text,
});
}
private beautifiersForLanguageAndOptions(
lang: Language,
langOptions: OptionValues
): {
selectedBeautifiers: (Beautifier | undefined)[];
missingBeautifierName: string | undefined;
} {
const allBeautifiers: Beautifier[] = this.getBeautifiersForLanguage(lang);
const beautifierNames: string[] = langOptions.beautifiers || [];
const selectedBeautifiers: (Beautifier | undefined)[] =
beautifierNames.length > 0
? this.beautifiersWithNames(beautifierNames, allBeautifiers)
: allBeautifiers;
const missingBeautifierName:
| string
| undefined = selectedBeautifiers
.map((curr, index) => (curr ? undefined : beautifierNames[index]))
.find(curr => !!curr);
return {
missingBeautifierName,
selectedBeautifiers,
};
}
private beautifiersWithNames(
names: string[],
beautifiers: Beautifier[]
): (Beautifier | undefined)[] {
const beautifiersByName = beautifiers.reduce((index, current) => {
index[current.name] = current;
return index;
}, {} as { [beautifierName: string]: Beautifier });
return names.map(name => beautifiersByName[name]);
}
// tslint:disable:max-func-body-length
private beautifyWithBeautifiers({
beautifiers,
language,
langOptions,
fileExtension,
filePath,
projectPath,
text,
}: {
beautifiers: Beautifier[];
language: Language;
langOptions: OptionValues;
text: BeautifyData["text"];
fileExtension: BeautifyData["fileExtension"];
filePath: BeautifyData["filePath"];
projectPath: BeautifyData["projectPath"];
}): Promise<string> {
return beautifiers.reduce(
(promise: Promise<string>, beautifier: Beautifier) => {
const options: OptionValues = Unibeautify.getOptionsForBeautifier(
beautifier,
language,
langOptions
);
return promise.then(currentText => {
const beautifierOptions = langOptions[beautifier.name] || {};
const dependencyManager = new DependencyManager(
beautifier.name,
beautifier.dependencies || [],
beautifierOptions
);
return dependencyManager
.load()
.then(() => {
if (
beautifierOptions.prefer_beautifier_config &&
beautifier.resolveConfig
) {
const resolveConfigPath: string | undefined =
typeof beautifierOptions.prefer_beautifier_config === "string"
? beautifierOptions.prefer_beautifier_config
: filePath;
return beautifier.resolveConfig({
dependencies: dependencyManager,
filePath: resolveConfigPath,
projectPath,
});
}
return Promise.resolve({});
})
.then((beautifierConfig: ResolvedConfig) => {
return beautifier
.beautify({
beautifierConfig,
dependencies: dependencyManager,
filePath: filePath,
language: language,
options,
projectPath: projectPath,
text: currentText,
})
.then(newText => {
if (typeof newText !== "string") {
return Promise.reject(
new Error(
`Beautifier response type must be "string" not "${typeof newText}": ${newText}`
)
);
}
return Promise.resolve(newText);
})
.then((newText: string) =>
this.handleInlineFlags(currentText, newText)
);
});
});
},
Promise.resolve(text)
);
}
private handleInlineFlags(currentText: string, newText: string): string {
const manager = new InlineFlagManager(currentText, newText);
return manager.text;
}
/**
* @deprecated use LanguageManager
*/
public findLanguages(query: LanguageQuery): Language[] {
return this.languageManager.findLanguages(query);
}
/**
* @deprecated use LanguageManager
*/
public getLoadedLanguages(): Language[] {
return this.languageManager.getLoadedLanguages();
}
/**
* Get first loaded beautifier for given language.
*/
private getBeautifierForLanguage(language: Language): Beautifier | undefined {
return this.beautifiers.find(beautifier =>
this.doesBeautifierSupportLanguage(beautifier, language)
);
}
/**
* Find and return the appropriate Beautifiers for the given Language.
*/
public getBeautifiersForLanguage(language: Language): Beautifier[] {
return this.beautifiers.filter(beautifier =>
this.doesBeautifierSupportLanguage(beautifier, language)
);
}
private doesBeautifierSupportLanguage(
beautifier: Beautifier,
language: Language
): boolean {
return beautifier.options.hasOwnProperty(language.name);
}
/**
* Get loaded beautifiers which have a loaded languages supporting the given option
*/
public getBeautifiersSupportingOption(
optionName: BeautifierOptionName
): Beautifier[] {
return this.beautifiers.filter(
beautifier =>
this.languageManager.languages.findIndex(language =>
this.doesBeautifierSupportOptionForLanguage({
beautifier,
language,
optionName,
})
) !== -1
);
}
/**
* Determine whether beautifier supports option for a language
*/
public doesBeautifierSupportOptionForLanguage({
beautifier,
language,
optionName,
}: {
beautifier: Beautifier;
language: Language;
optionName: BeautifierOptionName;
}): boolean {
return optionKeys(beautifier, language).indexOf(optionName) !== -1;
}
/**
* Find loaded languages the given beautifier supports.
*/
public getLanguagesForBeautifier(beautifier: Beautifier): Language[] {
const { options } = beautifier;
return this.languageManager.languages.filter(lang =>
options.hasOwnProperty(lang.name)
);
}
/**
* Get a shallow copy of the options currently loaded.
*/
public get loadedOptions(): OptionsRegistry {
return this.optionsManager.loadedOptions;
}
/**
* Get a shallow copy of the beautifiers currently loaded.
*/
public get loadedBeautifiers(): Beautifier[] {
return this.beautifiers.slice();
}
/**
Extract the Language-specific option values.
*/
public static getOptionsForLanguage(
language: Language,
options: LanguageOptionValues
): OptionValues {
const { name } = language;
return options[name] || {};
}
/**
Extract the option values that the Beautifier supports, including applying transformations.
*/
public static getOptionsForBeautifier(
beautifier: Beautifier,
language: Language,
options: OptionValues
): OptionValues {
const beautifierOptions = beautifier.options[language.name];
if (typeof beautifierOptions === "boolean" && beautifierOptions === false) {
return {};
} else if (typeof beautifierOptions === "object") {
return Object.keys(beautifierOptions).reduce(
(acc: OptionValues, key: string) => {
const option = beautifierOptions[key];
if (typeof option === "string") {
return {
...acc,
[key]: options[option],
};
} else if (typeof option === "function") {
return {
...acc,
[key]: option(options[key]),
};
} else if (option === true) {
return {
...acc,
[key]: options[key],
};
} else if (option instanceof Array) {
const [fields, fn] = option;
const values = fields.map(field => options[field]);
const obj = zipObject(fields, values);
return {
...acc,
[key]: fn(obj),
};
}
// tslint:disable-next-line
console.log(
`Invalid option "${key}" with value ${JSON.stringify(option)}.`
);
return acc;
},
{} as OptionValues
);
} else {
return options;
}
}
/**
Load a Beautifier
*/
public loadBeautifier(beautifier: Beautifier): Unibeautify {
this.validateBeautifier(beautifier);
this.beautifiers.push(beautifier);
return this;
}
private validateBeautifier(beautifier: any = {}): void {
if (!beautifier.name) {
throw new Error('Beautifier is missing a "name" property.');
}
// tslint:disable-next-line:no-unused-expression
new DependencyManager(beautifier.name, beautifier.dependencies, {});
}
/**
Load multiple beautifiers.
*/
public loadBeautifiers(beautifiers: Beautifier[]): Unibeautify {
beautifiers.forEach(beautifier => this.loadBeautifier(beautifier));
return this;
}
/**
* Load a single language
*/
public loadLanguage(language: Language): Unibeautify {
this.languageManager.loadLanguage(language);
return this;
}
/**
* Load multiple languages
*/
public loadLanguages(languages: Language[]): Unibeautify {
this.languageManager.loadLanguages(languages);
return this;
}
/**
* Load multiple options
*/
public loadOptions(options: OptionsRegistry): Unibeautify {
this.optionsManager.loadOptions(options);
return this;
}
}