Skip to content

Commit

Permalink
Merge pull request #331 from caiych/config
Browse files Browse the repository at this point in the history
  • Loading branch information
svsool authored May 14, 2021
2 parents 961af86 + 8fb531c commit 59081ba
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 3 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,22 @@ If you want to try out Memo just install it via marketplace using [this link](ht

![Creating notes on the fly](./help/Attachments/Creating%20notes%20from%20links.png)

- Also supporting configurable rules to specify the destination of the newly created notes.
The following snippet is an example to create daily notes in directory `Daily` and all other notes in `Notes`.

```json
[{
"rule": "/([12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))\\.md$",
"comment": "Daily notes yyyy-mm-dd",
"folder": "/Daily"
},
{
"rule": "\\.md$",
"comment": "All other notes",
"folder": "/Notes"
]}
```

- 🖇 **Backlinks panel**

![Backlinks panel](./help/Attachments/Backlinks%20panel.png)
Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@
"description": "Whether to enable references search for links in the editor. Reload required!",
"type": "boolean"
},
"memo.links.rules": {
"default": [],
"scope": "resource",
"description": "Rules specifying the location where new files should be created for short links. Applicable only if links format is set to short in the settings. In case if multiple rules matching the file path, the rule that comes first will be applied.",
"type": "array"
},
"memo.links.sync.enabled": {
"default": true,
"scope": "resource",
Expand Down
57 changes: 57 additions & 0 deletions src/commands/openDocumentByReference.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
getOpenedPaths,
closeEditorsAndCleanWorkspace,
toPlainObject,
updateMemoConfigProperty,
} from '../test/testUtils';

describe('openDocumentByReference command', () => {
Expand Down Expand Up @@ -201,4 +202,60 @@ describe('openDocumentByReference command', () => {

executeCommandSpy.mockRestore();
});

it('should create a note in a configured sub dir', async () => {
await updateMemoConfigProperty('links.rules', [
{
rule: '.*\\.md$',
comment: 'all notes',
folder: '/Notes',
},
]);

const name = rndName();

expect(getOpenedFilenames()).not.toContain(`${name}.md`);

await openDocumentByReference({ reference: name });

expect(getOpenedPaths()).toContain(
`${path.join(getWorkspaceFolder()!, 'Notes', `${name}.md`)}`,
);
});

it('should not create a note in a configured sub dir for long links', async () => {
await updateMemoConfigProperty('links.rules', [
{
rule: '.*\\.md$',
comment: 'all notes',
folder: '/Notes',
},
]);

const name = `dir/${rndName()}`;

expect(getOpenedFilenames()).not.toContain(`${name}.md`);

await openDocumentByReference({ reference: name });

expect(getOpenedPaths()).toContain(`${path.join(getWorkspaceFolder()!, `${name}.md`)}`);
});

it('should create a note in a root dir when no matching rule found', async () => {
await updateMemoConfigProperty('links.rules', [
{
rule: '.*\\.txt$',
comment: 'all text',
folder: '/Text',
},
]);

const name = rndName();

expect(getOpenedFilenames()).not.toContain(`${name}.md`);

await openDocumentByReference({ reference: name });

expect(getOpenedPaths()).toContain(`${path.join(getWorkspaceFolder()!, `${name}.md`)}`);
});
});
24 changes: 22 additions & 2 deletions src/commands/openDocumentByReference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
ensureDirectoryExists,
parseRef,
getWorkspaceFolder,
getMemoConfigProperty,
isLongRef,
} from '../utils';

const openDocumentByReference = async ({
Expand All @@ -28,10 +30,28 @@ const openDocumentByReference = async ({
if (workspaceFolder) {
const paths = ref.split('/');
const refExt = path.parse(ref).ext;
const pathsWithExt = [

const resolvedRef = path.join(
...paths.slice(0, -1),
`${paths.slice(-1)}${refExt !== '.md' && refExt !== '' ? '' : '.md'}`,
];
);

let defaultPath;
try {
// Apply default folder rule if it's a short ref(i.e. doesn't have an existing dir in ref).
defaultPath = !isLongRef(ref)
? getMemoConfigProperty('links.rules', []).find((rule) =>
new RegExp(rule.rule).test(resolvedRef),
)?.folder
: undefined;
} catch (error) {
vscode.window.showWarningMessage(
`Fail to decide path to create the file, please check config. error: ${error}`,
);
return;
}

const pathsWithExt = (defaultPath ? [defaultPath] : []).concat([resolvedRef]);
const filePath = path.join(workspaceFolder, ...pathsWithExt);

// don't override file content if it already exists
Expand Down
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,9 @@ export type FoundRefT = {
location: Location;
matchText: string;
};

export type LinkRuleT = {
rule: string;
comment?: string;
folder: string;
};
7 changes: 6 additions & 1 deletion src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from 'path';
import { sort as sortPaths } from 'cross-path-sort';
import fs from 'fs';

import { WorkspaceCache, RefT, FoundRefT } from '../types';
import { WorkspaceCache, RefT, FoundRefT, LinkRuleT } from '../types';
import { isInCodeSpan, isInFencedCodeBlock } from './externalUtils';
import { default as createDailyQuickPick } from './createDailyQuickPick';

Expand Down Expand Up @@ -260,6 +260,11 @@ export function getMemoConfigProperty(
fallback: null | number,
): number;

export function getMemoConfigProperty(
property: 'links.rules',
fallback: null | Array<LinkRuleT>,
): LinkRuleT[];

export function getMemoConfigProperty(property: MemoBoolConfigProp, fallback: boolean): boolean;

export function getMemoConfigProperty<T>(property: string, fallback: T): T {
Expand Down

0 comments on commit 59081ba

Please sign in to comment.