initial
This commit is contained in:
commit
3d122b5022
8 files changed
+1065
No files matched your search
@@ -0,0 +1,168 @@
|
|||||||
|
# Onyx Python Helper
|
||||||
|
|
||||||
|
A Python-based command-line interface tool for interacting with Obsidian vaults. This tool allows you to manage your Obsidian notes directly from the terminal.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
1. Clone this repository
|
||||||
|
2. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
### Set Default Vault
|
||||||
|
|
||||||
|
First, you need to set up your vault with both its name and path:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Set up a new vault with its path (required for first use)
|
||||||
|
ob-cli set-default "vault-name" --path "/path/to/vault"
|
||||||
|
|
||||||
|
# Print current default vault and its path
|
||||||
|
ob-cli print-default
|
||||||
|
|
||||||
|
# Switch to another existing vault (only works for already configured vaults)
|
||||||
|
ob-cli set-default "another-vault"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Open Notes
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Open a note in Obsidian
|
||||||
|
python src/obsidian_cli.py open "note-name"
|
||||||
|
|
||||||
|
# Open a note in specific vault
|
||||||
|
python src/obsidian_cli.py open "note-name" --vault "vault-name"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Daily Notes
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create and open today's daily note
|
||||||
|
python src/obsidian_cli.py daily
|
||||||
|
|
||||||
|
# Create daily note in specific vault
|
||||||
|
python src/obsidian_cli.py daily --vault "vault-name"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Create/Update Notes
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Create a new note
|
||||||
|
python src/obsidian_cli.py create "note-name"
|
||||||
|
|
||||||
|
# Create note with content
|
||||||
|
python src/obsidian_cli.py create "note-name" --content "Your content here"
|
||||||
|
|
||||||
|
# Create note in specific vault
|
||||||
|
python src/obsidian_cli.py create "note-name" --vault "vault-name"
|
||||||
|
|
||||||
|
# Overwrite existing note
|
||||||
|
python src/obsidian_cli.py create "note-name" --content "New content" --overwrite
|
||||||
|
|
||||||
|
# Append to existing note
|
||||||
|
python src/obsidian_cli.py create "note-name" --content "Additional content" --append
|
||||||
|
|
||||||
|
# Create and open note
|
||||||
|
python src/obsidian_cli.py create "note-name" --content "content" --open
|
||||||
|
```
|
||||||
|
|
||||||
|
### View Notes
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Print note contents
|
||||||
|
python src/obsidian_cli.py print-note "note-name"
|
||||||
|
|
||||||
|
# Print note from specific vault
|
||||||
|
python src/obsidian_cli.py print-note "note-name" --vault "vault-name"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Move/Rename Notes
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Move/rename a note
|
||||||
|
python src/obsidian_cli.py move "old-path" "new-path"
|
||||||
|
|
||||||
|
# Move in specific vault
|
||||||
|
python src/obsidian_cli.py move "old-path" "new-path" --vault "vault-name"
|
||||||
|
|
||||||
|
# Move and open note
|
||||||
|
python src/obsidian_cli.py move "old-path" "new-path" --open
|
||||||
|
```
|
||||||
|
|
||||||
|
### Delete Notes
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Delete a note
|
||||||
|
python src/obsidian_cli.py delete "note-path"
|
||||||
|
|
||||||
|
# Delete from specific vault
|
||||||
|
python src/obsidian_cli.py delete "note-path" --vault "vault-name"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontmatter Management
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Edit frontmatter
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --edit --key "tags" --value "project"
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --edit --key "tags" --value "project,urgent"
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --edit --key "status" --value "in-progress"
|
||||||
|
|
||||||
|
# View frontmatter
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --view --key "tags"
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --view --key "tags" --value "project"
|
||||||
|
|
||||||
|
# Clear frontmatter values
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --clear --key "tags"
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --clear --key "date,status,tags"
|
||||||
|
|
||||||
|
# Delete frontmatter keys
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --delete --key "tags"
|
||||||
|
python src/obsidian_cli.py frontmatter "note-name" --delete --key "date,status,tags"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
The tool now includes all major features from the original Obsidian CLI tool:
|
||||||
|
- Set and manage default vault
|
||||||
|
- Open notes in Obsidian
|
||||||
|
- Create and manage daily notes
|
||||||
|
- Create/update notes with content
|
||||||
|
- Print note contents
|
||||||
|
- Move/rename notes (with automatic link updates)
|
||||||
|
- Delete notes
|
||||||
|
- Complete frontmatter management (edit, view, clear, delete)
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Python 3.7+
|
||||||
|
- click
|
||||||
|
- pyyaml
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Running Tests
|
||||||
|
|
||||||
|
To run the tests:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install test dependencies
|
||||||
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# Run tests
|
||||||
|
python -m pytest
|
||||||
|
|
||||||
|
# Run tests with coverage report
|
||||||
|
python -m pytest --cov=src tests/
|
||||||
|
```
|
||||||
|
|
||||||
|
The test suite includes tests for:
|
||||||
|
- Vault management
|
||||||
|
- Note creation and modification
|
||||||
|
- Frontmatter operations
|
||||||
|
- Note movement and link updates
|
||||||
|
- Daily notes
|
||||||
|
- Platform-specific note opening
|
||||||
|
- Note deletion
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
[tool.pytest]
|
||||||
|
testpaths = ["tests"]
|
||||||
|
python_files = ["test_*.py"]
|
||||||
|
python_classes = ["Test*"]
|
||||||
|
python_functions = ["test_*"]
|
||||||
|
|
||||||
|
[tool.coverage.run]
|
||||||
|
source = ["src"]
|
||||||
|
omit = ["tests/*"]
|
||||||
|
|
||||||
|
[tool.coverage.report]
|
||||||
|
exclude_lines = [
|
||||||
|
"pragma: no cover",
|
||||||
|
"def __repr__",
|
||||||
|
"if self.debug:",
|
||||||
|
"raise NotImplementedError",
|
||||||
|
"if __name__ == .__main__.:",
|
||||||
|
"pass",
|
||||||
|
"raise ImportError",
|
||||||
|
]
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
click==8.1.7
|
||||||
|
pyyaml==6.0.1
|
||||||
|
pytest==7.4.3
|
||||||
|
pytest-cov==4.1.0
|
||||||
Binary file not shown.
@@ -0,0 +1,675 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
import click
|
||||||
|
import os
|
||||||
|
import yaml
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
from typing import List, Union, Optional, Dict, Any
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
class OnyxCLI:
|
||||||
|
def __init__(self):
|
||||||
|
self.config_file = Path.home() / '.onyx-cli' / 'config.yaml'
|
||||||
|
self._ensure_config_exists()
|
||||||
|
self.default_vault = self._load_default_vault()
|
||||||
|
if self.default_vault:
|
||||||
|
try:
|
||||||
|
self.vault_path = self._get_vault_path(self.default_vault)
|
||||||
|
except click.UsageError:
|
||||||
|
# Vault is set but not configured - will be handled by commands
|
||||||
|
self.vault_path = None
|
||||||
|
else:
|
||||||
|
self.vault_path = None
|
||||||
|
|
||||||
|
def _ensure_config_exists(self):
|
||||||
|
self.config_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if not self.config_file.exists():
|
||||||
|
self.config_file.write_text(yaml.dump({'default_vault': None, 'vaults': {}}))
|
||||||
|
|
||||||
|
def _load_default_vault(self):
|
||||||
|
if self.config_file.exists():
|
||||||
|
config = yaml.safe_load(self.config_file.read_text())
|
||||||
|
return config.get('default_vault')
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _get_vault_path(self, vault_name: str) -> Path:
|
||||||
|
config = yaml.safe_load(self.config_file.read_text())
|
||||||
|
vault_path = config.get('vaults', {}).get(vault_name)
|
||||||
|
if not vault_path:
|
||||||
|
raise click.UsageError(f"Vault '{vault_name}' not found in config")
|
||||||
|
return Path(vault_path)
|
||||||
|
|
||||||
|
def _get_vault_and_path(self, vault: Optional[str] = None) -> tuple[str, Path]:
|
||||||
|
vault_name = vault or self.default_vault
|
||||||
|
if not vault_name:
|
||||||
|
raise click.UsageError("No vault specified. Either set a default vault or provide --vault option")
|
||||||
|
vault_path = self._get_vault_path(vault_name)
|
||||||
|
return vault_name, vault_path
|
||||||
|
|
||||||
|
def _get_daily_note_settings(self, vault_path: Path) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Get daily note settings from Periodic Notes plugin (if enabled),
|
||||||
|
falling back to core Daily Notes plugin if not available.
|
||||||
|
|
||||||
|
Returns a dict with: format, folder, template
|
||||||
|
"""
|
||||||
|
# Try Periodic Notes plugin first
|
||||||
|
periodic_notes_config = vault_path / ".obsidian" / "plugins" / "periodic-notes" / "data.json"
|
||||||
|
if periodic_notes_config.exists():
|
||||||
|
try:
|
||||||
|
config = json.loads(periodic_notes_config.read_text())
|
||||||
|
daily_config = config.get('daily', {})
|
||||||
|
|
||||||
|
# Check if daily notes are enabled in Periodic Notes
|
||||||
|
if daily_config.get('enabled', False):
|
||||||
|
return {
|
||||||
|
'format': daily_config.get('format', 'YYYY-MM-DD'),
|
||||||
|
'folder': daily_config.get('folder', ''),
|
||||||
|
'template': daily_config.get('template', '')
|
||||||
|
}
|
||||||
|
except (json.JSONDecodeError, KeyError):
|
||||||
|
pass # Fall through to core plugin
|
||||||
|
|
||||||
|
# Fall back to core Daily Notes plugin
|
||||||
|
daily_notes_config = vault_path / ".obsidian" / "daily-notes.json"
|
||||||
|
if daily_notes_config.exists():
|
||||||
|
try:
|
||||||
|
config = json.loads(daily_notes_config.read_text())
|
||||||
|
return {
|
||||||
|
'format': config.get('format', 'YYYY-MM-DD'),
|
||||||
|
'folder': config.get('folder', ''),
|
||||||
|
'template': config.get('template', '')
|
||||||
|
}
|
||||||
|
except (json.JSONDecodeError, KeyError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Default settings if neither plugin is configured
|
||||||
|
return {
|
||||||
|
'format': 'YYYY-MM-DD',
|
||||||
|
'folder': '',
|
||||||
|
'template': ''
|
||||||
|
}
|
||||||
|
|
||||||
|
def set_default_vault(self, vault_name: str, vault_path: str = None):
|
||||||
|
try:
|
||||||
|
config = yaml.safe_load(self.config_file.read_text()) if self.config_file.exists() else {}
|
||||||
|
except Exception:
|
||||||
|
config = {}
|
||||||
|
|
||||||
|
config.setdefault('vaults', {})
|
||||||
|
|
||||||
|
if vault_path is not None:
|
||||||
|
# If path is provided, always update or create the vault entry
|
||||||
|
try:
|
||||||
|
resolved_path = Path(vault_path).resolve()
|
||||||
|
if not resolved_path.exists():
|
||||||
|
click.echo(f"Creating vault directory: {resolved_path}")
|
||||||
|
resolved_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
config['vaults'][vault_name] = str(resolved_path)
|
||||||
|
except Exception as e:
|
||||||
|
raise click.UsageError(f"Error setting vault path: {str(e)}")
|
||||||
|
elif vault_name not in config['vaults']:
|
||||||
|
# If no path and vault doesn't exist, show error
|
||||||
|
raise click.UsageError(
|
||||||
|
f"Vault '{vault_name}' not found. Please provide the path when setting a new vault:\n"
|
||||||
|
f"ob-cli set-default \"{vault_name}\" --path \"path/to/vault\""
|
||||||
|
)
|
||||||
|
|
||||||
|
config['default_vault'] = vault_name
|
||||||
|
self.config_file.write_text(yaml.dump(config))
|
||||||
|
self.default_vault = vault_name
|
||||||
|
|
||||||
|
actual_path = config['vaults'][vault_name]
|
||||||
|
click.echo(f"Default vault set to: {vault_name}")
|
||||||
|
click.echo(f"Vault path: {actual_path}")
|
||||||
|
|
||||||
|
def print_default(self):
|
||||||
|
if not self.default_vault:
|
||||||
|
click.echo("No default vault set")
|
||||||
|
return
|
||||||
|
|
||||||
|
config = yaml.safe_load(self.config_file.read_text())
|
||||||
|
vault_path = config.get('vaults', {}).get(self.default_vault)
|
||||||
|
|
||||||
|
if not vault_path:
|
||||||
|
raise click.UsageError(
|
||||||
|
f"Vault '{self.default_vault}' not found in config. Please set it up with:\n"
|
||||||
|
f"ob-cli set-default \"{self.default_vault}\" --path \"path/to/vault\""
|
||||||
|
)
|
||||||
|
|
||||||
|
click.echo(f"Default vault: {self.default_vault}")
|
||||||
|
click.echo(f"Path: {vault_path}")
|
||||||
|
|
||||||
|
def create_note(self, note_name: str, content: str = "", vault: str = None,
|
||||||
|
overwrite: bool = False, append: bool = False, open_after: bool = False):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
note_path = vault_path / note_name
|
||||||
|
if not note_path.suffix:
|
||||||
|
note_path = note_path.with_suffix('.md')
|
||||||
|
|
||||||
|
note_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
if note_path.exists():
|
||||||
|
if overwrite:
|
||||||
|
mode = 'w'
|
||||||
|
elif append:
|
||||||
|
mode = 'a'
|
||||||
|
else:
|
||||||
|
raise click.UsageError(f"Note {note_name} already exists. Use --overwrite or --append to modify")
|
||||||
|
else:
|
||||||
|
mode = 'w'
|
||||||
|
|
||||||
|
with note_path.open(mode) as f:
|
||||||
|
if append and note_path.exists():
|
||||||
|
f.write('\n')
|
||||||
|
f.write(content)
|
||||||
|
|
||||||
|
click.echo(f"Note {'updated' if note_path.exists() else 'created'}: {note_path}")
|
||||||
|
|
||||||
|
if open_after:
|
||||||
|
self.open_note(note_name, vault_name)
|
||||||
|
|
||||||
|
def open_note(self, note_name: str, vault: str = None):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
|
||||||
|
# Try exact path first
|
||||||
|
note_path = vault_path / note_name
|
||||||
|
if not note_path.suffix:
|
||||||
|
note_path = note_path.with_suffix('.md')
|
||||||
|
|
||||||
|
# If not found, try in daily notes folder if configured
|
||||||
|
# if not note_path.exists():
|
||||||
|
# settings = self._get_daily_note_settings(vault_path)
|
||||||
|
# if settings['folder']:
|
||||||
|
# daily_note_path = vault_path / settings['folder'] / f"{note_name}.md"
|
||||||
|
# if daily_note_path.exists():
|
||||||
|
# note_path = daily_note_path
|
||||||
|
|
||||||
|
# If still not found, try searching the entire vault
|
||||||
|
if not note_path.exists():
|
||||||
|
matches = list(vault_path.rglob(f"{note_name}.md"))
|
||||||
|
if matches:
|
||||||
|
note_path = matches[0] # Use first match
|
||||||
|
|
||||||
|
if not note_path.exists():
|
||||||
|
raise click.UsageError(f"Note {note_name} does not exist")
|
||||||
|
|
||||||
|
# Get the relative path from the vault root for the URI
|
||||||
|
relative_path = note_path.relative_to(vault_path)
|
||||||
|
# URL encode both the vault name and file path to handle special characters
|
||||||
|
encoded_vault = self._url_encode(vault_name)
|
||||||
|
encoded_file = self._url_encode(relative_path.as_posix())
|
||||||
|
uri = f"obsidian://open?vault={encoded_vault}&file={encoded_file}"
|
||||||
|
self._open_uri(uri)
|
||||||
|
|
||||||
|
def _convert_moment_format(self, moment_format: str) -> str:
|
||||||
|
"""Convert moment.js date format to Python strftime format."""
|
||||||
|
# Handle literal text in brackets first (e.g., [W] -> W)
|
||||||
|
result = re.sub(r'\[([^\]]+)\]', r'\1', moment_format)
|
||||||
|
|
||||||
|
# Use non-printable placeholders to avoid conflicts
|
||||||
|
# Order matters: process longest patterns first
|
||||||
|
placeholders = [
|
||||||
|
('YYYY', '\x001'),
|
||||||
|
('MMMM', '\x002'),
|
||||||
|
('dddd', '\x003'),
|
||||||
|
('MMM', '\x004'),
|
||||||
|
('ddd', '\x005'),
|
||||||
|
('Do', '\x006'),
|
||||||
|
('YY', '\x007'),
|
||||||
|
('MM', '\x008'),
|
||||||
|
('DD', '\x009'),
|
||||||
|
('HH', '\x00A'),
|
||||||
|
('hh', '\x00B'),
|
||||||
|
('mm', '\x00C'),
|
||||||
|
('ss', '\x00D'),
|
||||||
|
('M', '\x00E'),
|
||||||
|
('D', '\x00F'),
|
||||||
|
('H', '\x010'),
|
||||||
|
('h', '\x011'),
|
||||||
|
('A', '\x012'),
|
||||||
|
('a', '\x013'),
|
||||||
|
]
|
||||||
|
|
||||||
|
strftime_codes = {
|
||||||
|
'\x001': '%Y',
|
||||||
|
'\x007': '%y',
|
||||||
|
'\x002': '%B',
|
||||||
|
'\x004': '%b',
|
||||||
|
'\x008': '%m',
|
||||||
|
'\x00E': '%m',
|
||||||
|
'\x009': '%d',
|
||||||
|
'\x00F': '%d',
|
||||||
|
'\x006': '%d',
|
||||||
|
'\x003': '%A',
|
||||||
|
'\x005': '%a',
|
||||||
|
'\x00A': '%H',
|
||||||
|
'\x010': '%H',
|
||||||
|
'\x00B': '%I',
|
||||||
|
'\x011': '%I',
|
||||||
|
'\x00C': '%M',
|
||||||
|
'\x00D': '%S',
|
||||||
|
'\x012': '%p',
|
||||||
|
'\x013': '%p',
|
||||||
|
}
|
||||||
|
|
||||||
|
# First pass: replace moment patterns with placeholders
|
||||||
|
for moment_pattern, placeholder in placeholders:
|
||||||
|
result = result.replace(moment_pattern, placeholder)
|
||||||
|
|
||||||
|
# Second pass: replace placeholders with strftime codes
|
||||||
|
for placeholder, strftime_code in strftime_codes.items():
|
||||||
|
result = result.replace(placeholder, strftime_code)
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
def _create_or_open_periodic_note(self, note_type: str, vault: str = None):
|
||||||
|
"""Generic method to create or open periodic notes."""
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
|
||||||
|
# Get settings from plugin
|
||||||
|
settings = self._get_daily_note_settings(vault_path)
|
||||||
|
|
||||||
|
# Load periodic notes settings if available
|
||||||
|
periodic_notes_config = vault_path / ".obsidian" / "plugins" / "periodic-notes" / "data.json"
|
||||||
|
if periodic_notes_config.exists():
|
||||||
|
try:
|
||||||
|
config = json.loads(periodic_notes_config.read_text())
|
||||||
|
note_config = config.get(note_type, {})
|
||||||
|
if note_config.get('enabled', False):
|
||||||
|
settings = {
|
||||||
|
'format': note_config.get('format', 'YYYY-MM-DD'),
|
||||||
|
'folder': note_config.get('folder', ''),
|
||||||
|
'template': note_config.get('template', '')
|
||||||
|
}
|
||||||
|
except (json.JSONDecodeError, KeyError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Convert format and generate filename
|
||||||
|
date_format = self._convert_moment_format(settings['format'])
|
||||||
|
|
||||||
|
# Handle week format specially for ISO weeks
|
||||||
|
if 'W' in settings['format'] and '[W]' in settings['format']:
|
||||||
|
# Handle formats like "yyyy-[W]WW" or "YYYY-[W]WW" or "yy-[W]WW"
|
||||||
|
# Use ISO week number
|
||||||
|
year_format = 'yyyy' if 'yyyy' in settings['format'] else ('YYYY' if 'YYYY' in settings['format'] else 'yy')
|
||||||
|
if year_format == 'yyyy' or year_format == 'YYYY':
|
||||||
|
year = datetime.now().strftime('%G') # ISO year (4 digits)
|
||||||
|
else:
|
||||||
|
year = datetime.now().strftime('%g') # ISO year (2 digits)
|
||||||
|
week = datetime.now().strftime('%V') # ISO week number
|
||||||
|
filename = f"{year}-W{week}"
|
||||||
|
else:
|
||||||
|
filename = datetime.now().strftime(date_format)
|
||||||
|
|
||||||
|
# Get template content if specified
|
||||||
|
content = ""
|
||||||
|
if settings['template']:
|
||||||
|
template_path = vault_path / settings['template']
|
||||||
|
if not template_path.suffix:
|
||||||
|
template_path = template_path.with_suffix('.md')
|
||||||
|
if template_path.exists():
|
||||||
|
content = template_path.read_text()
|
||||||
|
|
||||||
|
# Construct note path with folder
|
||||||
|
folder = settings['folder']
|
||||||
|
if folder:
|
||||||
|
note_path = f"{folder}/{filename}.md"
|
||||||
|
else:
|
||||||
|
note_path = f"{filename}.md"
|
||||||
|
|
||||||
|
# Check if note exists
|
||||||
|
full_note_path = vault_path / note_path
|
||||||
|
if not full_note_path.suffix:
|
||||||
|
full_note_path = full_note_path.with_suffix('.md')
|
||||||
|
|
||||||
|
if full_note_path.exists():
|
||||||
|
# Note exists, just open it
|
||||||
|
self.open_note(note_path, vault_name)
|
||||||
|
else:
|
||||||
|
# Note doesn't exist, create and open it
|
||||||
|
self.create_note(note_path, content=content, vault=vault_name, open_after=True)
|
||||||
|
|
||||||
|
def daily_note(self, vault: str = None):
|
||||||
|
"""Create or open today's daily note."""
|
||||||
|
self._create_or_open_periodic_note('daily', vault)
|
||||||
|
|
||||||
|
def weekly_note(self, vault: str = None):
|
||||||
|
"""Create or open this week's note."""
|
||||||
|
self._create_or_open_periodic_note('weekly', vault)
|
||||||
|
|
||||||
|
def monthly_note(self, vault: str = None):
|
||||||
|
"""Create or open this month's note."""
|
||||||
|
self._create_or_open_periodic_note('monthly', vault)
|
||||||
|
|
||||||
|
def quarterly_note(self, vault: str = None):
|
||||||
|
"""Create or open this quarter's note."""
|
||||||
|
self._create_or_open_periodic_note('quarterly', vault)
|
||||||
|
|
||||||
|
def yearly_note(self, vault: str = None):
|
||||||
|
"""Create or open this year's note."""
|
||||||
|
self._create_or_open_periodic_note('yearly', vault)
|
||||||
|
|
||||||
|
def print_note(self, note_name: str, vault: str = None):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
note_path = vault_path / note_name
|
||||||
|
if not note_path.suffix:
|
||||||
|
note_path = note_path.with_suffix('.md')
|
||||||
|
|
||||||
|
if not note_path.exists():
|
||||||
|
raise click.UsageError(f"Note {note_name} does not exist")
|
||||||
|
|
||||||
|
click.echo(note_path.read_text())
|
||||||
|
|
||||||
|
def move_note(self, current_path: str, new_path: str, vault: str = None, open_after: bool = False):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
|
||||||
|
current = vault_path / current_path
|
||||||
|
if not current.suffix:
|
||||||
|
current = current.with_suffix('.md')
|
||||||
|
|
||||||
|
new = vault_path / new_path
|
||||||
|
if not new.suffix:
|
||||||
|
new = new.with_suffix('.md')
|
||||||
|
|
||||||
|
if not current.exists():
|
||||||
|
raise click.UsageError(f"Note {current_path} does not exist")
|
||||||
|
|
||||||
|
new.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
current.rename(new)
|
||||||
|
|
||||||
|
# Update internal links in all vault files
|
||||||
|
old_link_pattern = f"\\[\\[{current.stem}\\]\\]"
|
||||||
|
new_link = f"[[{new.stem}]]"
|
||||||
|
|
||||||
|
for md_file in vault_path.rglob("*.md"):
|
||||||
|
if md_file != new: # Skip the moved file
|
||||||
|
content = md_file.read_text()
|
||||||
|
updated_content = re.sub(old_link_pattern, new_link, content)
|
||||||
|
if updated_content != content:
|
||||||
|
md_file.write_text(updated_content)
|
||||||
|
|
||||||
|
click.echo(f"Moved {current_path} to {new_path}")
|
||||||
|
|
||||||
|
if open_after:
|
||||||
|
self.open_note(new_path, vault_name)
|
||||||
|
|
||||||
|
def delete_note(self, note_path: str, vault: str = None):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
note = vault_path / note_path
|
||||||
|
if not note.suffix:
|
||||||
|
note = note.with_suffix('.md')
|
||||||
|
|
||||||
|
if not note.exists():
|
||||||
|
raise click.UsageError(f"Note {note_path} does not exist")
|
||||||
|
|
||||||
|
note.unlink()
|
||||||
|
click.echo(f"Deleted {note_path}")
|
||||||
|
|
||||||
|
def _parse_frontmatter(self, content: str) -> tuple[dict, str, int]:
|
||||||
|
if not content.startswith('---\n'):
|
||||||
|
return {}, content, 0
|
||||||
|
|
||||||
|
parts = content.split('---\n', 2)
|
||||||
|
if len(parts) < 3:
|
||||||
|
return {}, content, 0
|
||||||
|
|
||||||
|
try:
|
||||||
|
frontmatter = yaml.safe_load(parts[1]) or {}
|
||||||
|
return frontmatter, parts[2], len(parts[0]) + len(parts[1]) + 6
|
||||||
|
except yaml.YAMLError:
|
||||||
|
return {}, content, 0
|
||||||
|
|
||||||
|
def _update_frontmatter(self, note_path: Path, updates: dict):
|
||||||
|
content = note_path.read_text()
|
||||||
|
frontmatter, rest_content, fm_length = self._parse_frontmatter(content)
|
||||||
|
|
||||||
|
frontmatter.update(updates)
|
||||||
|
|
||||||
|
new_content = '---\n'
|
||||||
|
new_content += yaml.dump(frontmatter, default_flow_style=False)
|
||||||
|
new_content += '---\n'
|
||||||
|
new_content += rest_content if fm_length else content
|
||||||
|
|
||||||
|
note_path.write_text(new_content)
|
||||||
|
|
||||||
|
def frontmatter_edit(self, note_name: str, key: str, value: str = None, vault: str = None):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
note_path = vault_path / note_name
|
||||||
|
if not note_path.suffix:
|
||||||
|
note_path = note_path.with_suffix('.md')
|
||||||
|
|
||||||
|
if not note_path.exists():
|
||||||
|
raise click.UsageError(f"Note {note_name} does not exist")
|
||||||
|
|
||||||
|
# Handle multiple keys
|
||||||
|
keys = [k.strip() for k in re.split(r',|\[|\]', key) if k.strip()]
|
||||||
|
updates = {}
|
||||||
|
|
||||||
|
for k in keys:
|
||||||
|
if k == 'tags':
|
||||||
|
if value:
|
||||||
|
updates[k] = value.split(',') if ',' in value else [value]
|
||||||
|
else:
|
||||||
|
updates[k] = []
|
||||||
|
else:
|
||||||
|
updates[k] = value if value is not None else ""
|
||||||
|
|
||||||
|
self._update_frontmatter(note_path, updates)
|
||||||
|
click.echo(f"Updated frontmatter for {note_name}")
|
||||||
|
|
||||||
|
def frontmatter_view(self, note_name: str, key: str, value: str = None, vault: str = None):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
note_path = vault_path / note_name
|
||||||
|
if not note_path.suffix:
|
||||||
|
note_path = note_path.with_suffix('.md')
|
||||||
|
|
||||||
|
if not note_path.exists():
|
||||||
|
raise click.UsageError(f"Note {note_name} does not exist")
|
||||||
|
|
||||||
|
content = note_path.read_text()
|
||||||
|
frontmatter, _, _ = self._parse_frontmatter(content)
|
||||||
|
|
||||||
|
if key not in frontmatter:
|
||||||
|
click.echo(f"Key '{key}' not found in frontmatter")
|
||||||
|
return
|
||||||
|
|
||||||
|
if value is not None:
|
||||||
|
# Check if value exists
|
||||||
|
current_value = frontmatter[key]
|
||||||
|
if isinstance(current_value, list):
|
||||||
|
result = value in current_value
|
||||||
|
else:
|
||||||
|
result = str(current_value) == value
|
||||||
|
click.echo(str(result).lower())
|
||||||
|
else:
|
||||||
|
click.echo(yaml.dump({key: frontmatter[key]}, default_flow_style=False).strip())
|
||||||
|
|
||||||
|
def frontmatter_clear(self, note_name: str, key: str, vault: str = None):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
note_path = vault_path / note_name
|
||||||
|
if not note_path.suffix:
|
||||||
|
note_path = note_path.with_suffix('.md')
|
||||||
|
|
||||||
|
if not note_path.exists():
|
||||||
|
raise click.UsageError(f"Note {note_name} does not exist")
|
||||||
|
|
||||||
|
keys = [k.strip() for k in re.split(r',|\[|\]', key) if k.strip()]
|
||||||
|
updates = {}
|
||||||
|
|
||||||
|
for k in keys:
|
||||||
|
updates[k] = [] if k == 'tags' else ""
|
||||||
|
|
||||||
|
self._update_frontmatter(note_path, updates)
|
||||||
|
click.echo(f"Cleared frontmatter values for {note_name}")
|
||||||
|
|
||||||
|
def frontmatter_delete(self, note_name: str, key: str, vault: str = None):
|
||||||
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
note_path = vault_path / note_name
|
||||||
|
if not note_path.suffix:
|
||||||
|
note_path = note_path.with_suffix('.md')
|
||||||
|
|
||||||
|
if not note_path.exists():
|
||||||
|
raise click.UsageError(f"Note {note_name} does not exist")
|
||||||
|
|
||||||
|
content = note_path.read_text()
|
||||||
|
frontmatter, rest_content, _ = self._parse_frontmatter(content)
|
||||||
|
|
||||||
|
keys = [k.strip() for k in re.split(r',|\[|\]', key) if k.strip()]
|
||||||
|
modified = False
|
||||||
|
|
||||||
|
for k in keys:
|
||||||
|
if k in frontmatter:
|
||||||
|
del frontmatter[k]
|
||||||
|
modified = True
|
||||||
|
|
||||||
|
if modified:
|
||||||
|
if frontmatter:
|
||||||
|
new_content = '---\n'
|
||||||
|
new_content += yaml.dump(frontmatter, default_flow_style=False)
|
||||||
|
new_content += '---\n'
|
||||||
|
new_content += rest_content
|
||||||
|
else:
|
||||||
|
new_content = rest_content
|
||||||
|
|
||||||
|
note_path.write_text(new_content)
|
||||||
|
click.echo(f"Deleted frontmatter keys from {note_name}")
|
||||||
|
else:
|
||||||
|
click.echo("No matching keys found in frontmatter")
|
||||||
|
|
||||||
|
def _url_encode(self, text: str) -> str:
|
||||||
|
"""URL encode a string, preserving forward slashes."""
|
||||||
|
return quote(text, safe='/')
|
||||||
|
|
||||||
|
def _open_uri(self, uri: str):
|
||||||
|
"""Open URI using the appropriate command for the current platform."""
|
||||||
|
if sys.platform == 'darwin': # macOS
|
||||||
|
subprocess.run(['open', uri])
|
||||||
|
elif sys.platform == 'win32': # Windows
|
||||||
|
os.startfile(uri)
|
||||||
|
else: # Linux
|
||||||
|
subprocess.run(['xdg-open', uri])
|
||||||
|
|
||||||
|
# CLI Commands
|
||||||
|
|
||||||
|
@click.group(name='ob-cli')
|
||||||
|
def cli():
|
||||||
|
"""Onyx CLI - Interact with Obsidian from the command line"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.argument('vault_name')
|
||||||
|
@click.option('--path', help="Path to the vault directory")
|
||||||
|
def set_default(vault_name, path):
|
||||||
|
"""Set the default vault for future operations"""
|
||||||
|
# Convert Windows backslashes to forward slashes if needed
|
||||||
|
if path:
|
||||||
|
path = str(Path(path))
|
||||||
|
OnyxCLI().set_default_vault(vault_name, path)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
def print_default():
|
||||||
|
"""Print the current default vault and its path"""
|
||||||
|
OnyxCLI().print_default()
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.argument('note_name')
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def open(note_name, vault):
|
||||||
|
"""Open a note in Obsidian"""
|
||||||
|
OnyxCLI().open_note(note_name, vault)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def daily(vault):
|
||||||
|
"""Create or open today's daily note"""
|
||||||
|
OnyxCLI().daily_note(vault)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def weekly(vault):
|
||||||
|
"""Create or open this week's note"""
|
||||||
|
OnyxCLI().weekly_note(vault)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def monthly(vault):
|
||||||
|
"""Create or open this month's note"""
|
||||||
|
OnyxCLI().monthly_note(vault)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def quarterly(vault):
|
||||||
|
"""Create or open this quarter's note"""
|
||||||
|
OnyxCLI().quarterly_note(vault)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def yearly(vault):
|
||||||
|
"""Create or open this year's note"""
|
||||||
|
OnyxCLI().yearly_note(vault)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.argument('note_name')
|
||||||
|
@click.option('--content', default="", help="Content to write to the note")
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
@click.option('--overwrite', is_flag=True, help="Overwrite existing note")
|
||||||
|
@click.option('--append', is_flag=True, help="Append to existing note")
|
||||||
|
@click.option('--open', 'open_after', is_flag=True, help="Open note after creation")
|
||||||
|
def create(note_name, content, vault, overwrite, append, open_after):
|
||||||
|
"""Create a new note in the vault"""
|
||||||
|
OnyxCLI().create_note(note_name, content, vault, overwrite, append, open_after)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.argument('note_name')
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def print_note(note_name, vault):
|
||||||
|
"""Print the contents of a note"""
|
||||||
|
OnyxCLI().print_note(note_name, vault)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.argument('current_path')
|
||||||
|
@click.argument('new_path')
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
@click.option('--open', 'open_after', is_flag=True, help="Open note after moving")
|
||||||
|
def move(current_path, new_path, vault, open_after):
|
||||||
|
"""Move/rename a note and update all internal links"""
|
||||||
|
OnyxCLI().move_note(current_path, new_path, vault, open_after)
|
||||||
|
|
||||||
|
@cli.command()
|
||||||
|
@click.argument('note_path')
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def delete(note_path, vault):
|
||||||
|
"""Delete a note"""
|
||||||
|
OnyxCLI().delete_note(note_path, vault)
|
||||||
|
|
||||||
|
@cli.command(name='frontmatter')
|
||||||
|
@click.argument('note_name')
|
||||||
|
@click.option('--edit', is_flag=True, help="Edit frontmatter")
|
||||||
|
@click.option('--view', is_flag=True, help="View frontmatter")
|
||||||
|
@click.option('--clear', is_flag=True, help="Clear frontmatter values")
|
||||||
|
@click.option('--delete', is_flag=True, help="Delete frontmatter keys")
|
||||||
|
@click.option('--key', required=True, help="Frontmatter key to manage")
|
||||||
|
@click.option('--value', help="Value to set or check for")
|
||||||
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
|
def frontmatter_command(note_name, edit, view, clear, delete, key, value, vault):
|
||||||
|
"""Manage note frontmatter"""
|
||||||
|
cli = OnyxCLI()
|
||||||
|
if sum([edit, view, clear, delete]) != 1:
|
||||||
|
raise click.UsageError("Exactly one of --edit, --view, --clear, or --delete must be specified")
|
||||||
|
|
||||||
|
if edit:
|
||||||
|
cli.frontmatter_edit(note_name, key, value, vault)
|
||||||
|
elif view:
|
||||||
|
cli.frontmatter_view(note_name, key, value, vault)
|
||||||
|
elif clear:
|
||||||
|
cli.frontmatter_clear(note_name, key, vault)
|
||||||
|
elif delete:
|
||||||
|
cli.frontmatter_delete(note_name, key, vault)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
cli()
|
||||||
Whitespace-only changes.
Binary file not shown.
@@ -0,0 +1,198 @@
|
|||||||
|
import unittest
|
||||||
|
import os
|
||||||
|
import yaml
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
from src.obsidian_cli import OnyxCLI
|
||||||
|
from unittest.mock import patch, MagicMock
|
||||||
|
import click
|
||||||
|
|
||||||
|
class TestOnyxCLI(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
# Create temporary test directory and files
|
||||||
|
self.test_dir = Path('test_vault')
|
||||||
|
self.test_dir.mkdir(exist_ok=True)
|
||||||
|
|
||||||
|
# Create a temporary config directory
|
||||||
|
self.temp_config_dir = Path('temp_config')
|
||||||
|
self.temp_config_dir.mkdir(exist_ok=True)
|
||||||
|
|
||||||
|
# Mock home directory for config
|
||||||
|
self.patcher = patch('pathlib.Path.home')
|
||||||
|
self.mock_home = self.patcher.start()
|
||||||
|
self.mock_home.return_value = Path('temp_config')
|
||||||
|
|
||||||
|
self.cli = OnyxCLI()
|
||||||
|
|
||||||
|
# Set up test vault
|
||||||
|
self.cli.set_default_vault('test_vault', str(self.test_dir.resolve()))
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
# Clean up test directories
|
||||||
|
self.patcher.stop()
|
||||||
|
shutil.rmtree(self.test_dir, ignore_errors=True)
|
||||||
|
shutil.rmtree(self.temp_config_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
def test_set_default_vault(self):
|
||||||
|
"""Test setting default vault"""
|
||||||
|
self.cli.set_default_vault('new_vault', str(self.test_dir))
|
||||||
|
self.assertEqual(self.cli.default_vault, 'new_vault')
|
||||||
|
|
||||||
|
config = yaml.safe_load(self.cli.config_file.read_text())
|
||||||
|
self.assertEqual(config['default_vault'], 'new_vault')
|
||||||
|
self.assertEqual(Path(config['vaults']['new_vault']), self.test_dir.resolve())
|
||||||
|
|
||||||
|
def test_create_note(self):
|
||||||
|
"""Test note creation"""
|
||||||
|
# Test basic note creation
|
||||||
|
self.cli.create_note('test.md', 'Test content')
|
||||||
|
note_path = self.test_dir / 'test.md'
|
||||||
|
self.assertTrue(note_path.exists())
|
||||||
|
self.assertEqual(note_path.read_text(), 'Test content')
|
||||||
|
|
||||||
|
# Test note creation with auto-extension
|
||||||
|
self.cli.create_note('test2', 'Test content 2')
|
||||||
|
self.assertTrue((self.test_dir / 'test2.md').exists())
|
||||||
|
|
||||||
|
# Test overwrite
|
||||||
|
with self.assertRaises(click.UsageError):
|
||||||
|
self.cli.create_note('test.md', 'New content')
|
||||||
|
self.cli.create_note('test.md', 'New content', overwrite=True)
|
||||||
|
self.assertEqual((self.test_dir / 'test.md').read_text(), 'New content')
|
||||||
|
|
||||||
|
# Test append
|
||||||
|
self.cli.create_note('test.md', 'Additional content', append=True)
|
||||||
|
self.assertEqual(
|
||||||
|
(self.test_dir / 'test.md').read_text(),
|
||||||
|
'New content\nAdditional content'
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_frontmatter_operations(self):
|
||||||
|
"""Test frontmatter operations"""
|
||||||
|
# Create a test note with frontmatter
|
||||||
|
initial_content = """---
|
||||||
|
title: Test Note
|
||||||
|
tags: [test]
|
||||||
|
status: draft
|
||||||
|
---
|
||||||
|
Test content"""
|
||||||
|
test_note = 'frontmatter_test.md'
|
||||||
|
self.cli.create_note(test_note, initial_content)
|
||||||
|
|
||||||
|
# Mock click.UsageError for testing
|
||||||
|
click_error = click.UsageError
|
||||||
|
|
||||||
|
# Test that frontmatter operations work correctly
|
||||||
|
|
||||||
|
# Test frontmatter --edit
|
||||||
|
self.cli.frontmatter_edit(test_note, 'tags', 'test,new')
|
||||||
|
self.cli.frontmatter_edit(test_note, 'status', 'published')
|
||||||
|
|
||||||
|
content = (self.test_dir / test_note).read_text()
|
||||||
|
frontmatter = yaml.safe_load(content.split('---')[1])
|
||||||
|
self.assertEqual(frontmatter['tags'], ['test', 'new'])
|
||||||
|
self.assertEqual(frontmatter['status'], 'published')
|
||||||
|
|
||||||
|
# Test frontmatter --view
|
||||||
|
with patch('click.echo') as mock_echo:
|
||||||
|
self.cli.frontmatter_view(test_note, 'tags')
|
||||||
|
mock_echo.assert_called_with(yaml.dump({'tags': ['test', 'new']}, default_flow_style=False).strip())
|
||||||
|
|
||||||
|
# Test frontmatter --view with value check
|
||||||
|
with patch('click.echo') as mock_echo:
|
||||||
|
self.cli.frontmatter_view(test_note, 'tags', 'test')
|
||||||
|
mock_echo.assert_called_with('true')
|
||||||
|
|
||||||
|
self.cli.frontmatter_view(test_note, 'tags', 'nonexistent')
|
||||||
|
mock_echo.assert_called_with('false')
|
||||||
|
|
||||||
|
# Test frontmatter --clear
|
||||||
|
self.cli.frontmatter_clear(test_note, 'tags')
|
||||||
|
content = (self.test_dir / test_note).read_text()
|
||||||
|
frontmatter = yaml.safe_load(content.split('---')[1])
|
||||||
|
self.assertEqual(frontmatter['tags'], [])
|
||||||
|
|
||||||
|
# Test frontmatter --clear with multiple keys
|
||||||
|
self.cli.frontmatter_clear(test_note, 'status,title')
|
||||||
|
content = (self.test_dir / test_note).read_text()
|
||||||
|
frontmatter = yaml.safe_load(content.split('---')[1])
|
||||||
|
self.assertEqual(frontmatter['status'], '')
|
||||||
|
self.assertEqual(frontmatter['title'], '')
|
||||||
|
|
||||||
|
# Test frontmatter --delete
|
||||||
|
self.cli.frontmatter_delete(test_note, 'tags')
|
||||||
|
content = (self.test_dir / test_note).read_text()
|
||||||
|
frontmatter = yaml.safe_load(content.split('---')[1])
|
||||||
|
self.assertNotIn('tags', frontmatter)
|
||||||
|
|
||||||
|
# Test frontmatter --delete with multiple keys
|
||||||
|
self.cli.frontmatter_delete(test_note, 'status,title')
|
||||||
|
content = (self.test_dir / test_note).read_text()
|
||||||
|
# After deleting all keys, there should be no frontmatter section
|
||||||
|
self.assertNotIn('---', content)
|
||||||
|
|
||||||
|
def test_move_note(self):
|
||||||
|
"""Test moving/renaming notes"""
|
||||||
|
# Create a test note and another note that links to it
|
||||||
|
self.cli.create_note('source.md', 'Test content')
|
||||||
|
self.cli.create_note('link.md', 'Link to [[source]]')
|
||||||
|
|
||||||
|
# Move the note
|
||||||
|
self.cli.move_note('source.md', 'folder/dest.md')
|
||||||
|
|
||||||
|
# Check that the note was moved
|
||||||
|
self.assertFalse((self.test_dir / 'source.md').exists())
|
||||||
|
self.assertTrue((self.test_dir / 'folder' / 'dest.md').exists())
|
||||||
|
|
||||||
|
# Check that links were updated
|
||||||
|
link_content = (self.test_dir / 'link.md').read_text()
|
||||||
|
self.assertIn('[[dest]]', link_content)
|
||||||
|
|
||||||
|
def test_daily_note(self):
|
||||||
|
"""Test daily note creation"""
|
||||||
|
# Create daily note (default settings don't use templates)
|
||||||
|
with patch('datetime.datetime') as mock_date:
|
||||||
|
mock_date.now.return_value.strftime.return_value = '2025-10-24'
|
||||||
|
self.cli.daily_note()
|
||||||
|
|
||||||
|
daily_note = self.test_dir / '2025-10-24.md'
|
||||||
|
self.assertTrue(daily_note.exists())
|
||||||
|
# Daily note should be empty since no template is configured
|
||||||
|
self.assertEqual(daily_note.read_text(), '')
|
||||||
|
|
||||||
|
@patch('subprocess.run')
|
||||||
|
@patch('os.startfile')
|
||||||
|
def test_open_note(self, mock_startfile, mock_run):
|
||||||
|
"""Test opening notes"""
|
||||||
|
# Create a test note
|
||||||
|
self.cli.create_note('test.md', 'Test content')
|
||||||
|
|
||||||
|
# Test opening on different platforms
|
||||||
|
with patch('sys.platform', 'win32'):
|
||||||
|
self.cli.open_note('test.md')
|
||||||
|
mock_startfile.assert_called_with('obsidian://open?vault=test_vault&file=test')
|
||||||
|
|
||||||
|
with patch('sys.platform', 'darwin'):
|
||||||
|
self.cli.open_note('test.md')
|
||||||
|
mock_run.assert_called_with(['open', 'obsidian://open?vault=test_vault&file=test'])
|
||||||
|
|
||||||
|
with patch('sys.platform', 'linux'):
|
||||||
|
self.cli.open_note('test.md')
|
||||||
|
mock_run.assert_called_with(['xdg-open', 'obsidian://open?vault=test_vault&file=test'])
|
||||||
|
|
||||||
|
def test_delete_note(self):
|
||||||
|
"""Test note deletion"""
|
||||||
|
# Create a test note
|
||||||
|
self.cli.create_note('test.md', 'Test content')
|
||||||
|
self.assertTrue((self.test_dir / 'test.md').exists())
|
||||||
|
|
||||||
|
# Delete the note
|
||||||
|
self.cli.delete_note('test.md')
|
||||||
|
self.assertFalse((self.test_dir / 'test.md').exists())
|
||||||
|
|
||||||
|
# Test deleting non-existent note
|
||||||
|
with self.assertRaises(click.UsageError):
|
||||||
|
self.cli.delete_note('nonexistent.md')
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user