Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: duplicate frontmatter (with new Obsidian API) #317

Merged
merged 1 commit into from
Feb 23, 2024
Merged

Conversation

Mara-Li
Copy link
Member

@Mara-Li Mara-Li commented Feb 23, 2024

Summary by CodeRabbit

  • Refactor
    • Improved the handling and parsing of YAML frontmatter in text processing functions for enhanced performance and reliability.
    • Enhanced error handling and notification mechanisms to provide better feedback during text conversion processes.

thanks to new Obsidian API, I can readd editing with regex on the frontmatter without duplicating it
Copy link

coderabbitai bot commented Feb 23, 2024

Walkthrough

The recent updates focus on enhancing the project's import structure and refining the YAML frontmatter processing. By relocating import statements and introducing a getFrontMatterInfo function, these changes streamline the handling of YAML within text conversions and bolster error management, ensuring a more robust and efficient codebase.

Changes

File Path Change Summary
.../GitHub/upload.ts Updated the import path for mainConverting.
.../compiler/embeds.ts Modified the import location for addToYaml.
.../conversion/index.ts Introduced getFrontMatterInfo and improved YAML frontmatter handling and error notifications.

🐇✨
In the heart of the code, where the rabbits play,
A change was made, oh what a day!
Imports moved, with grace and flair,
YAML tamed, with utmost care.
Now the code, so sleek and bright,
Runs with joy, from morning till night.
🌟📝

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 3

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 19a48ae and 440c991.
Files ignored due to path filters (2)
  • package.json is excluded by: !**/*.json
  • pnpm-lock.yaml is excluded by: !**/*.yaml
Files selected for processing (3)
  • src/GitHub/upload.ts (1 hunks)
  • src/conversion/compiler/embeds.ts (1 hunks)
  • src/conversion/index.ts (1 hunks)
Additional comments: 3
src/conversion/index.ts (1)
  • 137-150: The function inlineTags demonstrates a good approach to extracting and deduplicating tags from both inline metadata and frontmatter. A few points to note:
  • The use of metadataCache.getFileCache(file)?.tags and parseFrontMatterTags(frontmatter) to gather tags from different sources is a solid approach.
  • The replacement of "/" with "_" in tags (lines 143 and 148) is consistent and prevents potential issues with tag naming conventions.
  • The deduplication of tags using [...new Set([...inlineTagsInText, ...yamlTags])] is efficient and ensures that each tag is unique.

This function is well-implemented and follows best practices for handling tags in YAML frontmatter.

src/conversion/compiler/embeds.ts (1)
  • 25-25: The modification of the import statement for addToYaml to import from a different location suggests a reorganization of the project structure. This change is likely part of the broader refactoring effort mentioned in the PR objectives. It's important to ensure that the new import path is correct and that the addToYaml function is still accessible and functional within this file. Assuming the path has been verified and is correct, this change appears to be a straightforward adjustment to accommodate the project's evolving structure.
src/GitHub/upload.ts (1)
  • 15-15: The import statement for mainConverting has been updated to reflect a change in the project structure. This change is consistent with the PR's objective to refactor code and improve frontmatter handling. Ensure that all references to mainConverting throughout the project have been updated to match this new import path to avoid any import errors.
Verification successful

The review of the provided script outputs reveals that the mainConverting function is indeed defined in src/conversion/index.ts and is imported in src/GitHub/upload.ts using the updated path ../conversion. This confirms that the import statement for mainConverting has been correctly updated in src/GitHub/upload.ts to reflect the change in the project structure, as mentioned in the original review comment. Additionally, there are no indications of incorrect references to mainConverting in other parts of the project based on the script outputs provided. Therefore, the original review comment is verified to be accurate.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that all references to `mainConverting` have been updated.
rg --type ts 'mainConverting' --files-with-matches

Length of output: 95



Script:

#!/bin/bash
# Inspect the content of the files where `mainConverting` is referenced to verify the import paths.
cat src/conversion/index.ts
cat src/GitHub/upload.ts

Length of output: 25912

