any-rule/src/loader.ts

46 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-01-03 00:15:54 +08:00
import axios from 'axios';
import { IRule } from './interface';
2020-01-05 20:11:57 +08:00
import { writeFileSync, readFileSync } from 'fs';
import { join as pathJoin } from 'path';
2020-01-03 00:15:54 +08:00
2020-01-05 20:11:57 +08:00
async function loadRulesFromFile(path: string): Promise<IRule[] | null> {
2020-01-03 00:15:54 +08:00
try {
2020-01-05 20:11:57 +08:00
const json = readFileSync(path);
2020-01-03 00:15:54 +08:00
return JSON.parse(json.toString()) as IRule[];
} catch(e) {
return null;
}
}
async function loadRulesFromWeb(): Promise<IRule[]> {
const dataSources = [
'https://raw.githubusercontent.com/any86/any-rule/feature/vscode-refactor/rules.json'
];
let rules: IRule[] = [];
for (const source of dataSources) {
try {
const response = await axios.get(source);
const body = response.data;
rules = body as IRule[];
} catch(e) {
console.log(e);
continue;
}
}
return rules;
}
export async function loadRules (extensionPath: string, force: boolean = false): Promise<IRule[]> {
2020-01-05 20:11:57 +08:00
const rulePath = pathJoin(extensionPath, 'rules.json');
2020-01-03 00:15:54 +08:00
let rules: IRule[] | null = null;
if (!force) {
2020-01-05 20:11:57 +08:00
rules = await loadRulesFromFile(rulePath);
2020-01-03 00:15:54 +08:00
}
if (!rules) {
rules = await loadRulesFromWeb();
2020-01-05 20:11:57 +08:00
writeFileSync(rulePath, Buffer.from(JSON.stringify(rules)));
2020-01-03 00:15:54 +08:00
}
return rules;
}