feat: Add support for date navigation in periodic notes and improve daily note settings retrieval
This commit is contained in:
1 parent
a82cb97267
commit
9880d09294
3 files changed
+162
-128
No files matched your search
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{}
|
||||||
+160
-128
@@ -51,84 +51,6 @@ class OnyxCLI:
|
|||||||
vault_path = self._get_vault_path(vault_name)
|
vault_path = self._get_vault_path(vault_name)
|
||||||
return vault_name, vault_path
|
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(encoding='utf-8-sig'))
|
|
||||||
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(encoding='utf-8-sig'))
|
|
||||||
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(encoding='utf-8-sig')) 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"onyx set-default \"{vault_name}\" --path \"path/to/vault\""
|
|
||||||
)
|
|
||||||
|
|
||||||
config['default_vault'] = vault_name
|
|
||||||
self.config_file.write_text(yaml.dump(config), encoding='utf-8-sig')
|
|
||||||
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):
|
def print_default(self):
|
||||||
if not self.default_vault:
|
if not self.default_vault:
|
||||||
click.echo("No default vault set")
|
click.echo("No default vault set")
|
||||||
@@ -331,13 +253,10 @@ class OnyxCLI:
|
|||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def _create_or_open_periodic_note(self, note_type: str, vault: str = None):
|
def _create_or_open_periodic_note(self, note_type: str, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
||||||
"""Generic method to create or open periodic notes."""
|
"""Generic method to create or open periodic notes with date navigation."""
|
||||||
vault_name, vault_path = self._get_vault_and_path(vault)
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
|
|
||||||
# Get settings from plugin
|
|
||||||
settings = self._get_daily_note_settings(vault_path)
|
settings = self._get_daily_note_settings(vault_path)
|
||||||
|
|
||||||
# Load periodic notes settings if available
|
# Load periodic notes settings if available
|
||||||
periodic_notes_config = vault_path / ".obsidian" / "plugins" / "periodic-notes" / "data.json"
|
periodic_notes_config = vault_path / ".obsidian" / "plugins" / "periodic-notes" / "data.json"
|
||||||
if periodic_notes_config.exists():
|
if periodic_notes_config.exists():
|
||||||
@@ -352,24 +271,85 @@ class OnyxCLI:
|
|||||||
}
|
}
|
||||||
except (json.JSONDecodeError, KeyError):
|
except (json.JSONDecodeError, KeyError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Convert format and generate filename
|
# Date calculation
|
||||||
|
base_date = None
|
||||||
|
if date:
|
||||||
|
try:
|
||||||
|
base_date = datetime.datetime.strptime(date, "%Y-%m-%d")
|
||||||
|
except Exception:
|
||||||
|
base_date = datetime.datetime.now()
|
||||||
|
else:
|
||||||
|
base_date = datetime.datetime.now()
|
||||||
|
|
||||||
|
# Adjust date for navigation
|
||||||
|
if next_:
|
||||||
|
if note_type == 'daily':
|
||||||
|
base_date += datetime.timedelta(days=1)
|
||||||
|
elif note_type == 'weekly':
|
||||||
|
base_date += datetime.timedelta(weeks=1)
|
||||||
|
elif note_type == 'monthly':
|
||||||
|
month = base_date.month + 1 if base_date.month < 12 else 1
|
||||||
|
year = base_date.year + 1 if base_date.month == 12 else base_date.year
|
||||||
|
base_date = base_date.replace(year=year, month=month, day=1)
|
||||||
|
elif note_type == 'quarterly':
|
||||||
|
month = ((base_date.month - 1) // 3 + 1) * 3 + 1
|
||||||
|
year = base_date.year + (1 if month > 12 else 0)
|
||||||
|
month = month if month <= 12 else 1
|
||||||
|
base_date = base_date.replace(year=year, month=month, day=1)
|
||||||
|
elif note_type == 'yearly':
|
||||||
|
base_date = base_date.replace(year=base_date.year + 1, month=1, day=1)
|
||||||
|
elif previous:
|
||||||
|
if note_type == 'daily':
|
||||||
|
base_date -= datetime.timedelta(days=1)
|
||||||
|
elif note_type == 'weekly':
|
||||||
|
base_date -= datetime.timedelta(weeks=1)
|
||||||
|
elif note_type == 'monthly':
|
||||||
|
month = base_date.month - 1 if base_date.month > 1 else 12
|
||||||
|
year = base_date.year - 1 if base_date.month == 1 else base_date.year
|
||||||
|
base_date = base_date.replace(year=year, month=month, day=1)
|
||||||
|
elif note_type == 'quarterly':
|
||||||
|
month = ((base_date.month - 1) // 3 - 1) * 3 + 1
|
||||||
|
year = base_date.year - 1 if month < 1 else base_date.year
|
||||||
|
month = month if month > 0 else 10
|
||||||
|
base_date = base_date.replace(year=year, month=month, day=1)
|
||||||
|
elif note_type == 'yearly':
|
||||||
|
base_date = base_date.replace(year=base_date.year - 1, month=1, day=1)
|
||||||
|
|
||||||
|
|
||||||
|
# Force correct format for yearly, monthly, and weekly notes
|
||||||
|
if note_type == 'yearly':
|
||||||
|
settings['format'] = 'YYYY'
|
||||||
|
elif note_type == 'monthly':
|
||||||
|
settings['format'] = 'YYYY-MM'
|
||||||
|
elif note_type == 'weekly':
|
||||||
|
# Only override if not set to a weekly format
|
||||||
|
fmt = settings.get('format', '')
|
||||||
|
if not ('W' in fmt and '[' in fmt and ']' in fmt):
|
||||||
|
settings['format'] = 'YYYY-[W]WW'
|
||||||
|
|
||||||
date_format = self._convert_moment_format(settings['format'])
|
date_format = self._convert_moment_format(settings['format'])
|
||||||
|
|
||||||
# Handle week format specially for ISO weeks
|
# Handle week format specially for ISO weeks
|
||||||
|
filename = None
|
||||||
if 'W' in settings['format'] and '[W]' in settings['format']:
|
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')
|
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':
|
if year_format == 'yyyy' or year_format == 'YYYY':
|
||||||
year = datetime.datetime.now().strftime('%G') # ISO year (4 digits)
|
year = base_date.strftime('%G') # ISO year (4 digits)
|
||||||
else:
|
else:
|
||||||
year = datetime.datetime.now().strftime('%g') # ISO year (2 digits)
|
year = base_date.strftime('%g') # ISO year (2 digits)
|
||||||
week = datetime.datetime.now().strftime('%V') # ISO week number
|
week = base_date.strftime('%V') # ISO week number
|
||||||
filename = f"{year}-W{week}"
|
filename = f"{year}-W{week}"
|
||||||
else:
|
else:
|
||||||
filename = datetime.datetime.now().strftime(date_format)
|
try:
|
||||||
|
filename = base_date.strftime(date_format)
|
||||||
|
except Exception:
|
||||||
|
filename = base_date.strftime('%Y-%m-%d')
|
||||||
|
|
||||||
|
if not filename or filename == '.md':
|
||||||
|
# fallback to today if something went wrong
|
||||||
|
filename = base_date.strftime('%Y-%m-%d')
|
||||||
|
|
||||||
# Get template content if specified
|
# Get template content if specified
|
||||||
content = ""
|
content = ""
|
||||||
if settings['template']:
|
if settings['template']:
|
||||||
@@ -378,45 +358,43 @@ class OnyxCLI:
|
|||||||
template_path = template_path.with_suffix('.md')
|
template_path = template_path.with_suffix('.md')
|
||||||
if template_path.exists():
|
if template_path.exists():
|
||||||
content = template_path.read_text(encoding='utf-8-sig')
|
content = template_path.read_text(encoding='utf-8-sig')
|
||||||
|
|
||||||
# Construct note path with folder
|
# Construct note path with folder
|
||||||
folder = settings['folder']
|
folder = settings['folder']
|
||||||
if folder:
|
if folder:
|
||||||
note_path = f"{folder}/{filename}.md"
|
note_path = f"{folder}/{filename}.md"
|
||||||
else:
|
else:
|
||||||
note_path = f"{filename}.md"
|
note_path = f"{filename}.md"
|
||||||
|
|
||||||
# Check if note exists
|
# Check if note exists
|
||||||
full_note_path = vault_path / note_path
|
full_note_path = vault_path / note_path
|
||||||
if not full_note_path.suffix:
|
if not full_note_path.suffix:
|
||||||
full_note_path = full_note_path.with_suffix('.md')
|
full_note_path = full_note_path.with_suffix('.md')
|
||||||
|
|
||||||
if full_note_path.exists():
|
if full_note_path.exists():
|
||||||
# Note exists, just open it
|
|
||||||
self.open_note(note_path, vault_name)
|
self.open_note(note_path, vault_name)
|
||||||
else:
|
else:
|
||||||
# Note doesn't exist, create and open it
|
|
||||||
self.create_note(note_path, content=content, vault=vault_name, open_after=True)
|
self.create_note(note_path, content=content, vault=vault_name, open_after=True)
|
||||||
|
|
||||||
def daily_note(self, vault: str = None):
|
def daily_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
||||||
"""Create or open today's daily note."""
|
"""Create or open a daily note for a specific date, next, or previous day."""
|
||||||
self._create_or_open_periodic_note('daily', vault)
|
self._create_or_open_periodic_note('daily', vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
def weekly_note(self, vault: str = None):
|
def weekly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
||||||
"""Create or open this week's note."""
|
"""Create or open a weekly note for a specific date, next, or previous week."""
|
||||||
self._create_or_open_periodic_note('weekly', vault)
|
self._create_or_open_periodic_note('weekly', vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
def monthly_note(self, vault: str = None):
|
def monthly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
||||||
"""Create or open this month's note."""
|
"""Create or open a monthly note for a specific date, next, or previous month."""
|
||||||
self._create_or_open_periodic_note('monthly', vault)
|
self._create_or_open_periodic_note('monthly', vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
def quarterly_note(self, vault: str = None):
|
def quarterly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
||||||
"""Create or open this quarter's note."""
|
"""Create or open a quarterly note for a specific date, next, or previous quarter."""
|
||||||
self._create_or_open_periodic_note('quarterly', vault)
|
self._create_or_open_periodic_note('quarterly', vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
def yearly_note(self, vault: str = None):
|
def yearly_note(self, vault: str = None, date: str = None, next_: bool = False, previous: bool = False):
|
||||||
"""Create or open this year's note."""
|
"""Create or open a yearly note for a specific date, next, or previous year."""
|
||||||
self._create_or_open_periodic_note('yearly', vault)
|
self._create_or_open_periodic_note('yearly', vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
def print_note(self, note_name: str, vault: str = None):
|
def print_note(self, note_name: str, vault: str = None):
|
||||||
vault_name, vault_path = self._get_vault_and_path(vault)
|
vault_name, vault_path = self._get_vault_and_path(vault)
|
||||||
@@ -680,6 +658,45 @@ class OnyxCLI:
|
|||||||
else: # Linux
|
else: # Linux
|
||||||
subprocess.run(['xdg-open', uri])
|
subprocess.run(['xdg-open', uri])
|
||||||
|
|
||||||
|
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(encoding='utf-8-sig'))
|
||||||
|
daily_config = config.get('daily', {})
|
||||||
|
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(encoding='utf-8-sig'))
|
||||||
|
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': ''
|
||||||
|
}
|
||||||
|
|
||||||
# CLI Commands
|
# CLI Commands
|
||||||
|
|
||||||
@click.group(name='onyx')
|
@click.group(name='onyx')
|
||||||
@@ -734,35 +751,50 @@ def open(note_name, vault):
|
|||||||
|
|
||||||
@cli.command()
|
@cli.command()
|
||||||
@click.option('--vault', help="Vault name (if not using default)")
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
def daily(vault):
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
||||||
"""Create or open today's daily note
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
||||||
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
||||||
|
def daily(vault, date, next_, previous):
|
||||||
|
"""Create or open a daily note for a specific date, next, or previous day
|
||||||
|
|
||||||
Uses Obsidian's daily notes plugin settings (format, folder, template) if configured."""
|
Uses Obsidian's daily notes plugin settings (format, folder, template) if configured."""
|
||||||
OnyxCLI().daily_note(vault)
|
OnyxCLI().daily_note(vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
@cli.command()
|
@cli.command()
|
||||||
@click.option('--vault', help="Vault name (if not using default)")
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
def weekly(vault):
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
||||||
"""Create or open this week's note"""
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
||||||
OnyxCLI().weekly_note(vault)
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
||||||
|
def weekly(vault, date, next_, previous):
|
||||||
|
"""Create or open a weekly note for a specific date, next, or previous week"""
|
||||||
|
OnyxCLI().weekly_note(vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
@cli.command()
|
@cli.command()
|
||||||
@click.option('--vault', help="Vault name (if not using default)")
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
def monthly(vault):
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
||||||
"""Create or open this month's note"""
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
||||||
OnyxCLI().monthly_note(vault)
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
||||||
|
def monthly(vault, date, next_, previous):
|
||||||
|
"""Create or open a monthly note for a specific date, next, or previous month"""
|
||||||
|
OnyxCLI().monthly_note(vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
@cli.command()
|
@cli.command()
|
||||||
@click.option('--vault', help="Vault name (if not using default)")
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
def quarterly(vault):
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
||||||
"""Create or open this quarter's note"""
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
||||||
OnyxCLI().quarterly_note(vault)
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
||||||
|
def quarterly(vault, date, next_, previous):
|
||||||
|
"""Create or open a quarterly note for a specific date, next, or previous quarter"""
|
||||||
|
OnyxCLI().quarterly_note(vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
@cli.command()
|
@cli.command()
|
||||||
@click.option('--vault', help="Vault name (if not using default)")
|
@click.option('--vault', help="Vault name (if not using default)")
|
||||||
def yearly(vault):
|
@click.option('--date', help="Target date (YYYY-MM-DD) for the note")
|
||||||
"""Create or open this year's note"""
|
@click.option('--next', 'next_', is_flag=True, help="Open the next period's note")
|
||||||
OnyxCLI().yearly_note(vault)
|
@click.option('--previous', is_flag=True, help="Open the previous period's note")
|
||||||
|
def yearly(vault, date, next_, previous):
|
||||||
|
"""Create or open a yearly note for a specific date, next, or previous year"""
|
||||||
|
OnyxCLI().yearly_note(vault, date=date, next_=next_, previous=previous)
|
||||||
|
|
||||||
@cli.command()
|
@cli.command()
|
||||||
@click.argument('note_name')
|
@click.argument('note_name')
|
||||||
|
|||||||
@@ -1,2 +1,3 @@
|
|||||||
- trim the content of tags. `onyx frontmatter "branch thing" --edit --key "tags" --value "one, two, three"` should not give the tags "one", " two", " three".
|
- trim the content of tags. `onyx frontmatter "branch thing" --edit --key "tags" --value "one, two, three"` should not give the tags "one", " two", " three".
|
||||||
- add a way to add multiple properties at once. not sure how.
|
- add a way to add multiple properties at once. not sure how.
|
||||||
|
|
||||||
Reference in new issue
Block a user