Comment on lines +100 to +122
export function addToYaml(text: string, toAdd: string[], plugin: GithubPublisher, folderNoteParaMeters: { properties: MultiProperties | null, file: TFile}): string {
const properties = folderNoteParaMeters?.properties;
const {contentStart, exists, frontmatter} = getFrontMatterInfo(text);
if (!properties || (!properties.plugin.settings.conversion.tags.inline && !properties.plugin.settings.upload.folderNote.addTitle))
return text;
const { settings } = plugin;
let yamlObject = parseYaml(exists ? frontmatter:"{}");
try {
if (yamlObject && toAdd.length > 0) {
yamlObject = tagsToYaml(toAdd, settings, yamlObject);
}
if (folderNoteParaMeters?.properties) {
yamlObject = titleToYaml(yamlObject, folderNoteParaMeters.properties, folderNoteParaMeters.file);
}
if (yamlObject && Object.keys(yamlObject).length > 0) {
return `---\n${stringifyYaml(yamlObject)}---\n${(exists ? text.slice(contentStart) : text)}`;
}
} catch (e) {
new Notice(i18next.t("error.parseYaml"));
return text; //not a valid yaml, skipping
}
new Notice(i18next.t("error.parseYaml"));
return text;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function addToYaml has been significantly refactored to improve the handling of YAML frontmatter. However, there are a few points to consider:

  • The use of parseYaml and stringifyYaml from the obsidian import ensures proper parsing and serialization of YAML content, which is good practice.
  • The error handling with try-catch blocks and the use of new Notice(i18next.t("error.parseYaml")); provides user feedback in case of parsing errors, enhancing the user experience.
  • The conditional checks and manipulation of yamlObject seem logical and aim to prevent duplicate tags and ensure proper YAML structure.

However, there's a potential issue with the error handling:

  • The new Notice(i18next.t("error.parseYaml")); is called twice (lines 118 and 121), once inside the catch block and once outside, regardless of whether an exception was thrown. This could lead to confusing user feedback since the notice will be shown even if there's no error. Consider removing the notice outside the catch block or adding a condition to ensure it's only shown when an actual error occurs.
- new Notice(i18next.t("error.parseYaml"));

Remove or conditionally execute the second notice to avoid confusion.


Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export function addToYaml(text: string, toAdd: string[], plugin: GithubPublisher, folderNoteParaMeters: { properties: MultiProperties | null, file: TFile}): string {
const properties = folderNoteParaMeters?.properties;
const {contentStart, exists, frontmatter} = getFrontMatterInfo(text);
if (!properties || (!properties.plugin.settings.conversion.tags.inline && !properties.plugin.settings.upload.folderNote.addTitle))
return text;
const { settings } = plugin;
let yamlObject = parseYaml(exists ? frontmatter:"{}");
try {
if (yamlObject && toAdd.length > 0) {
yamlObject = tagsToYaml(toAdd, settings, yamlObject);
}
if (folderNoteParaMeters?.properties) {
yamlObject = titleToYaml(yamlObject, folderNoteParaMeters.properties, folderNoteParaMeters.file);
}
if (yamlObject && Object.keys(yamlObject).length > 0) {
return `---\n${stringifyYaml(yamlObject)}---\n${(exists ? text.slice(contentStart) : text)}`;
}
} catch (e) {
new Notice(i18next.t("error.parseYaml"));
return text; //not a valid yaml, skipping
}
new Notice(i18next.t("error.parseYaml"));
return text;
export function addToYaml(text: string, toAdd: string[], plugin: GithubPublisher, folderNoteParaMeters: { properties: MultiProperties | null, file: TFile}): string {
const properties = folderNoteParaMeters?.properties;
const {contentStart, exists, frontmatter} = getFrontMatterInfo(text);
if (!properties || (!properties.plugin.settings.conversion.tags.inline && !properties.plugin.settings.upload.folderNote.addTitle))
return text;
const { settings } = plugin;
let yamlObject = parseYaml(exists ? frontmatter:"{}");
try {
if (yamlObject && toAdd.length > 0) {
yamlObject = tagsToYaml(toAdd, settings, yamlObject);
}
if (folderNoteParaMeters?.properties) {
yamlObject = titleToYaml(yamlObject, folderNoteParaMeters.properties, folderNoteParaMeters.file);
}
if (yamlObject && Object.keys(yamlObject).length > 0) {
return `---\n${stringifyYaml(yamlObject)}---\n${(exists ? text.slice(contentStart) : text)}`;
}
} catch (e) {
new Notice(i18next.t("error.parseYaml"));
return text; //not a valid yaml, skipping
}
return text;

Comment on lines +126 to +134
function titleToYaml(yaml: any, properties: MultiProperties, file: TFile) {
const settings = properties.plugin.settings.upload.folderNote.addTitle;
if (!settings) {
return yaml;
}
if (!yaml[settings.key] && isFolderNote(properties) && settings.enable) {
yaml[settings.key] = file.basename;
}
return yaml;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function titleToYaml correctly checks for the presence of a title key in the YAML frontmatter and adds it if missing, which is a useful feature for ensuring consistency in frontmatter across files. However, there's a minor improvement that could be made for clarity and maintainability:

  • The condition if (!yaml[settings.key] && isFolderNote(properties) && settings.enable) combines several checks in one line. While this is efficient, it might be beneficial for readability and future maintenance to separate these conditions, especially the isFolderNote(properties) check, which could have its result stored in a variable with a descriptive name.

Consider refactoring the condition for improved readability and maintainability.

@@ -12,7 +12,7 @@ import {
} from "obsidian";

import { convertToHTMLSVG } from "../conversion/compiler/excalidraw";
import { mainConverting } from "../conversion/convert_text";
import { mainConverting } from "../conversion";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given the comprehensive changes across multiple files, it's crucial to ensure that the updated import paths and refactored code do not introduce any regressions or break existing functionality. Consider adding or updating unit tests to cover the changes made in this PR, especially for critical functions like publish, uploadImage, and uploadText. This will help maintain the reliability of the system as it evolves.

Would you like assistance in creating or updating the unit tests to cover these changes?

@Mara-Li Mara-Li merged commit 39e100c into master Feb 23, 2024
4 checks passed
@Mara-Li Mara-Li deleted the frontmatter-api branch February 23, 2024 08:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant