Skip to content

Commit

Permalink
Add tests; fix eslint violations
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan-lednev committed Mar 14, 2023
1 parent b3ac535 commit 0bcfafa
Show file tree
Hide file tree
Showing 8 changed files with 88 additions and 36 deletions.
2 changes: 2 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,7 @@ module.exports = {
"`with` is disallowed in strict mode because it makes code impossible to predict and optimize.",
},
],
"import/prefer-default-export": "off",
"import/no-default-export": "error",
},
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
"install": "^0.13.0",
"jest": "^27.0.6",
"lint-staged": "^13.1.2",
"lodash": "^4.17.21",
"moment": "^2.29.1",
"obsidian": "^0.12.0",
"prettier": "^2.5.1",
Expand All @@ -60,6 +59,7 @@
},
"dependencies": {
"babel-preset-solid": "^1.6.10",
"lodash": "^4.17.21",
"solid-js": "^1.6.11"
},
"lint-staged": {
Expand Down
45 changes: 20 additions & 25 deletions src/features/ArchiveFeature.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { Editor, TFile, Vault, Workspace } from "obsidian";

import { dropRight, first, flow, isEmpty } from "lodash";
import { groupBy, map, mapValues, toPairs } from "lodash/fp";
import { dropRight, flow, groupBy, isEmpty, map, mapValues, toPairs } from "lodash/fp";

import { ActiveFile, DiskFile, EditorFile } from "../ActiveFile";
import { DEFAULT_DATE_FORMAT } from "../Constants";
import { Rule, Settings } from "../Settings";
import { Block } from "../model/Block";
import { RootBlock } from "../model/RootBlock";
Expand All @@ -24,7 +22,6 @@ import {
buildIndentation,
deepExtractBlocks,
extractBlocksRecursively,
findSection,
findSectionRecursively,
shallowExtractBlocks,
} from "../util/Util";
Expand Down Expand Up @@ -55,6 +52,16 @@ export interface BlockWithRule {
rule?: Rule;
}

// todo: move to parsing
function getTaskStatus(task: Block) {
const [, taskStatus] = task.text.match(/\[(.)]/);
return taskStatus;
}

function completeTask(task: string) {
return task.replace("[ ]", "[x]");
}

export class ArchiveFeature {
private readonly taskFilter: TreeFilter;

Expand All @@ -80,14 +87,11 @@ export class ArchiveFeature {
}

async archiveShallowTasksInActiveFile(file: ActiveFile) {
return await this.extractAndArchiveTasksInActiveFile(
file,
shallowExtractBlocks
);
return this.extractAndArchiveTasksInActiveFile(file, shallowExtractBlocks);
}

async archiveDeepTasksInActiveFile(file: ActiveFile) {
return await this.extractAndArchiveTasksInActiveFile(file, deepExtractBlocks);
return this.extractAndArchiveTasksInActiveFile(file, deepExtractBlocks);
}

async archiveTaskUnderCursor(editor: Editor) {
Expand All @@ -104,7 +108,7 @@ export class ArchiveFeature {
const parsedTaskRoot = this.parser.parse(thisTaskLines);
const parsedTaskBlock = parsedTaskRoot.blockContent.children[0];
// todo: tidy up
parsedTaskBlock.text = this.completeTask(parsedTaskBlock.text);
parsedTaskBlock.text = completeTask(parsedTaskBlock.text);
const activeFile = new EditorFile(editor);

await this.archiveTasks(
Expand All @@ -116,10 +120,6 @@ export class ArchiveFeature {
editor.setCursor(thisTaskStart);
}

private completeTask(task: string) {
return task.replace("[ ]", "[x]");
}

private getDefaultRule() {
return {
archiveToSeparateFile: this.settings.archiveToSeparateFile,
Expand All @@ -139,7 +139,7 @@ export class ArchiveFeature {
task,
rule:
this.settings.rules.find((rule) =>
rule.statuses.includes(this.getTaskStatus(task))
rule.statuses.includes(getTaskStatus(task))
) || this.getDefaultRule(),
}));

Expand Down Expand Up @@ -180,7 +180,7 @@ export class ArchiveFeature {
rule,
task: this.textReplacementService.replaceText(task),
}),
(taskWithRule) => this.metadataService.appendMetadata(taskWithRule),
this.metadataService.appendMetadata,
({ rule, task }: BlockWithRule) => ({
task,
archivePath: rule.archiveToSeparateFile
Expand Down Expand Up @@ -209,12 +209,6 @@ export class ArchiveFeature {
)(tasks);
}

// todo: move to parsing
private getTaskStatus(task: Block) {
const [, taskStatus] = task.text.match(/\[(.)]/);
return taskStatus;
}

private async getArchiveFile(activeFile: ActiveFile) {
if (!this.settings.archiveToSeparateFile) {
return activeFile;
Expand All @@ -238,6 +232,7 @@ export class ArchiveFeature {

private async editFileTree(file: ActiveFile, cb: TreeEditorCallback) {
const tree = this.parser.parse(await file.readLines());
// todo: mutation
cb(tree);
await file.writeLines(this.stringifyTree(tree));
}
Expand Down Expand Up @@ -294,7 +289,7 @@ export class ArchiveFeature {
for (
let headingIndex = 0;
headingIndex < resolvedHeadings.length;
headingIndex++
headingIndex += 1
) {
const headingTextToSearchFor = resolvedHeadings[headingIndex];
const existingHeading = findSectionRecursively(
Expand All @@ -305,7 +300,7 @@ export class ArchiveFeature {
if (existingHeading === null) {
const tokenLevel = headingIndex + this.settings.archiveHeadingDepth;
const newSection = new Section(
" " + headingTextToSearchFor, // todo: do not manage spaces manually
` ${headingTextToSearchFor}`, // todo: do not manage spaces manually
tokenLevel,
new RootBlock()
);
Expand Down Expand Up @@ -351,7 +346,7 @@ export class ArchiveFeature {
const pathNodes = path.split(pathSeparator);
const pathContainsFolders = pathNodes.length > 1;
if (pathContainsFolders) {
const folderPath = dropRight(pathNodes).join(pathSeparator);
const folderPath = dropRight(1, pathNodes).join(pathSeparator);
const existingFolder = this.vault.getAbstractFileByPath(folderPath);
if (!existingFolder) {
await this.vault.createFolder(folderPath);
Expand Down
62 changes: 58 additions & 4 deletions src/features/__tests__/ArchiveFeature.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -506,7 +506,7 @@ describe("Sort orders", () => {

describe("Rules", () => {
test("A single task gets archived to a different file", async () => {
const deferredArchive = createTFile({ state: [], path: "deferred.md" });
const deferredArchive = createTFile({ path: "deferred.md" });

const { mockActiveFile } = await archiveTasks(["- [>] foo", "- [ ] bar"], {
settings: {
Expand All @@ -527,8 +527,8 @@ describe("Rules", () => {
});

test("Different files", async () => {
const deferredArchive = createTFile({ state: [], path: "deferred.md" });
const cancelledArchive = createTFile({ state: [], path: "cancelled.md" });
const deferredArchive = createTFile({ path: "deferred.md" });
const cancelledArchive = createTFile({ path: "cancelled.md" });

await archiveTasks(
["- [>] foo", "- [-] cancelled", "- [-] another one cancelled"],
Expand Down Expand Up @@ -564,7 +564,7 @@ describe("Rules", () => {
});

test("Custom date format in file name", async () => {
const deferredArchive = createTFile({ state: [], path: "2021-deferred.md" });
const deferredArchive = createTFile({ path: "2021-deferred.md" });

await archiveTasks(["- [>] foo", "- [ ] bar"], {
settings: {
Expand Down Expand Up @@ -795,3 +795,57 @@ describe("Building a list item chain", () => {
);
});
});

describe("obsidian-tasks dates", () => {
test("Get resolved in headings", async () => {
await archiveTasksAndCheckActiveFile(
["- [x] foo ✅ 2023-01-01"],
["", "# 2023-01-01", "", "- [x] foo ✅ 2023-01-01", ""],
{
settings: {
...DEFAULT_SETTINGS_FOR_TESTS,
headings: [
{
text: "{{obsidianTasksCompletedDate}}",
// obsidianTasksCompletedDateFormat: DEFAULT_DATE_FORMAT,
},
],
},
}
);
});

test("Get resolved in file names", async () => {
const fileWithDate = createTFile({ path: "2023-01-01.md" });

const { vault } = await archiveTasks(["- [x] foo ✅ 2023-01-01"], {
settings: {
...DEFAULT_SETTINGS_FOR_TESTS,
archiveUnderHeading: false,
archiveToSeparateFile: true,
defaultArchiveFileName: "{{obsidianTasksCompletedDate}}",
},
vaultFiles: [fileWithDate],
});

expect(fileWithDate.state).toEqual("", "- [x] foo ✅ 2023-01-01", "");
});

test("Work with custom formats", async () => {
await archiveTasksAndCheckActiveFile(
["- [x] foo ✅ 2023-01-01"],
["", "# 2023", "", "- [x] foo ✅ 2023-01-01", ""],
{
settings: {
...DEFAULT_SETTINGS_FOR_TESTS,
headings: [
{
text: "{{obsidianTasksCompletedDate}}",
obsidianTasksCompletedDateFormat: "YYYY",
},
],
},
}
);
});
});
5 changes: 4 additions & 1 deletion src/features/__tests__/test-util/ArchiveFeatureUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,13 @@ export async function archiveTasksAndCheckMessage(activeFileState, expectedMessa
export async function archiveTasksAndCheckActiveFile(
activeFileState,
expectedActiveFileState,
{ settings = DEFAULT_SETTINGS_FOR_TESTS } = { settings: DEFAULT_SETTINGS_FOR_TESTS }
{ settings = DEFAULT_SETTINGS_FOR_TESTS, vaultFiles = [] } = {
settings: DEFAULT_SETTINGS_FOR_TESTS,
}
) {
const { mockActiveFile } = await archiveTasks(activeFileState, {
settings,
vaultFiles,
});

expect(mockActiveFile.state).toEqual(expectedActiveFileState);
Expand Down
2 changes: 1 addition & 1 deletion src/features/__tests__/test-util/TestUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class TestDependencies {
}

// This is needed to pass `instanceof` checks
export function createTFile({ state, path }) {
export function createTFile({ state = [], path }) {
return Object.assign(new TFile(), {
// todo: move to variable
basename: "mock-file-base-name",
Expand Down
4 changes: 2 additions & 2 deletions src/services/MetadataService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class MetadataService {
private readonly settings: Settings
) {}

appendMetadata({ task, rule }: BlockWithRule) {
appendMetadata = ({ task, rule }: BlockWithRule) => {
if (!this.settings.additionalMetadataBeforeArchiving.addMetadata) {
return { task, rule };
}
Expand All @@ -27,5 +27,5 @@ export class MetadataService {

task.text = `${task.text} ${resolvedMetadata}`;
return { task, rule };
}
};
}
2 changes: 0 additions & 2 deletions src/settings-ui/components/ListItemsSettings.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { partial } from "lodash";

import { DateFormatDescription } from "./DateFormatDescription";
import { useSettingsContext } from "./context/SettingsProvider";
import { BaseSetting } from "./setting/BaseSetting";
Expand Down

0 comments on commit 0bcfafa

Please sign in to comment.