improvements

This commit is contained in:
olivier committed 2025-10-28 21:52:04 -04:00
1 parent 3d122b5022
commit bf1dca3bc4
12 files changed
+303 -103

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.12 (Onyx - obsidian cli tool)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.12 (Onyx - obsidian cli tool)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.12 (Onyx - obsidian cli tool)" project-jdk-type="Python SDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Onyx - obsidian cli tool.iml" filepath="$PROJECT_DIR$/.idea/Onyx - obsidian cli tool.iml" />
</modules>
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
+105 -83
View File
@@ -1,6 +1,6 @@
# Onyx Python Helper
# Onyx CLI - Obsidian Command Line Tool
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.
A Python-based command-line interface for interacting with Obsidian vaults. Manage notes directly from the terminal without opening Obsidian.
## Installation
@@ -10,130 +10,153 @@ A Python-based command-line interface tool for interacting with Obsidian vaults.
pip install -r requirements.txt
```
## Usage
### Set Default Vault
First, you need to set up your vault with both its name and path:
## Quick Start
Set up your default vault:
```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"
ob-cli set-default "my-vault" --path "/path/to/vault"
```
### Open Notes
Then use any command:
```bash
ob-cli open "note-name"
ob-cli daily
ob-cli frontmatter "note-name" --view --key "tags"
```
## Commands
### Vault Management
```bash
# Set default vault (required first time)
ob-cli set-default "vault-name" --path "/path/to/vault"
# Print current default vault
ob-cli print-default
```
### Opening Notes
```bash
# Open a note in Obsidian
python src/obsidian_cli.py open "note-name"
ob-cli open "note-name"
# Open a note in specific vault
python src/obsidian_cli.py open "note-name" --vault "vault-name"
# Open note from specific vault
ob-cli open "note-name" --vault "vault-name"
```
### Daily Notes
### Periodic Notes
```bash
# Create and open today's daily note
python src/obsidian_cli.py daily
# Create or open today's daily note
ob-cli daily
# Create daily note in specific vault
python src/obsidian_cli.py daily --vault "vault-name"
# Create or open this week's note
ob-cli weekly
# Create or open this month's note
ob-cli monthly
# Create or open this quarter's note
ob-cli quarterly
# Create or open this year's note
ob-cli yearly
```
### Create/Update Notes
### Creating & Editing Notes
```bash
# Create a new note
python src/obsidian_cli.py create "note-name"
ob-cli create "note-name"
# Create note with content
python src/obsidian_cli.py create "note-name" --content "Your content here"
# Create with content
ob-cli create "note-name" --content "Your content here"
# Create note in specific vault
python src/obsidian_cli.py create "note-name" --vault "vault-name"
# Create in specific vault
ob-cli create "note-name" --vault "vault-name"
# Overwrite existing note
python src/obsidian_cli.py create "note-name" --content "New content" --overwrite
ob-cli create "note-name" --content "New content" --overwrite
# Append to existing note
python src/obsidian_cli.py create "note-name" --content "Additional content" --append
ob-cli create "note-name" --content "Additional content" --append
# Create and open note
python src/obsidian_cli.py create "note-name" --content "content" --open
# Create and open
ob-cli create "note-name" --content "content" --open
```
### View Notes
### Viewing Notes
```bash
# Print note contents
python src/obsidian_cli.py print-note "note-name"
# Print note contents to terminal
ob-cli print-note "note-name"
# Print note from specific vault
python src/obsidian_cli.py print-note "note-name" --vault "vault-name"
# Print from specific vault
ob-cli print-note "note-name" --vault "vault-name"
```
### Move/Rename Notes
### Moving & Deleting Notes
```bash
# Move/rename a note
python src/obsidian_cli.py move "old-path" "new-path"
# Move or rename a note (auto-updates internal links)
ob-cli move "old-path" "new-path"
# Move in specific vault
python src/obsidian_cli.py move "old-path" "new-path" --vault "vault-name"
ob-cli move "old-path" "new-path" --vault "vault-name"
# Move and open note
python src/obsidian_cli.py move "old-path" "new-path" --open
```
# Move and open
ob-cli move "old-path" "new-path" --open
### Delete Notes
```bash
# Delete a note
python src/obsidian_cli.py delete "note-path"
ob-cli delete "note-path"
# Delete from specific vault
python src/obsidian_cli.py delete "note-path" --vault "vault-name"
ob-cli 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"
Edit note metadata in YAML frontmatter:
# 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"
```bash
# View a frontmatter key
ob-cli frontmatter "note-name" --view --key "tags"
# Check if a value exists in frontmatter
ob-cli frontmatter "note-name" --view --key "tags" --value "project"
# Edit frontmatter (add or update key)
ob-cli frontmatter "note-name" --edit --key "tags" --value "project"
ob-cli frontmatter "note-name" --edit --key "tags" --value "project,urgent"
ob-cli frontmatter "note-name" --edit --key "status" --value "in-progress"
# 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"
ob-cli frontmatter "note-name" --clear --key "tags"
ob-cli 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"
ob-cli frontmatter "note-name" --delete --key "tags"
ob-cli frontmatter "note-name" --delete --key "date,status,tags"
```
### Version
```bash
# Display version
ob-cli --version
```
## 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)
- **Vault Management**: Set and switch between multiple Obsidian vaults
- **Note Operations**: Create, open, move, rename, and delete notes
- **Recursive Search**: Find notes in nested directories
- **Periodic Notes**: Support for daily, weekly, monthly, quarterly, and yearly notes
- **Frontmatter Management**: Edit, view, clear, and delete YAML frontmatter
- **Link Updates**: Automatically update internal links when moving notes
- **Cross-Platform**: Works on macOS, Windows, and Linux
## Requirements
@@ -145,8 +168,6 @@ The tool now includes all major features from the original Obsidian CLI tool:
### Running Tests
To run the tests:
```bash
# Install test dependencies
pip install -r requirements.txt
@@ -154,15 +175,16 @@ pip install -r requirements.txt
# Run tests
python -m pytest
# Run tests with coverage report
# Run with coverage
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
## Configuration
The CLI stores vault configuration in `~/.onyx-cli/config.yaml`. You can manually edit this file to manage vaults:
```yaml
default_vault: my-vault
vaults:
my-vault: /path/to/vault
work: /path/to/work/vault
Binary file not shown.
+88 -15
View File
@@ -5,7 +5,8 @@ import yaml
import json
import subprocess
import sys
from datetime import datetime
import datetime
import builtins
from pathlib import Path
import re
from typing import List, Union, Optional, Dict, Any
@@ -50,6 +51,7 @@ class OnyxCLI:
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),
@@ -298,13 +300,13 @@ class OnyxCLI:
# 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)
year = datetime.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
year = datetime.datetime.now().strftime('%g') # ISO year (2 digits)
week = datetime.datetime.now().strftime('%V') # ISO week number
filename = f"{year}-W{week}"
else:
filename = datetime.now().strftime(date_format)
filename = datetime.datetime.now().strftime(date_format)
# Get template content if specified
content = ""
@@ -443,6 +445,11 @@ class OnyxCLI:
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0]
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
@@ -468,6 +475,11 @@ class OnyxCLI:
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0]
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
@@ -495,6 +507,11 @@ class OnyxCLI:
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0]
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
@@ -513,6 +530,11 @@ class OnyxCLI:
if not note_path.suffix:
note_path = note_path.with_suffix('.md')
if not note_path.exists():
matches = list(vault_path.rglob(f"{note_name}.md"))
if matches:
note_path = matches[0]
if not note_path.exists():
raise click.UsageError(f"Note {note_name} does not exist")
@@ -558,14 +580,30 @@ class OnyxCLI:
@click.group(name='ob-cli')
def cli():
"""Onyx CLI - Interact with Obsidian from the command line"""
"""Onyx CLI - Interact with Obsidian vaults from the command line
Manage your Obsidian notes, frontmatter, and periodic notes directly from the terminal.
EXAMPLES:
ob-cli open "my-note"
ob-cli daily
ob-cli frontmatter "my-note" --view --key "tags"
ob-cli --version
For more help on a specific command:
ob-cli COMMAND --help
"""
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"""
"""Set or switch the default vault
USAGE:
ob-cli set-default VAULT_NAME --path /path/to/vault
"""
# Convert Windows backslashes to forward slashes if needed
if path:
path = str(Path(path))
@@ -573,20 +611,29 @@ def set_default(vault_name, path):
@cli.command()
def print_default():
"""Print the current default vault and its path"""
"""Display the currently configured 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"""
"""Open a note in Obsidian
Searches for the note in the vault and opens it in Obsidian. Supports nested directories.
USAGE:
ob-cli open "my-note"
ob-cli open "folder/my-note"
"""
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"""
"""Create or open today's daily note
Uses Obsidian's daily notes plugin settings (format, folder, template) if configured."""
OnyxCLI().daily_note(vault)
@cli.command()
@@ -621,14 +668,19 @@ def yearly(vault):
@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"""
"""Create or modify a note in the vault
USAGE:
ob-cli create "my-note"
ob-cli create "my-note" --content "Some content" --open
"""
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"""
"""Display the full contents of a note in the terminal"""
OnyxCLI().print_note(note_name, vault)
@cli.command()
@@ -637,14 +689,21 @@ def print_note(note_name, vault):
@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"""
"""Move or rename a note and auto-update internal links
Automatically updates all [[links]] pointing to this note in other vault files.
USAGE:
ob-cli move "old-name" "new-name"
ob-cli move "old-folder/note" "new-folder/note"
"""
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"""
"""Permanently delete a note from the vault"""
OnyxCLI().delete_note(note_path, vault)
@cli.command(name='frontmatter')
@@ -657,7 +716,15 @@ def delete(note_path, vault):
@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"""
"""Manage YAML frontmatter in notes
Must specify exactly one action: --edit, --view, --clear, or --delete
USAGE:
ob-cli frontmatter "my-note" --view --key "tags"
ob-cli frontmatter "my-note" --edit --key "tags" --value "project,work"
ob-cli frontmatter "my-note" --delete --key "date"
"""
cli = OnyxCLI()
if sum([edit, view, clear, delete]) != 1:
raise click.UsageError("Exactly one of --edit, --view, --clear, or --delete must be specified")
@@ -671,5 +738,11 @@ def frontmatter_command(note_name, edit, view, clear, delete, key, value, vault)
elif delete:
cli.frontmatter_delete(note_name, key, vault)
@cli.command()
@click.version_option(version='0.0.1', prog_name='onyx')
def version():
"""Display version information"""
pass
if __name__ == '__main__':
cli()
View File
Whitespace-only changes.
+61 -5
View File
@@ -6,6 +6,7 @@ from pathlib import Path
from src.obsidian_cli import OnyxCLI
from unittest.mock import patch, MagicMock
import click
from datetime import datetime
class TestOnyxCLI(unittest.TestCase):
def setUp(self):
@@ -48,6 +49,59 @@ class TestOnyxCLI(unittest.TestCase):
self.cli.create_note('test.md', 'Test content')
note_path = self.test_dir / 'test.md'
self.assertTrue(note_path.exists())
def test_export_to_csv(self):
"""Test exporting note frontmatter to CSV"""
# Create a test note with frontmatter
note_content = """---
title: Test Note
tags: [tag1, tag2]
status: in-progress
date: 2025-10-28
custom: value
---
Note content"""
self.cli.create_note('test_note.md', note_content)
# Test export with specific columns included
output_file = self.test_dir / 'output1.csv'
self.cli.export_to_csv('test_note', str(output_file), include_columns=['title', 'status', 'date'])
with open(output_file, 'r', encoding='utf-8') as f:
content = f.read().strip()
self.assertEqual(content, 'title,status,date\nTest Note,in-progress,2025-10-28')
# Test export excluding specific columns
output_file = self.test_dir / 'output2.csv'
self.cli.export_to_csv('test_note', str(output_file), exclude_columns=['tags', 'custom'])
with open(output_file, 'r', encoding='utf-8') as f:
content = f.read().strip()
self.assertEqual(content, 'title,status,date\nTest Note,in-progress,2025-10-28')
# Test export with both include and exclude (exclude takes precedence)
output_file = self.test_dir / 'output3.csv'
self.cli.export_to_csv('test_note', str(output_file),
include_columns=['title', 'status', 'date', 'custom'],
exclude_columns=['status'])
with open(output_file, 'r', encoding='utf-8') as f:
content = f.read().strip()
self.assertEqual(content, 'title,date,custom\nTest Note,2025-10-28,value')
# Test with non-existent note
with self.assertRaises(click.UsageError) as context:
self.cli.export_to_csv('non_existent', 'output.csv')
self.assertTrue("not found in vault" in str(context.exception))
# Test with note without frontmatter
self.cli.create_note('no_frontmatter.md', 'Just content')
with self.assertRaises(click.UsageError) as context:
self.cli.export_to_csv('no_frontmatter', 'output.csv')
self.assertTrue("No frontmatter found" in str(context.exception))
# Test with empty frontmatter
self.cli.create_note('empty_frontmatter.md', '---\n---\nContent')
with self.assertRaises(click.UsageError) as context:
self.cli.export_to_csv('empty_frontmatter', 'output.csv')
self.assertTrue("Empty frontmatter" in str(context.exception))
self.assertEqual(note_path.read_text(), 'Test content')
# Test note creation with auto-extension
@@ -150,9 +204,11 @@ Test content"""
def test_daily_note(self):
"""Test daily note creation"""
# Create daily note (default settings don't use templates)
# Mock datetime.now() to return a specific date
mock_dt = MagicMock()
mock_dt.strftime.return_value = '2025-10-24'
with patch('datetime.datetime') as mock_date:
mock_date.now.return_value.strftime.return_value = '2025-10-24'
mock_date.now.return_value = mock_dt
self.cli.daily_note()
daily_note = self.test_dir / '2025-10-24.md'
@@ -170,15 +226,15 @@ 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')
mock_startfile.assert_called_with('obsidian://open?vault=test_vault&file=test.md')
with patch('sys.platform', 'darwin'):
self.cli.open_note('test.md')
mock_run.assert_called_with(['open', 'obsidian://open?vault=test_vault&file=test'])
mock_run.assert_called_with(['open', 'obsidian://open?vault=test_vault&file=test.md'])
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'])
mock_run.assert_called_with(['xdg-open', 'obsidian://open?vault=test_vault&file=test.md'])
def test_delete_note(self):
"""Test note deletion"""