Skip to content

Commit

Permalink
refactor: Consolidate cache functionality under workspace folder
Browse files Browse the repository at this point in the history
  • Loading branch information
svsool committed Jan 23, 2022
1 parent bf45c36 commit 9b7cc58
Show file tree
Hide file tree
Showing 23 changed files with 548 additions and 507 deletions.
8 changes: 4 additions & 4 deletions src/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import openReferenceBeside from './openReferenceBeside';
import openDailyNote from './openDailyNote';
import pasteHtmlAsMarkdown from './pasteHtmlAsMarkdown';
import extractRangeToNewNote from './extractRangeToNewNote';
import { cacheWorkspace, cleanWorkspaceCache, getWorkspaceCache } from '../utils';
import { cache } from '../workspace';

const commands = [
vscode.commands.registerCommand('_memo.openDocumentByReference', openDocumentByReference),
vscode.commands.registerCommand('_memo.cacheWorkspace', cacheWorkspace),
vscode.commands.registerCommand('_memo.cleanWorkspaceCache', cleanWorkspaceCache),
vscode.commands.registerCommand('_memo.getWorkspaceCache', getWorkspaceCache),
vscode.commands.registerCommand('_memo.cacheWorkspace', cache.cacheWorkspace),
vscode.commands.registerCommand('_memo.cleanWorkspaceCache', cache.cleanWorkspaceCache),
vscode.commands.registerCommand('_memo.getWorkspaceCache', cache.getWorkspaceCache),
vscode.commands.registerCommand('memo.openRandomNote', openRandomNote),
vscode.commands.registerCommand('memo.openDailyNote', openDailyNote),
vscode.commands.registerCommand('memo.openReferenceInDefaultApp', openReferenceInDefaultApp),
Expand Down
4 changes: 2 additions & 2 deletions src/commands/openDocumentByReference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import vscode from 'vscode';
import fs from 'fs';
import path from 'path';

import { cache } from '../workspace';
import {
getWorkspaceCache,
findUriByRef,
ensureDirectoryExists,
parseRef,
Expand All @@ -21,7 +21,7 @@ const openDocumentByReference = async ({
}) => {
const { ref } = parseRef(reference);

const uri = findUriByRef(getWorkspaceCache().allUris, ref);
const uri = findUriByRef(cache.getWorkspaceCache().allUris, ref);

if (uri) {
await vscode.commands.executeCommand('vscode.open', uri, showOption);
Expand Down
8 changes: 4 additions & 4 deletions src/commands/openRandomNote.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { commands, workspace } from 'vscode';
import fs from 'fs';

import { getWorkspaceCache } from '../utils';
import { cache } from '../workspace';

const openRandomNote = async () => {
const openedFileNames = workspace.textDocuments.map((d) => d.fileName);
const markdownUris = getWorkspaceCache().markdownUris.filter(
({ fsPath }) => !openedFileNames.includes(fsPath),
);
const markdownUris = cache
.getWorkspaceCache()
.markdownUris.filter(({ fsPath }) => !openedFileNames.includes(fsPath));
const randomUriIndex = Math.floor(Math.random() * markdownUris.length);
const randomUri = markdownUris[randomUriIndex];

Expand Down
5 changes: 3 additions & 2 deletions src/commands/openReferenceInDefaultApp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import open from 'open';
import * as vscode from 'vscode';

import { getWorkspaceCache, getReferenceAtPosition, findUriByRef } from '../utils';
import { cache } from '../workspace';
import { getReferenceAtPosition, findUriByRef } from '../utils';

const openReferenceInDefaultApp = async () => {
const activeTextEditor = vscode.window.activeTextEditor;
Expand All @@ -13,7 +14,7 @@ const openReferenceInDefaultApp = async () => {
);

if (refAtPos) {
const uri = findUriByRef(getWorkspaceCache().allUris, refAtPos.ref);
const uri = findUriByRef(cache.getWorkspaceCache().allUris, refAtPos.ref);

if (uri) {
await open(uri.fsPath);
Expand Down
8 changes: 4 additions & 4 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as vscode from 'vscode';

import { fileWatcher } from './workspace';
import { fileWatcher, cache } from './workspace';
import {
syntaxDecorations,
referenceContextWatcher,
Expand All @@ -16,7 +16,7 @@ import {
} from './features';
import commands from './commands';
import logger from './logger';
import { cacheWorkspace, getMemoConfigProperty, MemoBoolConfigProp, isDefined } from './utils';
import { getMemoConfigProperty, MemoBoolConfigProp, isDefined } from './utils';

const mdLangSelector = { language: 'markdown', scheme: '*' };

Expand All @@ -38,7 +38,7 @@ export const activate = async (

referenceContextWatcher.activate(context);

await cacheWorkspace();
await cache.cacheWorkspace();

context.subscriptions.push(logger.logger);

Expand All @@ -47,7 +47,7 @@ export const activate = async (
vscode.languages.registerCodeActionsProvider(mdLangSelector, codeActionProvider),
vscode.workspace.onDidChangeConfiguration(async (configChangeEvent) => {
if (configChangeEvent.affectsConfiguration('search.exclude')) {
await cacheWorkspace();
await cache.cacheWorkspace();
}
}),
...[
Expand Down
4 changes: 2 additions & 2 deletions src/features/BacklinksTreeDataProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import vscode, { workspace } from 'vscode';
import path from 'path';
import groupBy from 'lodash.groupby';

import { cache } from '../workspace';
import {
getWorkspaceCache,
containsMarkdownExt,
findReferences,
trimSlashes,
Expand Down Expand Up @@ -69,7 +69,7 @@ export default class BacklinksTreeDataProvider implements vscode.TreeDataProvide
return [];
}

const urisByPathBasename = groupBy(getWorkspaceCache().markdownUris, ({ fsPath }) =>
const urisByPathBasename = groupBy(cache.getWorkspaceCache().markdownUris, ({ fsPath }) =>
path.basename(fsPath).toLowerCase(),
);

Expand Down
4 changes: 2 additions & 2 deletions src/features/ReferenceHoverProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import vscode from 'vscode';
import fs from 'fs';
import path from 'path';

import { cache } from '../workspace';
import {
containsImageExt,
containsUnknownExt,
containsOtherKnownExts,
getWorkspaceCache,
getMemoConfigProperty,
getReferenceAtPosition,
isUncPath,
Expand All @@ -25,7 +25,7 @@ export default class ReferenceHoverProvider implements vscode.HoverProvider {
new vscode.Position(range.end.line, range.end.character - 2),
);

const uris = getWorkspaceCache().allUris;
const uris = cache.getWorkspaceCache().allUris;
const foundUri = findUriByRef(uris, ref);

if (!foundUri && containsUnknownExt(ref)) {
Expand Down
10 changes: 5 additions & 5 deletions src/features/ReferenceRenameProvider.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { RenameProvider, TextDocument, Position, Range, WorkspaceEdit, Uri } from 'vscode';
import path from 'path';

import { cache } from '../workspace';
import {
getReferenceAtPosition,
findUriByRef,
getWorkspaceCache,
isLongRef,
getWorkspaceFolder,
containsMarkdownExt,
Expand Down Expand Up @@ -33,11 +33,11 @@ export default class ReferenceRenameProvider implements RenameProvider {
const unknownUris = containsUnknownExt(ref) ? await findFilesByExts([extractExt(ref)]) : [];

const augmentedUris = unknownUris.length
? sortPaths([...getWorkspaceCache().allUris, ...unknownUris], {
? sortPaths([...cache.getWorkspaceCache().allUris, ...unknownUris], {
pathKey: 'path',
shallowFirst: true,
})
: getWorkspaceCache().allUris;
: cache.getWorkspaceCache().allUris;

if (!findUriByRef(augmentedUris, ref)) {
throw new Error(
Expand Down Expand Up @@ -69,11 +69,11 @@ export default class ReferenceRenameProvider implements RenameProvider {
const unknownUris = containsUnknownExt(ref) ? await findFilesByExts([extractExt(ref)]) : [];

const augmentedUris = unknownUris.length
? sortPaths([...getWorkspaceCache().allUris, ...unknownUris], {
? sortPaths([...cache.getWorkspaceCache().allUris, ...unknownUris], {
pathKey: 'path',
shallowFirst: true,
})
: getWorkspaceCache().allUris;
: cache.getWorkspaceCache().allUris;

const fsPath = findUriByRef(augmentedUris, ref)?.fsPath;

Expand Down
12 changes: 6 additions & 6 deletions src/features/completionProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import path from 'path';
import groupBy from 'lodash.groupby';
import fs from 'fs';

import { cache } from '../workspace';
import {
getWorkspaceCache,
fsPathToRef,
containsMarkdownExt,
containsImageExt,
Expand Down Expand Up @@ -46,13 +46,13 @@ export const provideCompletionItems = (document: TextDocument, position: Positio

const uris: Uri[] = [
...(isResourceAutocomplete
? [...getWorkspaceCache().imageUris, ...getWorkspaceCache().markdownUris]
? [...cache.getWorkspaceCache().imageUris, ...cache.getWorkspaceCache().markdownUris]
: []),
...(!isResourceAutocomplete
? [
...getWorkspaceCache().markdownUris,
...getWorkspaceCache().imageUris,
...getWorkspaceCache().otherUris,
...cache.getWorkspaceCache().markdownUris,
...cache.getWorkspaceCache().imageUris,
...cache.getWorkspaceCache().otherUris,
]
: []),
];
Expand Down Expand Up @@ -100,7 +100,7 @@ export const provideCompletionItems = (document: TextDocument, position: Positio
completionItems.push(item);
});

const danglingRefs = getWorkspaceCache().danglingRefs;
const danglingRefs = cache.getWorkspaceCache().danglingRefs;

const completionItemsLength = completionItems.length;

Expand Down
8 changes: 4 additions & 4 deletions src/features/extendMarkdownIt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import markdownItRegex from 'markdown-it-regex';
import path from 'path';
import fs from 'fs';

import { cache } from '../workspace';
import {
getWorkspaceCache,
getImgUrlForMarkdownPreview,
getFileUrlForMarkdownPreview,
containsImageExt,
Expand Down Expand Up @@ -37,7 +37,7 @@ const extendMarkdownIt = (md: MarkdownIt) => {
const { ref, label } = parseRef(rawRef);

if (containsImageExt(ref)) {
const imagePath = findUriByRef(getWorkspaceCache().imageUris, ref)?.fsPath;
const imagePath = findUriByRef(cache.getWorkspaceCache().imageUris, ref)?.fsPath;

if (imagePath) {
return `<div><img src="${getImgUrlForMarkdownPreview(
Expand All @@ -48,7 +48,7 @@ const extendMarkdownIt = (md: MarkdownIt) => {
}
}

const fsPath = findUriByRef(getWorkspaceCache().markdownUris, ref)?.fsPath;
const fsPath = findUriByRef(cache.getWorkspaceCache().markdownUris, ref)?.fsPath;

if (!fsPath && containsUnknownExt(ref)) {
return getUnknownExtRefAnchor(label || ref, ref);
Expand Down Expand Up @@ -100,7 +100,7 @@ const extendMarkdownIt = (md: MarkdownIt) => {
replace: (rawRef: string) => {
const { ref, label } = parseRef(rawRef);

const fsPath = findUriByRef(getWorkspaceCache().allUris, ref)?.fsPath;
const fsPath = findUriByRef(cache.getWorkspaceCache().allUris, ref)?.fsPath;

if (!fsPath && containsUnknownExt(ref)) {
return getUnknownExtRefAnchor(label || ref, ref);
Expand Down
5 changes: 3 additions & 2 deletions src/test/testUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from 'path';
import { workspace, Uri, commands, ConfigurationTarget } from 'vscode';
export { default as waitForExpect } from 'wait-for-expect';

import { cache } from '../workspace';
import * as utils from '../utils';
import { WorkspaceCache } from '../types';

Expand Down Expand Up @@ -35,12 +36,12 @@ export const cleanWorkspace = () => {
};

export const cacheWorkspace = async () => {
await utils.cacheWorkspace();
await cache.cacheWorkspace();
await commands.executeCommand('_memo.cacheWorkspace');
};

export const cleanWorkspaceCache = async () => {
utils.cleanWorkspaceCache();
cache.cleanWorkspaceCache();
await commands.executeCommand('_memo.cleanWorkspaceCache');
};

Expand Down
8 changes: 5 additions & 3 deletions src/utils/createDailyQuickPick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import range from 'lodash.range';
import path from 'path';
import { window } from 'vscode';

import { findUriByRef, getWorkspaceCache } from './utils';
import { findUriByRef } from './utils';
import { cache } from '../workspace';

const toOffsetLabel = (dayOffset: number) => {
if (dayOffset === -1) {
Expand All @@ -21,7 +22,8 @@ const yyyymmddRegExp = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/;

const createDailyQuickPick = () => {
const now = moment().startOf('day');
const allDailyDates = getWorkspaceCache()
const allDailyDates = cache
.getWorkspaceCache()
.markdownUris.map((uri) => path.parse(uri.fsPath).name)
.filter((name) => yyyymmddRegExp.exec(name) && moment(name).isValid());
const existingDayOffsets = allDailyDates.map((dateStr) =>
Expand Down Expand Up @@ -51,7 +53,7 @@ const createDailyQuickPick = () => {
quickPick.items = dayOffsets.map((dayOffset) => {
const date = now.clone().add(dayOffset, 'day');
const dateYYYYMMDD = date.format('YYYY-MM-DD');
const ref = findUriByRef(getWorkspaceCache().markdownUris, dateYYYYMMDD);
const ref = findUriByRef(cache.getWorkspaceCache().markdownUris, dateYYYYMMDD);

return {
label: `${ref ? '✓' : '✕'} ${toOffsetLabel(dayOffset)} | ${date.format(
Expand Down
7 changes: 7 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import { sort as sortPaths } from 'cross-path-sort';

import { default as createDailyQuickPick } from './createDailyQuickPick';
import { readClipboard } from './clipboardUtils';

export { sortPaths, createDailyQuickPick, readClipboard };

export * from './utils';
export * from './externalUtils';
export * from './replaceUtils';
Expand Down
8 changes: 4 additions & 4 deletions src/utils/replaceUtils.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import path from 'path';
import { Uri, TextDocument } from 'vscode';
import groupBy from 'lodash.groupby';
import { sort as sortPaths } from 'cross-path-sort';

import { cache } from '../workspace';
import {
fsPathToRef,
getWorkspaceFolder,
containsMarkdownExt,
isDefined,
getMemoConfigProperty,
sortPaths,
getWorkspaceCache,
findAllUrisWithUnknownExts,
escapeForRegExp,
} from './utils';
Expand Down Expand Up @@ -46,7 +46,7 @@ export const resolveRefsReplaceMap = async (
const oldUrisGroupedByBasename = groupBy(
sortPaths(
[
...getWorkspaceCache().allUris.filter((uri) => !oldFsPaths.includes(uri.fsPath)),
...cache.getWorkspaceCache().allUris.filter((uri) => !oldFsPaths.includes(uri.fsPath)),
...renamedFiles.map(({ oldUri }) => oldUri),
],
{
Expand All @@ -60,7 +60,7 @@ export const resolveRefsReplaceMap = async (
const newFsPaths = renamedFiles.map(({ newUri }) => newUri.fsPath);

const allUris = [
...getWorkspaceCache().allUris.filter((uri) => !newFsPaths.includes(uri.fsPath)),
...cache.getWorkspaceCache().allUris.filter((uri) => !newFsPaths.includes(uri.fsPath)),
...renamedFiles.map(({ newUri }) => newUri),
];

Expand Down
Loading

0 comments on commit 9b7cc58

Please sign in to comment.