Skip to content
This repository has been archived by the owner on Jul 1, 2024. It is now read-only.

feat: add inline metadata #15

Merged
merged 8 commits into from
Feb 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ repos:
entry: yamllint --strict --config-file .yamllint.yml

- repo: "https://github.com/charliermarsh/ruff-pre-commit"
rev: "v0.0.239"
rev: "v0.0.240"
hooks:
- id: ruff
args: ["--extend-ignore", "I001,D301,D401,PLR2004,PLR0913"]
Expand Down
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Once installed, run `obsidian-metadata` in your terminal to enter an interactive
**Add Metadata**: Add new metadata to your vault.

- Add metadata to the frontmatter
- Add to inline metadata (Not yet implemented)
- Add to inline metadata - Set `insert_location` in the config to control where the new metadata is inserted. (Default: Bottom)
- Add to inline tag (Not yet implemented)

**Rename Metadata**: Rename either a key and all associated values, a specific value within a key. or an in-text tag.
Expand Down Expand Up @@ -103,9 +103,16 @@ Below is an example with two vaults.
# Folders within the vault to ignore when indexing metadata
exclude_paths = [".git", ".obsidian"]

# Location to add metadata. One of:
# TOP: Directly after frontmatter.
# AFTER_TITLE: After a header following frontmatter.
# BOTTOM: The bottom of the note
insert_location = "BOTTOM"

["Vault Two"]
path = "/path/to/second_vault"
exclude_paths = [".git", ".obsidian"]
exclude_paths = [".git", ".obsidian", "daily_notes"]
insert_location = "AFTER_TITLE"
```

To bypass the configuration file and specify a vault to use at runtime use the `--vault-path` option.
Expand Down
10 changes: 5 additions & 5 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@
]
ignore-init-module-imports = true
line-length = 100
per-file-ignores = { "cli.py" = ["PLR0913"] }
per-file-ignores = { "cli.py" = [
"PLR0913",
], "tests/*.py" = [
"E999",
"PLR2004",
] }
select = [
"A",
"B",
Expand Down
70 changes: 43 additions & 27 deletions src/obsidian_metadata/_config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@
class ConfigQuestions:
"""Questions to ask the user when creating a configuration file."""

@staticmethod
def _validate_valid_dir(path: str) -> bool | str:
"""Validate a valid directory.

Returns:
bool | str: True if the path is valid, otherwise a string with the error message.
"""
path_to_validate: Path = Path(path).expanduser().resolve()
if not path_to_validate.exists():
return f"Path does not exist: {path_to_validate}"
if not path_to_validate.is_dir():
return f"Path is not a directory: {path_to_validate}"

return True

@staticmethod
def ask_for_vault_path() -> Path: # pragma: no cover
"""Ask the user for the path to their vault.
Expand All @@ -34,21 +49,6 @@ def ask_for_vault_path() -> Path: # pragma: no cover

return Path(vault_path).expanduser().resolve()

@staticmethod
def _validate_valid_dir(path: str) -> bool | str:
"""Validate a valid directory.

Returns:
bool | str: True if the path is valid, otherwise a string with the error message.
"""
path_to_validate: Path = Path(path).expanduser().resolve()
if not path_to_validate.exists():
return f"Path does not exist: {path_to_validate}"
if not path_to_validate.is_dir():
return f"Path is not a directory: {path_to_validate}"

return True


@rich.repr.auto
class Config:
Expand All @@ -65,7 +65,11 @@ def __init__(self, config_path: Path = None, vault_path: Path = None) -> None:
else:
self.config_path = None
self.config = {
"command_line_vault": {"path": vault_path, "exclude_paths": [".git", ".obsidian"]}
"command_line_vault": {
"path": vault_path,
"exclude_paths": [".git", ".obsidian"],
"insert_location": "BOTTOM",
}
}

try:
Expand All @@ -84,6 +88,15 @@ def __rich_repr__(self) -> rich.repr.Result: # pragma: no cover
yield "config_path", self.config_path
yield "vaults", self.vaults

def _load_config(self) -> dict[str, Any]:
"""Load the configuration file."""
try:
with open(self.config_path, encoding="utf-8") as fp:
return tomlkit.load(fp)
except tomlkit.exceptions.TOMLKitError as e:
alerts.error(f"Could not parse '{self.config_path}'")
raise typer.Exit(code=1) from e

def _validate_config_path(self, config_path: Path | None) -> Path:
"""Load the configuration path."""
if config_path is None:
Expand All @@ -95,15 +108,6 @@ def _validate_config_path(self, config_path: Path | None) -> Path:

return config_path.expanduser().resolve()

def _load_config(self) -> dict[str, Any]:
"""Load the configuration file."""
try:
with open(self.config_path, encoding="utf-8") as fp:
return tomlkit.load(fp)
except tomlkit.exceptions.TOMLKitError as e:
alerts.error(f"Could not parse '{self.config_path}'")
raise typer.Exit(code=1) from e

def _write_default_config(self, path_to_config: Path) -> None:
"""Write the default configuration file when no config file is found."""
vault_path = ConfigQuestions.ask_for_vault_path()
Expand All @@ -116,7 +120,14 @@ def _write_default_config(self, path_to_config: Path) -> None:
path = "{vault_path}"

# Folders within the vault to ignore when indexing metadata
exclude_paths = [".git", ".obsidian"]"""
exclude_paths = [".git", ".obsidian"]

# Location to add metadata. One of:
# TOP: Directly after frontmatter.
# AFTER_TITLE: After a header following frontmatter.
# BOTTOM: The bottom of the note
insert_location = "BOTTOM"
"""

path_to_config.write_text(dedent(config_text))

Expand All @@ -140,7 +151,12 @@ def __init__(self, vault_name: str, vault_config: dict) -> None:
try:
self.exclude_paths = self.config["exclude_paths"]
except KeyError:
self.exclude_paths = []
self.exclude_paths = [".git", ".obsidian"]

try:
self.insert_location = self.config["insert_location"]
except KeyError:
self.insert_location = "BOTTOM"

def __rich_repr__(self) -> rich.repr.Result: # pragma: no cover
"""Define rich representation of a vault config."""
Expand Down
3 changes: 2 additions & 1 deletion src/obsidian_metadata/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ def main(
[bold underline]Add Metadata[/]
Add new metadata to your vault.
• Add metadata to the frontmatter
• [dim]Add to inline metadata (Not yet implemented)[/]
• Add to inline metadata - Set `insert_location` in the config to
control where the new metadata is inserted. (Default: Bottom)
• [dim]Add to inline tag (Not yet implemented)[/]

[bold underline]Rename Metadata[/]
Expand Down
9 changes: 7 additions & 2 deletions src/obsidian_metadata/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"""Shared models."""
from obsidian_metadata.models.enums import MetadataType # isort: skip
from obsidian_metadata.models.enums import (
InsertLocation,
MetadataType,
)

from obsidian_metadata.models.patterns import Patterns # isort: skip
from obsidian_metadata.models.metadata import (
Frontmatter,
Expand All @@ -17,11 +21,12 @@
"Frontmatter",
"InlineMetadata",
"InlineTags",
"InsertLocation",
"LoggerManager",
"MetadataType",
"Note",
"Patterns",
"Vault",
"VaultMetadata",
"VaultFilter",
"VaultMetadata",
]
Loading