Global/local settings

This commit is contained in:
Elio Struyf
2021-09-17 20:26:52 +02:00
parent 08fcf7cf15
commit 001a49b34e
13 changed files with 132 additions and 154 deletions
+7 -11
View File
@@ -109,7 +109,6 @@ export class Article {
* Sets the article lastmod date
*/
public static async setLastModifiedDate() {
const config = Settings.getConfig();
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
@@ -121,7 +120,7 @@ export class Article {
}
const cloneArticle = Object.assign({}, article);
const dateField = config.get(SETTING_MODIFIED_FIELD) as string || DefaultFields.LastModified;
const dateField = Settings.get(SETTING_MODIFIED_FIELD) as string || DefaultFields.LastModified;
try {
cloneArticle.data[dateField] = Article.formatDate(new Date());
@@ -135,11 +134,10 @@ export class Article {
* Generate the slug based on the article title
*/
public static async generateSlug() {
const config = Settings.getConfig();
const prefix = config.get(SETTING_SLUG_PREFIX) as string;
const suffix = config.get(SETTING_SLUG_SUFFIX) as string;
const updateFileName = config.get(SETTING_SLUG_UPDATE_FILE_NAME) as string;
const filePrefix = config.get<string>(SETTING_TEMPLATES_PREFIX);
const prefix = Settings.get(SETTING_SLUG_PREFIX) as string;
const suffix = Settings.get(SETTING_SLUG_SUFFIX) as string;
const updateFileName = Settings.get(SETTING_SLUG_UPDATE_FILE_NAME) as string;
const filePrefix = Settings.get<string>(SETTING_TEMPLATES_PREFIX);
const editor = vscode.window.activeTextEditor;
if (!editor) {
@@ -217,8 +215,7 @@ export class Article {
const editor = vscode.window.activeTextEditor;
if (txtChanges.length > 0 && editor && ArticleHelper.isMarkdownFile()) {
const config = Settings.getConfig();
const autoUpdate = config.get(SETTING_AUTO_UPDATE_DATE);
const autoUpdate = Settings.get(SETTING_AUTO_UPDATE_DATE);
if (autoUpdate) {
const article = ArticleHelper.getFrontMatter(editor);
@@ -241,8 +238,7 @@ export class Article {
* Format the date to the defined format
*/
public static formatDate(dateValue: Date) {
const config = Settings.getConfig();
const dateFormat = config.get(SETTING_DATE_FORMAT) as string;
const dateFormat = Settings.get(SETTING_DATE_FORMAT) as string;
if (dateFormat && typeof dateFormat === "string") {
return format(dateValue, dateFormat);
+10 -21
View File
@@ -40,8 +40,7 @@ export class Dashboard {
* Init the dashboard
*/
public static async init() {
const config = SettingsHelper.getConfig();
const openOnStartup = config.get(SETTINGS_DASHBOARD_OPENONSTART);
const openOnStartup = SettingsHelper.get(SETTINGS_DASHBOARD_OPENONSTART);
if (openOnStartup) {
Dashboard.open();
}
@@ -116,16 +115,10 @@ export class Dashboard {
panel.getMediaSelection();
});
workspace.onDidChangeConfiguration(() => {
SettingsHelper.onConfigChange((global?: any) => {
Dashboard.getSettings();
});
workspace.onDidChangeTextDocument((e) => {
if (e.document.fileName === "frontmatter.json") {
console.log("frontmatter.json changed");
}
});
Dashboard.webview.webview.onDidReceiveMessage(async (msg) => {
switch(msg.command) {
case DashboardMessage.getViewType:
@@ -195,7 +188,6 @@ export class Dashboard {
*/
private static async getSettings() {
const ext = Extension.getInstance();
const config = SettingsHelper.getConfig();
const wsFolder = Folders.getWorkspaceFolder();
Dashboard.postWebviewMessage({
@@ -203,12 +195,12 @@ export class Dashboard {
data: {
beta: ext.isBetaVersion(),
wsFolder: wsFolder ? wsFolder.fsPath : '',
staticFolder: config.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS),
staticFolder: SettingsHelper.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS),
folders: Folders.get(),
initialized: await Template.isInitialized(),
tags: SettingsHelper.getTaxonomy(TaxonomyType.Tag),
categories: SettingsHelper.getTaxonomy(TaxonomyType.Category),
openOnStart: config.get(SETTINGS_DASHBOARD_OPENONSTART),
openOnStart: SettingsHelper.get(SETTINGS_DASHBOARD_OPENONSTART),
versionInfo: ext.getVersion(),
pageViewType: await ext.getState<ViewType | undefined>(EXTENSION_STATE_PAGES_VIEW)
} as Settings
@@ -219,7 +211,7 @@ export class Dashboard {
* Update a setting from the dashboard
*/
private static async updateSetting(data: { name: string, value: any }) {
await SettingsHelper.updateSetting(data.name, data.value);
await SettingsHelper.update(data.name, data.value);
Dashboard.getSettings();
}
@@ -228,8 +220,7 @@ export class Dashboard {
*/
private static async getMedia(page: number = 0, folder: string = '') {
const wsFolder = Folders.getWorkspaceFolder();
const config = SettingsHelper.getConfig();
const staticFolder = config.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS);
const staticFolder = SettingsHelper.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS);
if (Dashboard.media.length === 0) {
const contentFolder = Folders.get();
@@ -313,12 +304,11 @@ export class Dashboard {
* Retrieve all the markdown pages
*/
private static async getPages() {
const config = SettingsHelper.getConfig();
const wsFolder = Folders.getWorkspaceFolder();
const descriptionField = config.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description;
const dateField = config.get(SETTING_DATE_FIELD) as string || DefaultFields.PublishingDate;
const staticFolder = config.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS);
const descriptionField = SettingsHelper.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description;
const dateField = SettingsHelper.get(SETTING_DATE_FIELD) as string || DefaultFields.PublishingDate;
const staticFolder = SettingsHelper.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS);
const folderInfo = await Folders.getInfo();
const pages: Page[] = [];
@@ -404,8 +394,7 @@ export class Dashboard {
private static async saveFile({fileName, contents, folder}: { fileName: string; contents: string; folder: string | null }) {
if (fileName && contents) {
const wsFolder = Folders.getWorkspaceFolder();
const config = SettingsHelper.getConfig();
const staticFolder = config.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS);
const staticFolder = SettingsHelper.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS);
const wsPath = wsFolder ? wsFolder.fsPath : "";
let absFolderPath = join(wsPath, staticFolder || "", folder || "");
+2 -4
View File
@@ -197,9 +197,8 @@ export class Folders {
* @returns
*/
public static get(): ContentFolder[] {
const config = Settings.getConfig();
const wsFolder = Folders.getWorkspaceFolder();
const folders: ContentFolder[] = config.get(SETTINGS_CONTENT_PAGE_FOLDERS) as ContentFolder[];
const folders: ContentFolder[] = Settings.get(SETTINGS_CONTENT_PAGE_FOLDERS) as ContentFolder[];
return folders.map(folder => ({
title: folder.title,
@@ -212,9 +211,8 @@ export class Folders {
* @param folders
*/
private static async update(folders: ContentFolder[]) {
const config = Settings.getConfig();
const wsFolder = Folders.getWorkspaceFolder();
await config.update(SETTINGS_CONTENT_PAGE_FOLDERS, folders.map(folder => ({ title: folder.title, path: Folders.relWsFolder(folder, wsFolder) })));
await Settings.update(SETTINGS_CONTENT_PAGE_FOLDERS, folders.map(folder => ({ title: folder.title, path: Folders.relWsFolder(folder, wsFolder) })));
}
/**
+2 -4
View File
@@ -124,10 +124,8 @@ export class Preview {
* Retrieve all settings related to the preview command
*/
public static getSettings(): PreviewSettings {
const config = Settings.getConfig();
const host = config.get<string>(SETTING_PREVIEW_HOST);
const pathname = config.get<string>(SETTING_PREVIEW_PATHNAME);
const host = Settings.get<string>(SETTING_PREVIEW_HOST);
const pathname = Settings.get<string>(SETTING_PREVIEW_PATHNAME);
return {
host,
+7 -10
View File
@@ -22,9 +22,8 @@ export class Settings {
});
if (newOption) {
const config = SettingsHelper.getConfig();
const configSetting = type === TaxonomyType.Tag ? SETTING_TAXONOMY_TAGS : SETTING_TAXONOMY_CATEGORIES;
let options = config.get(configSetting) as string[];
let options = SettingsHelper.get(configSetting) as string[];
if (!options) {
options = [];
}
@@ -35,7 +34,7 @@ export class Settings {
}
options.push(newOption);
await SettingsHelper.update(type, options);
await SettingsHelper.updateTaxonomy(type, options);
// Ask if the new term needs to be added to the page
const addToPage = await vscode.window.showQuickPick(["yes", "no"], { canPickMany: false, placeHolder: `Do you want to add the new ${type === TaxonomyType.Tag ? "tag" : "category"} to the page?` });
@@ -72,8 +71,6 @@ export class Settings {
* Export the tags/categories front matter to the user settings
*/
public static async export() {
const config = SettingsHelper.getConfig();
// Retrieve all the Markdown files
const allMdFiles = await FilesHelper.getMdFiles();
if (!allMdFiles) {
@@ -128,22 +125,22 @@ export class Settings {
}
// Retrieve the currently known tags, and add the new ones
let crntTags: string[] = config.get(SETTING_TAXONOMY_TAGS) as string[];
let crntTags: string[] = SettingsHelper.get(SETTING_TAXONOMY_TAGS) as string[];
if (!crntTags) { crntTags = []; }
crntTags = [...crntTags, ...tags];
// Update the tags and filter out the duplicates
crntTags = [...new Set(crntTags)];
crntTags = crntTags.sort().filter(t => !!t);
await config.update(SETTING_TAXONOMY_TAGS, crntTags);
await SettingsHelper.update(SETTING_TAXONOMY_TAGS, crntTags);
// Retrieve the currently known tags, and add the new ones
let crntCategories: string[] = config.get(SETTING_TAXONOMY_CATEGORIES) as string[];
let crntCategories: string[] = SettingsHelper.get(SETTING_TAXONOMY_CATEGORIES) as string[];
if (!crntCategories) { crntCategories = []; }
crntCategories = [...crntCategories, ...categories];
// Update the categories and filter out the duplicates
crntCategories = [...new Set(crntCategories)];
crntCategories = crntCategories.sort().filter(c => !!c);
await config.update(SETTING_TAXONOMY_CATEGORIES, crntCategories);
await SettingsHelper.update(SETTING_TAXONOMY_CATEGORIES, crntCategories);
// Done
Notifications.info(`Export completed. Tags: ${crntTags.length} - Categories: ${crntCategories.length}.`);
@@ -269,7 +266,7 @@ export class Settings {
// Remove the selected option
options = options.filter(o => o !== selectedOption);
}
await SettingsHelper.update(type, options);
await SettingsHelper.updateTaxonomy(type, options);
Notifications.info(`${newOptionValue ? "Remapping" : "Deleation"} of the ${selectedOption} ${type === TaxonomyType.Tag ? "tag" : "category"} completed.`);
});
+3 -4
View File
@@ -37,10 +37,9 @@ export class StatusListener {
collection.clear();
// Retrieve the SEO config properties
const config = Settings.getConfig();
const titleLength = config.get(SETTING_SEO_TITLE_LENGTH) as number || -1;
const descLength = config.get(SETTING_SEO_DESCRIPTION_LENGTH) as number || -1;
const fieldName = config.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description;
const titleLength = Settings.get(SETTING_SEO_TITLE_LENGTH) as number || -1;
const descLength = Settings.get(SETTING_SEO_DESCRIPTION_LENGTH) as number || -1;
const fieldName = Settings.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description;
if (article.data.title && titleLength > -1) {
SeoHelper.checkLength(editor, collection, article, "title", titleLength);
+3 -5
View File
@@ -93,9 +93,8 @@ export class Template {
* Create from a template
*/
public static async create(folderPath: string) {
const config = Settings.getConfig();
const folder = config.get<string>(SETTING_TEMPLATES_FOLDER);
const prefix = config.get<string>(SETTING_TEMPLATES_PREFIX);
const folder = Settings.get<string>(SETTING_TEMPLATES_FOLDER);
const prefix = Settings.get<string>(SETTING_TEMPLATES_PREFIX);
if (!folderPath) {
Notifications.warning(`Incorrect project folder path retrieved.`);
@@ -188,8 +187,7 @@ export class Template {
* Get the folder settings
*/
public static getSettings() {
const config = Settings.getConfig();
const folder = config.get<string>(SETTING_TEMPLATES_FOLDER);
const folder = Settings.get<string>(SETTING_TEMPLATES_FOLDER);
return folder;
}
}
+26 -41
View File
@@ -204,16 +204,9 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
}
}, this);
workspace.onDidChangeConfiguration(() => {
Settings.onConfigChange((global?: any) => {
this.getSettings();
});
workspace.onDidChangeTextDocument((e) => {
console.log(e.document.fileName);
if (e.document.fileName === "frontmatter.json") {
console.log("frontmatter.json changed");
}
});
}
/**
@@ -223,10 +216,9 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
public pushMetadata(metadata: any) {
const wsFolder = Folders.getWorkspaceFolder();
const filePath = window.activeTextEditor?.document.uri.fsPath;
const config = Settings.getConfig();
const commaSeparated = config.get<string[]>(SETTING_COMMA_SEPARATED_FIELDS);
const staticFolder = config.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS);
const contentTypes = config.get<string>(SETTING_TAXONOMY_CONTENT_TYPES);
const commaSeparated = Settings.get<string[]>(SETTING_COMMA_SEPARATED_FIELDS);
const staticFolder = Settings.get<string>(SETTINGS_CONTENT_STATIC_FOLDERS);
const contentTypes = Settings.get<string>(SETTING_TAXONOMY_CONTENT_TYPES);
const articleDetails = this.getArticleDetails();
@@ -338,8 +330,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
* @param msg
*/
private runCustomScript(msg: { command: string, data: any}) {
const config = Settings.getConfig();
const scripts: CustomScript[] | undefined = config.get(SETTING_CUSTOM_SCRIPTS);
const scripts: CustomScript[] | undefined = Settings.get(SETTING_CUSTOM_SCRIPTS);
if (msg?.data?.title && msg?.data?.script && scripts) {
const customScript = scripts.find((s: CustomScript) => s.title === msg.data.title);
@@ -389,36 +380,34 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
* Retrieve the extension settings
*/
public async getSettings() {
const config = Settings.getConfig();
this.postWebviewMessage({
command: Command.settings,
data: {
seo: {
title: config.get(SETTING_SEO_TITLE_LENGTH) as number || -1,
description: config.get(SETTING_SEO_DESCRIPTION_LENGTH) as number || -1,
content: config.get(SETTING_SEO_CONTENT_MIN_LENGTH) as number || -1,
descriptionField: config.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description
title: Settings.get(SETTING_SEO_TITLE_LENGTH) as number || -1,
description: Settings.get(SETTING_SEO_DESCRIPTION_LENGTH) as number || -1,
content: Settings.get(SETTING_SEO_CONTENT_MIN_LENGTH) as number || -1,
descriptionField: Settings.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description
},
slug: {
prefix: config.get(SETTING_SLUG_PREFIX) || "",
suffix: config.get(SETTING_SLUG_SUFFIX) || "",
updateFileName: !!config.get<boolean>(SETTING_SLUG_UPDATE_FILE_NAME),
prefix: Settings.get(SETTING_SLUG_PREFIX) || "",
suffix: Settings.get(SETTING_SLUG_SUFFIX) || "",
updateFileName: !!Settings.get<boolean>(SETTING_SLUG_UPDATE_FILE_NAME),
},
date: {
format: config.get(SETTING_DATE_FORMAT)
format: Settings.get(SETTING_DATE_FORMAT)
},
tags: config.get(SETTING_TAXONOMY_TAGS) || [],
categories: config.get(SETTING_TAXONOMY_CATEGORIES) || [],
freeform: config.get(SETTING_PANEL_FREEFORM),
scripts: config.get(SETTING_CUSTOM_SCRIPTS),
tags: Settings.get(SETTING_TAXONOMY_TAGS) || [],
categories: Settings.get(SETTING_TAXONOMY_CATEGORIES) || [],
freeform: Settings.get(SETTING_PANEL_FREEFORM),
scripts: Settings.get(SETTING_CUSTOM_SCRIPTS),
isInitialized: await Template.isInitialized(),
modifiedDateUpdate: config.get(SETTING_AUTO_UPDATE_DATE) || false,
modifiedDateUpdate: Settings.get(SETTING_AUTO_UPDATE_DATE) || false,
writingSettingsEnabled: this.isWritingSettingsEnabled() || false,
fmHighlighting: config.get(SETTINGS_CONTENT_FRONTMATTER_HIGHLIGHT),
fmHighlighting: Settings.get(SETTINGS_CONTENT_FRONTMATTER_HIGHLIGHT),
preview: Preview.getSettings(),
commaSeparatedFields: config.get(SETTING_COMMA_SEPARATED_FIELDS) || [],
contentTypes: config.get(SETTING_TAXONOMY_CONTENT_TYPES) || [],
commaSeparatedFields: Settings.get(SETTING_COMMA_SEPARATED_FIELDS) || [],
contentTypes: Settings.get(SETTING_TAXONOMY_CONTENT_TYPES) || [],
dashboardViewData: Dashboard.viewData
} as PanelSettings
});
@@ -473,8 +462,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
*/
private async addTags(tagType: TagType, value: string) {
if (value) {
const config = Settings.getConfig();
let options = tagType === TagType.tags ? config.get<string[]>(SETTING_TAXONOMY_TAGS) : config.get<string[]>(SETTING_TAXONOMY_CATEGORIES);
let options = tagType === TagType.tags ? Settings.get<string[]>(SETTING_TAXONOMY_TAGS) : Settings.get<string[]>(SETTING_TAXONOMY_CATEGORIES);
if (!options) {
options = [];
@@ -482,7 +470,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
options.push(value);
const taxType = tagType === TagType.tags ? TaxonomyType.Tag : TaxonomyType.Category;
await Settings.update(taxType, options);
await Settings.updateTaxonomy(taxType, options);
}
}
@@ -581,8 +569,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
* Update the preview URL
*/
private async updatePreviewUrl(previewUrl: string) {
const config = Settings.getConfig();
await config.update(SETTING_PREVIEW_HOST, previewUrl);
await Settings.update(SETTING_PREVIEW_HOST, previewUrl);
this.getSettings();
}
@@ -590,8 +577,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
* Toggle the Front Matter highlighting
*/
private async updateFmHighlight(autoUpdate: boolean) {
const config = Settings.getConfig();
await config.update(SETTINGS_CONTENT_FRONTMATTER_HIGHLIGHT, autoUpdate);
await Settings.update(SETTINGS_CONTENT_FRONTMATTER_HIGHLIGHT, autoUpdate);
this.getSettings();
}
@@ -599,8 +585,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable {
* Toggle the modified auto-update setting
*/
private async updateModifiedUpdating(autoUpdate: boolean) {
const config = Settings.getConfig();
await config.update(SETTING_AUTO_UPDATE_DATE, autoUpdate);
await Settings.update(SETTING_AUTO_UPDATE_DATE, autoUpdate);
this.getSettings();
}
+3 -1
View File
@@ -12,6 +12,7 @@ import { TagType } from './panelWebView/TagType';
import { ExplorerView } from './explorerView/ExplorerView';
import { Extension } from './helpers/Extension';
import { DashboardData } from './models/DashboardData';
import { Settings as SettingsHelper } from './helpers';
let frontMatterStatusBar: vscode.StatusBarItem;
let statusDebouncer: { (fnc: any, time: number): void; };
@@ -23,6 +24,7 @@ const mdSelector: vscode.DocumentSelector = { language: 'markdown', scheme: 'fil
export async function activate(context: vscode.ExtensionContext) {
const { subscriptions, extensionUri, extensionPath } = context;
SettingsHelper.init();
const extension = Extension.getInstance(context);
if (!extension.checkIfExtensionCanRun()) {
@@ -120,7 +122,7 @@ export async function activate(context: vscode.ExtensionContext) {
});
// Things to do when configuration changes
vscode.workspace.onDidChangeConfiguration(() => {
SettingsHelper.onConfigChange((global?: any) => {
Template.init();
Preview.init();
+8 -13
View File
@@ -39,9 +39,8 @@ export class ArticleHelper {
* @param article
*/
public static async update(editor: vscode.TextEditor, article: matter.GrayMatterFile<string>) {
const config = Settings.getConfig();
const removeQuotes = config.get(SETTING_REMOVE_QUOTES) as string[];
const commaSeparated = config.get<string[]>(SETTING_COMMA_SEPARATED_FIELDS);
const removeQuotes = Settings.get(SETTING_REMOVE_QUOTES) as string[];
const commaSeparated = Settings.get<string[]>(SETTING_COMMA_SEPARATED_FIELDS);
let newMarkdown = this.stringifyFrontMatter(article.content, Object.assign({}, article.data));
@@ -72,9 +71,8 @@ export class ArticleHelper {
* @param data
*/
public static stringifyFrontMatter(content: string, data: any) {
const config = Settings.getConfig();
const indentArray = config.get(SETTING_INDENT_ARRAY) as boolean;
const commaSeparated = config.get<string[]>(SETTING_COMMA_SEPARATED_FIELDS);
const indentArray = Settings.get(SETTING_INDENT_ARRAY) as boolean;
const commaSeparated = Settings.get<string[]>(SETTING_COMMA_SEPARATED_FIELDS);
const language = getFmLanguage();
const langOpts = getFormatOpts(language);
@@ -114,9 +112,8 @@ export class ArticleHelper {
return;
}
const config = Settings.getConfig();
const dateFormat = config.get(SETTING_DATE_FORMAT) as string;
const dateField = config.get(SETTING_DATE_FIELD) as string || DefaultFields.PublishingDate;
const dateFormat = Settings.get(SETTING_DATE_FORMAT) as string;
const dateField = Settings.get(SETTING_DATE_FIELD) as string || DefaultFields.PublishingDate;
if (typeof article.data[dateField] !== "undefined") {
if (dateFormat && typeof dateFormat === "string") {
@@ -135,8 +132,7 @@ export class ArticleHelper {
* @param updatedMetadata
*/
public static getContentType(metadata: { [field: string]: string; }): ContentType {
const config = Settings.getConfig();
const contentTypes = config.get<ContentType[]>(SETTING_TAXONOMY_CONTENT_TYPES);
const contentTypes = Settings.get<ContentType[]>(SETTING_TAXONOMY_CONTENT_TYPES);
if (!contentTypes || !metadata) {
return DEFAULT_CONTENT_TYPE;
@@ -173,8 +169,7 @@ export class ArticleHelper {
*/
private static parseFile(fileContents: string): matter.GrayMatterFile<string> | null {
try {
const config = Settings.getConfig();
const commaSeparated = config.get<string[]>(SETTING_COMMA_SEPARATED_FIELDS);
const commaSeparated = Settings.get<string[]>(SETTING_COMMA_SEPARATED_FIELDS);
if (fileContents) {
const language: string = getFmLanguage();
+7 -9
View File
@@ -66,10 +66,8 @@ export class Extension {
* Migrate old settings to new settings
*/
public async migrateSettings(): Promise<void> {
const config = Settings.getConfig();
// Migration to version 3.1.0
const folders = config.get<any>(SETTINGS_CONTENT_FOLDERS);
const folders = Settings.get<any>(SETTINGS_CONTENT_FOLDERS);
if (folders && folders.length > 0) {
const workspace = Folders.getWorkspaceFolder();
const projectFolder = basename(workspace?.fsPath || "");
@@ -79,14 +77,14 @@ export class Extension {
path: `${WORKSPACE_PLACEHOLDER}${folder.fsPath.split(projectFolder).slice(1).join('')}`.split('\\').join('/')
}));
await config.update(`${SETTINGS_CONTENT_PAGE_FOLDERS}`, paths);
await Settings.update(SETTINGS_CONTENT_PAGE_FOLDERS, paths);
}
// Migration to version 3.2.0
const dateField = config.get<string>(SETTING_DATE_FIELD);
const lastModField = config.get<string>(SETTING_MODIFIED_FIELD);
const description = config.get<string>(SETTING_SEO_DESCRIPTION_FIELD);
const contentTypes = config.get<ContentType[]>(SETTING_TAXONOMY_CONTENT_TYPES);
const dateField = Settings.get<string>(SETTING_DATE_FIELD);
const lastModField = Settings.get<string>(SETTING_MODIFIED_FIELD);
const description = Settings.get<string>(SETTING_SEO_DESCRIPTION_FIELD);
const contentTypes = Settings.get<ContentType[]>(SETTING_TAXONOMY_CONTENT_TYPES);
if (contentTypes) {
let needsUpdate = false;
@@ -121,7 +119,7 @@ export class Extension {
}
if (needsUpdate) {
await config.update(SETTING_TAXONOMY_CONTENT_TYPES, contentTypes);
await Settings.update(SETTING_TAXONOMY_CONTENT_TYPES, contentTypes);
}
}
}
+52 -27
View File
@@ -3,30 +3,31 @@ import * as vscode from 'vscode';
import { TaxonomyType } from '../models';
import { SETTING_TAXONOMY_TAGS, SETTING_TAXONOMY_CATEGORIES, CONFIG_KEY } from '../constants';
import { Folders } from '../commands/Folders';
import { join } from 'path';
import { existsSync, readFileSync } from 'fs';
import { join, basename } from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';
export class Settings {
private static config: vscode.WorkspaceConfiguration;
private static globalFile = "frontmatter.json";
private static globalConfig: any;
public static init() {
const wsFolder = Folders.getWorkspaceFolder();
if (wsFolder) {
const fmConfig = join(wsFolder.fsPath, 'frontmatter.json');
const fmConfig = join(wsFolder.fsPath, Settings.globalFile);
if (existsSync(fmConfig)) {
const localConfig = readFileSync(fmConfig, 'utf8');
this.globalConfig = JSON.parse(localConfig);
Settings.globalConfig = JSON.parse(localConfig);
}
}
this.config = vscode.workspace.getConfiguration(CONFIG_KEY);
Settings.config = vscode.workspace.getConfiguration(CONFIG_KEY);
Settings.onConfigChange((global?: any) => {
if (global) {
this.globalConfig = Object.assign({}, global);
Settings.globalConfig = Object.assign({}, global);
} else {
this.config = vscode.workspace.getConfiguration(CONFIG_KEY);
Settings.config = vscode.workspace.getConfiguration(CONFIG_KEY);
}
});
}
@@ -40,10 +41,12 @@ export class Settings {
callback();
});
workspace.onDidChangeTextDocument((e) => {
if (e.document.fileName === "frontmatter.json") {
if (e && e.document.fileName === "frontmatter.json") {
const fileContents = e.document.getText();
workspace.onDidSaveTextDocument(async (e) => {
const filename = e.uri.fsPath;
if (filename && basename(filename).toLowerCase() === Settings.globalFile.toLowerCase()) {
const file = await workspace.openTextDocument(e.uri);
if (file) {
const fileContents = file.getText();
const json = JSON.parse(fileContents);
callback(json);
}
@@ -55,39 +58,61 @@ export class Settings {
* Retrieve a setting from global and local config
*/
public static get<T>(name: string): T | undefined{
const configInpection = this.config.inspect<T>(name);
const configInpection = Settings.config.inspect<T>(name);
let setting = undefined;
const settingKey = `${CONFIG_KEY}.${name}`;
if (typeof this.globalConfig[settingKey] !== "undefined") {
setting = this.globalConfig[settingKey];
if (typeof Settings.globalConfig[settingKey] !== "undefined") {
setting = Settings.globalConfig[settingKey];
}
// Local overrides global
if (configInpection && typeof configInpection.workspaceValue !== undefined) {
if (configInpection && typeof configInpection.workspaceValue !== "undefined") {
setting = configInpection.workspaceValue;
}
if (setting === undefined) {
setting = Settings.config.get(name);
}
return setting;
}
/**
* String update config setting
* @param name
* @param value
*/
public static async update<T>(name: string, value: T, updateGlobal: boolean = false) {
const wsFolder = Folders.getWorkspaceFolder();
if (updateGlobal) {
if (wsFolder) {
const fmConfig = join(wsFolder.fsPath, Settings.globalFile);
if (existsSync(fmConfig)) {
const localConfig = readFileSync(fmConfig, 'utf8');
Settings.globalConfig = JSON.parse(localConfig);
Settings.globalConfig[`${CONFIG_KEY}.${name}`] = value;
writeFileSync(fmConfig, JSON.stringify(Settings.globalConfig, null, 2), 'utf8');
return;
}
}
} else {
await Settings.config.update(name, value);
return;
}
// Fallback to the local settings
await Settings.config.update(name, value);
}
/**
* Retrieves the config
* @returns
*/
public static getConfig(): vscode.WorkspaceConfiguration {
return this.config;
}
/**
* Update a setting
* @param name
* @param value
*/
public static async updateSetting(name: string, value: any) {
const config = vscode.workspace.getConfiguration(CONFIG_KEY);
await config.update(name, value);
return Settings.config;
}
/**
@@ -113,7 +138,7 @@ export class Settings {
* @param type
* @param options
*/
static async update(type: TaxonomyType, options: string[]) {
static async updateTaxonomy(type: TaxonomyType, options: string[]) {
const config = vscode.workspace.getConfiguration(CONFIG_KEY);
const configSetting = type === TaxonomyType.Tag ? SETTING_TAXONOMY_TAGS : SETTING_TAXONOMY_CATEGORIES;
options = [...new Set(options)];
+2 -4
View File
@@ -1,11 +1,9 @@
import * as vscode from 'vscode';
import * as toml from '@iarna/toml';
import { SETTING_FRONTMATTER_TYPE } from '../constants';
import { Settings } from '.';
import { Settings } from './SettingsHelper';
export const getFmLanguage = (): string => {
const config = Settings.getConfig();
const language = config.get(SETTING_FRONTMATTER_TYPE) as string || "YAML";
const language = Settings.get(SETTING_FRONTMATTER_TYPE) as string || "YAML";
return language.toLowerCase();
};