svelte-language-server
Version:
A language server for Svelte
82 lines • 3.22 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlobalVars = void 0;
const chokidar_1 = require("chokidar");
const fs_1 = require("fs");
const globrex_1 = __importDefault(require("globrex"));
const path_1 = require("path");
const utils_1 = require("../../utils");
const varRegex = /^\s*(--\w+.*?):\s*?([^;]*)/;
class GlobalVars {
constructor(workspaceRoot) {
this.globalVars = new Map();
this.workspaceRoot = workspaceRoot;
}
watchFiles(filesToWatch) {
if (!filesToWatch || this.watchedFiles === filesToWatch) {
return;
}
this.watchedFiles = filesToWatch;
if (this.fsWatcher) {
this.fsWatcher.close();
this.globalVars.clear();
}
const paths = new Set();
const includePatterns = new Set();
for (const root of this.workspaceRoot) {
for (const filePath of filesToWatch.split(',')) {
if (!filePath.includes('*')) {
paths.add(filePath);
continue;
}
const normalizedPath = (0, utils_1.normalizePath)((0, path_1.join)(root, filePath));
includePatterns.add(normalizedPath);
const pathSegments = normalizedPath.split('**');
let directory = pathSegments[0] || '.';
paths.add(directory);
}
}
this.fsWatcher = (0, chokidar_1.watch)(Array.from(paths), {
ignored: this.createIgnoreMatcher(includePatterns)
})
.addListener('add', (file) => this.updateForFile(file))
.addListener('change', (file) => {
this.updateForFile(file);
})
.addListener('unlink', (file) => this.globalVars.delete(file));
}
createIgnoreMatcher(includePatterns) {
if (includePatterns.size === 0) {
return undefined;
}
const regexList = Array.from(includePatterns).map((pattern) => (0, globrex_1.default)(pattern, { globstar: true }).regex);
return (path) => {
return !regexList.some((regex) => regex.test(path));
};
}
updateForFile(filename) {
// Inside a small timeout because it seems chikidar is "too fast"
// and reading the file will then return empty content
setTimeout(() => {
(0, fs_1.readFile)(filename, 'utf-8', (error, contents) => {
if (error) {
return;
}
const globalVarsForFile = contents
.split('\n')
.map((line) => line.match(varRegex))
.filter(utils_1.isNotNullOrUndefined)
.map((line) => ({ filename, name: line[1], value: line[2] }));
this.globalVars.set(filename, globalVarsForFile);
});
}, 1000);
}
getGlobalVars() {
return (0, utils_1.flatten)([...this.globalVars.values()]);
}
}
exports.GlobalVars = GlobalVars;
//# sourceMappingURL=global-vars.js.map