Add per-vault periodic notes config, fix version/print-default bugs, stop tracking build artifacts

- onyx periodic --view/--edit: configure folder/format/template per note type,
  independent of Obsidian's Daily Notes / Periodic Notes plugin state
- fix: weekly/monthly/quarterly/yearly notes no longer silently inherit the
  daily note's folder/template when no plugin config exists
- fix: quarterly notes now resolve the real quarter number instead of a
  literal 'Q'
- fix: onyx --version now works at the root command group; remove the
  redundant no-op 'version' subcommand
- fix: print-default no longer dumps the raw vault config dict for
  long-form vault entries
- expand --help text across periodic/create/set-default commands
- add .gitignore; stop tracking build/, dist/, __pycache__/, .idea/, .vscode/
This commit is contained in:
olivier committed 2026-09-24 17:11:43 -04:00
1 parent d13e377aba
commit 0dddb57d76
30 files changed
+453 -21314

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
# Python
__pycache__/
*.py[cod]
*.egg-info/
.eggs/
# PyInstaller build output (regenerate with `python -m PyInstaller onyx.spec`)
build/
dist/
# Testing
.pytest_cache/
.coverage
htmlcov/
test_vault/
temp_config/
# IDEs
.idea/
.vscode/
# OS
.DS_Store
Thumbs.db
# Stale pytest-run output redirects (not source)
test_failure.txt
test_final.txt
test_debug.txt
test_output.txt
-8
View File
@@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
-14
View File
@@ -1,14 +0,0 @@
<?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
@@ -1,6 +0,0 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
-7
View File
@@ -1,7 +0,0 @@
<?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
@@ -1,8 +0,0 @@
<?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
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
-1
View File
@@ -1 +0,0 @@
{}
+43 -5
View File
@@ -96,14 +96,43 @@ onyx quarterly --next # opens next quarter's note
onyx yearly --previous # opens last year's note
```
**Filename formats:**
**Default filename formats** (used when nothing else is configured):
- Daily: `YYYY-MM-DD.md`
- Weekly: `YYYY-WWW.md` (ISO week, e.g. `2025-W48.md`)
- Monthly: `YYYY-MM.md`
- Quarterly: `YYYY-QX.md` (e.g. `2025-Q4.md`)
- Yearly: `YYYY.md`
The correct filename is always generated automatically, regardless of your plugin settings.
Folder, filename format, and template for each note type are resolved in this order:
1. onyx's own config, set via `onyx periodic` (see below)
2. Obsidian's Periodic Notes plugin, or the core Daily Notes plugin for daily notes
3. The built-in defaults above
Each note type is resolved independently — configuring (or not configuring) one type
never affects another. See [Configuring Periodic Notes](#configuring-periodic-notes) to
set your own folders/formats/templates, especially for vaults without the Periodic Notes
plugin installed (daily/weekly/monthly/quarterly/yearly notes not stored in the vault root).
### Configuring Periodic Notes
```bash
# View the resolved settings for a note type
onyx periodic --type weekly --view
# Set your own folder / format / template for a note type
onyx periodic --type weekly --edit --folder "periodic/weekly" --format "YYYY-[W]WW" --template "resources/template/weekly-note.md"
# Any subset of --folder / --format / --template can be set at once
onyx periodic --type monthly --edit --folder "periodic/monthly"
# Configure a specific vault
onyx periodic --type weekly --edit --folder "periodic/weekly" --vault "work"
```
`--format` uses moment.js-style tokens (`YYYY`, `MM`, `DD`, `[W]WW`, `[Q]Q`, ...), matching
what Obsidian's own daily-notes/periodic-notes settings use. `--folder` and `--template` are
paths relative to the vault root.
### Creating & Editing Notes
@@ -222,11 +251,20 @@ python -m pytest --cov=src tests/
## Configuration
The CLI stores vault configuration in `~/.onyx-cli/config.yaml`. You can manually edit this file to manage vaults:
The CLI stores vault configuration in `~/.onyx-cli/config.yaml`. You can manually edit this file to manage vaults, or use `onyx set-default` and `onyx periodic` to edit it for you:
```yaml
default_vault: my-vault
vaults:
my-vault: /path/to/vault
work: /path/to/work/vault
my-vault: /path/to/vault # short form: just a path
work: # long form: path plus optional settings
path: /path/to/work/vault
path_prefix: /path/to/prefix
periodic_notes:
weekly:
folder: periodic/weekly
format: YYYY-[W]WW
template: resources/template/weekly-note.md
monthly:
folder: periodic/monthly
```
File diff suppressed because it is too large. Load diff
-142
View File
@@ -1,142 +0,0 @@
('C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\dist\\onyx.exe',
True,
False,
False,
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\bootloader\\images\\icon-console.ico',
None,
False,
False,
b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<assembly xmlns='
b'"urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">\n <trustInfo x'
b'mlns="urn:schemas-microsoft-com:asm.v3">\n <security>\n <requested'
b'Privileges>\n <requestedExecutionLevel level="asInvoker" uiAccess='
b'"false"/>\n </requestedPrivileges>\n </security>\n </trustInfo>\n '
b'<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">\n <'
b'application>\n <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f'
b'0}"/>\n <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>\n '
b' <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>\n <s'
b'upportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>\n <supporte'
b'dOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>\n </application>\n <'
b'/compatibility>\n <application xmlns="urn:schemas-microsoft-com:asm.v3">'
b'\n <windowsSettings>\n <longPathAware xmlns="http://schemas.micros'
b'oft.com/SMI/2016/WindowsSettings">true</longPathAware>\n </windowsSett'
b'ings>\n </application>\n <dependency>\n <dependentAssembly>\n <ass'
b'emblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version='
b'"6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" langua'
b'ge="*"/>\n </dependentAssembly>\n </dependency>\n</assembly>',
True,
False,
None,
None,
None,
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\onyx.pkg',
[('pyi-contents-directory _internal', '', 'OPTION'),
('PYZ-00.pyz',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\PYZ-00.pyz',
'PYZ'),
('struct',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\struct.pyc',
'PYMODULE'),
('pyimod01_archive',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\pyimod01_archive.pyc',
'PYMODULE'),
('pyimod02_importers',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\pyimod02_importers.pyc',
'PYMODULE'),
('pyimod03_ctypes',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\pyimod03_ctypes.pyc',
'PYMODULE'),
('pyimod04_pywin32',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\pyimod04_pywin32.pyc',
'PYMODULE'),
('pyiboot01_bootstrap',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\loader\\pyiboot01_bootstrap.py',
'PYSOURCE'),
('pyi_rth_inspect',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_inspect.py',
'PYSOURCE'),
('pyi_rth_pkgutil',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_pkgutil.py',
'PYSOURCE'),
('pyi_rth_multiprocessing',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_multiprocessing.py',
'PYSOURCE'),
('pyi_rth_setuptools',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_setuptools.py',
'PYSOURCE'),
('onyx',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\src\\onyx.py',
'PYSOURCE'),
('python312.dll', 'C:\\Python312\\python312.dll', 'BINARY'),
('_lzma.pyd', 'C:\\Python312\\DLLs\\_lzma.pyd', 'EXTENSION'),
('_bz2.pyd', 'C:\\Python312\\DLLs\\_bz2.pyd', 'EXTENSION'),
('_decimal.pyd', 'C:\\Python312\\DLLs\\_decimal.pyd', 'EXTENSION'),
('_hashlib.pyd', 'C:\\Python312\\DLLs\\_hashlib.pyd', 'EXTENSION'),
('select.pyd', 'C:\\Python312\\DLLs\\select.pyd', 'EXTENSION'),
('_socket.pyd', 'C:\\Python312\\DLLs\\_socket.pyd', 'EXTENSION'),
('_overlapped.pyd', 'C:\\Python312\\DLLs\\_overlapped.pyd', 'EXTENSION'),
('_ssl.pyd', 'C:\\Python312\\DLLs\\_ssl.pyd', 'EXTENSION'),
('_queue.pyd', 'C:\\Python312\\DLLs\\_queue.pyd', 'EXTENSION'),
('_ctypes.pyd', 'C:\\Python312\\DLLs\\_ctypes.pyd', 'EXTENSION'),
('_multiprocessing.pyd',
'C:\\Python312\\DLLs\\_multiprocessing.pyd',
'EXTENSION'),
('pyexpat.pyd', 'C:\\Python312\\DLLs\\pyexpat.pyd', 'EXTENSION'),
('_asyncio.pyd', 'C:\\Python312\\DLLs\\_asyncio.pyd', 'EXTENSION'),
('_wmi.pyd', 'C:\\Python312\\DLLs\\_wmi.pyd', 'EXTENSION'),
('unicodedata.pyd', 'C:\\Python312\\DLLs\\unicodedata.pyd', 'EXTENSION'),
('yaml\\_yaml.cp312-win_amd64.pyd',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\yaml\\_yaml.cp312-win_amd64.pyd',
'EXTENSION'),
('_uuid.pyd', 'C:\\Python312\\DLLs\\_uuid.pyd', 'EXTENSION'),
('VCRUNTIME140.dll', 'C:\\Python312\\VCRUNTIME140.dll', 'BINARY'),
('libcrypto-3.dll', 'C:\\Python312\\DLLs\\libcrypto-3.dll', 'BINARY'),
('libssl-3.dll', 'C:\\Python312\\DLLs\\libssl-3.dll', 'BINARY'),
('libffi-8.dll', 'C:\\Python312\\DLLs\\libffi-8.dll', 'BINARY'),
('VCRUNTIME140_1.dll', 'C:\\Python312\\VCRUNTIME140_1.dll', 'BINARY'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\INSTALLER',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\INSTALLER',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\REQUESTED',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\REQUESTED',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\RECORD',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\RECORD',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\METADATA',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\METADATA',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\top_level.txt',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\top_level.txt',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\LICENSE',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\LICENSE',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\WHEEL',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\WHEEL',
'DATA'),
('setuptools\\_vendor\\jaraco\\text\\Lorem ipsum.txt',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\jaraco\\text\\Lorem '
'ipsum.txt',
'DATA'),
('base_library.zip',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\base_library.zip',
'DATA')],
[],
False,
False,
1766888487,
[('run.exe',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\bootloader\\Windows-64bit-intel\\run.exe',
'EXECUTABLE')],
'C:\\Python312\\python312.dll')
-119
View File
@@ -1,119 +0,0 @@
('C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\onyx.pkg',
{'BINARY': True,
'DATA': True,
'EXECUTABLE': True,
'EXTENSION': True,
'PYMODULE': True,
'PYSOURCE': True,
'PYZ': False,
'SPLASH': True,
'SYMLINK': False},
[('pyi-contents-directory _internal', '', 'OPTION'),
('PYZ-00.pyz',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\PYZ-00.pyz',
'PYZ'),
('struct',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\struct.pyc',
'PYMODULE'),
('pyimod01_archive',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\pyimod01_archive.pyc',
'PYMODULE'),
('pyimod02_importers',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\pyimod02_importers.pyc',
'PYMODULE'),
('pyimod03_ctypes',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\pyimod03_ctypes.pyc',
'PYMODULE'),
('pyimod04_pywin32',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\localpycs\\pyimod04_pywin32.pyc',
'PYMODULE'),
('pyiboot01_bootstrap',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\loader\\pyiboot01_bootstrap.py',
'PYSOURCE'),
('pyi_rth_inspect',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_inspect.py',
'PYSOURCE'),
('pyi_rth_pkgutil',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_pkgutil.py',
'PYSOURCE'),
('pyi_rth_multiprocessing',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_multiprocessing.py',
'PYSOURCE'),
('pyi_rth_setuptools',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\PyInstaller\\hooks\\rthooks\\pyi_rth_setuptools.py',
'PYSOURCE'),
('onyx',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\src\\onyx.py',
'PYSOURCE'),
('python312.dll', 'C:\\Python312\\python312.dll', 'BINARY'),
('_lzma.pyd', 'C:\\Python312\\DLLs\\_lzma.pyd', 'EXTENSION'),
('_bz2.pyd', 'C:\\Python312\\DLLs\\_bz2.pyd', 'EXTENSION'),
('_decimal.pyd', 'C:\\Python312\\DLLs\\_decimal.pyd', 'EXTENSION'),
('_hashlib.pyd', 'C:\\Python312\\DLLs\\_hashlib.pyd', 'EXTENSION'),
('select.pyd', 'C:\\Python312\\DLLs\\select.pyd', 'EXTENSION'),
('_socket.pyd', 'C:\\Python312\\DLLs\\_socket.pyd', 'EXTENSION'),
('_overlapped.pyd', 'C:\\Python312\\DLLs\\_overlapped.pyd', 'EXTENSION'),
('_ssl.pyd', 'C:\\Python312\\DLLs\\_ssl.pyd', 'EXTENSION'),
('_queue.pyd', 'C:\\Python312\\DLLs\\_queue.pyd', 'EXTENSION'),
('_ctypes.pyd', 'C:\\Python312\\DLLs\\_ctypes.pyd', 'EXTENSION'),
('_multiprocessing.pyd',
'C:\\Python312\\DLLs\\_multiprocessing.pyd',
'EXTENSION'),
('pyexpat.pyd', 'C:\\Python312\\DLLs\\pyexpat.pyd', 'EXTENSION'),
('_asyncio.pyd', 'C:\\Python312\\DLLs\\_asyncio.pyd', 'EXTENSION'),
('_wmi.pyd', 'C:\\Python312\\DLLs\\_wmi.pyd', 'EXTENSION'),
('unicodedata.pyd', 'C:\\Python312\\DLLs\\unicodedata.pyd', 'EXTENSION'),
('yaml\\_yaml.cp312-win_amd64.pyd',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\yaml\\_yaml.cp312-win_amd64.pyd',
'EXTENSION'),
('_uuid.pyd', 'C:\\Python312\\DLLs\\_uuid.pyd', 'EXTENSION'),
('VCRUNTIME140.dll', 'C:\\Python312\\VCRUNTIME140.dll', 'BINARY'),
('libcrypto-3.dll', 'C:\\Python312\\DLLs\\libcrypto-3.dll', 'BINARY'),
('libssl-3.dll', 'C:\\Python312\\DLLs\\libssl-3.dll', 'BINARY'),
('libffi-8.dll', 'C:\\Python312\\DLLs\\libffi-8.dll', 'BINARY'),
('VCRUNTIME140_1.dll', 'C:\\Python312\\VCRUNTIME140_1.dll', 'BINARY'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\INSTALLER',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\INSTALLER',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\REQUESTED',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\REQUESTED',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\RECORD',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\RECORD',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\METADATA',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\METADATA',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\top_level.txt',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\top_level.txt',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\LICENSE',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\LICENSE',
'DATA'),
('setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\WHEEL',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\importlib_metadata-8.0.0.dist-info\\WHEEL',
'DATA'),
('setuptools\\_vendor\\jaraco\\text\\Lorem ipsum.txt',
'C:\\Users\\oli\\AppData\\Roaming\\Python\\Python312\\site-packages\\setuptools\\_vendor\\jaraco\\text\\Lorem '
'ipsum.txt',
'DATA'),
('base_library.zip',
'C:\\Users\\oli\\Documents\\o\\Resources\\repos\\Onyx - obsidian cli '
'tool\\build\\onyx\\base_library.zip',
'DATA')],
'python312.dll',
False,
False,
False,
[],
None,
None,
None)
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-47
View File
@@ -1,47 +0,0 @@
This file lists modules PyInstaller was not able to find. This does not
necessarily mean this module is required for running your program. Python and
Python 3rd-party packages include a lot of conditional or optional modules. For
example the module 'ntpath' only exists on Windows, whereas the module
'posixpath' only exists on Posix systems.
Types if import:
* top-level: imported at the top-level - look at these first
* conditional: imported within an if-statement
* delayed: imported within a function
* optional: imported within a try-except-statement
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
tracking down the missing module yourself. Thanks!
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), getpass (delayed), setuptools._distutils.util (delayed, conditional, optional), netrc (delayed, conditional), setuptools._vendor.backports.tarfile (optional), setuptools._distutils.archive_util (optional), http.server (delayed, optional)
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), setuptools._vendor.backports.tarfile (optional), setuptools._distutils.archive_util (optional)
missing module named posix - imported by os (conditional, optional), shutil (conditional), importlib._bootstrap_external (conditional), posixpath (optional)
missing module named resource - imported by posix (top-level)
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
missing module named _scproxy - imported by urllib.request (conditional)
missing module named termios - imported by tty (top-level), click._termui_impl (conditional), getpass (optional)
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
missing module named annotationlib - imported by typing_extensions (conditional)
missing module named vms_lib - imported by platform (delayed, optional)
missing module named 'java.lang' - imported by platform (delayed, optional)
missing module named java - imported by platform (delayed)
missing module named _winreg - imported by platform (delayed, optional)
missing module named usercustomize - imported by site (delayed, optional)
missing module named sitecustomize - imported by site (delayed, optional)
missing module named readline - imported by site (delayed, optional), rlcompleter (optional)
missing module named _typeshed - imported by setuptools._distutils.dist (conditional), setuptools.glob (conditional), setuptools.compat.py311 (conditional)
missing module named _manylinux - imported by packaging._manylinux (delayed, optional), setuptools._vendor.packaging._manylinux (delayed, optional), setuptools._vendor.wheel.vendored.packaging._manylinux (delayed, optional)
missing module named importlib_resources - imported by setuptools._vendor.jaraco.text (optional)
missing module named trove_classifiers - imported by setuptools.config._validate_pyproject.formats (optional)
missing module named pyimod02_importers - imported by C:\Users\oli\AppData\Roaming\Python\Python312\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
missing module named fcntl - imported by subprocess (optional)
File diff suppressed because it is too large. Load diff
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
+248 -54
View File
@@ -13,6 +13,14 @@ from typing import List, Union, Optional, Dict, Any
from urllib.parse import quote
class OnyxCLI:
_PERIODIC_DEFAULTS: Dict[str, Dict[str, str]] = {
'daily': {'format': 'YYYY-MM-DD', 'folder': '', 'template': ''},
'weekly': {'format': 'YYYY-[W]WW', 'folder': '', 'template': ''},
'monthly': {'format': 'YYYY-MM', 'folder': '', 'template': ''},
'quarterly': {'format': 'YYYY-[Q]Q', 'folder': '', 'template': ''},
'yearly': {'format': 'YYYY', 'folder': '', 'template': ''},
}
def __init__(self):
self.config_file = Path.home() / '.onyx-cli' / 'config.yaml'
self._ensure_config_exists()
@@ -39,10 +47,40 @@ class OnyxCLI:
def _get_vault_path(self, vault_name: str) -> Path:
config = yaml.safe_load(self.config_file.read_text(encoding='utf-8-sig'))
vault_path = config.get('vaults', {}).get(vault_name)
if not vault_path:
vault_config = config.get('vaults', {}).get(vault_name)
if not vault_config:
raise click.UsageError(f"Vault '{vault_name}' not found in config")
return Path(vault_path)
# Support both string path (old format) and dict format (new format)
if isinstance(vault_config, str):
return Path(vault_config)
elif isinstance(vault_config, dict):
vault_path = vault_config.get('path')
if not vault_path:
raise click.UsageError(f"Vault '{vault_name}' configuration missing 'path' key")
return Path(vault_path)
else:
raise click.UsageError(f"Invalid vault configuration format for '{vault_name}'")
def _get_vault_config(self, vault_name: str) -> Dict[str, Any]:
"""Get the full vault configuration for a given vault name.
Returns a dict with 'path' and optionally 'path_prefix'.
Converts old string format to new dict format for consistency.
"""
config = yaml.safe_load(self.config_file.read_text(encoding='utf-8-sig'))
vault_config = config.get('vaults', {}).get(vault_name)
if not vault_config:
raise click.UsageError(f"Vault '{vault_name}' not found in config")
# Convert string format to dict format for consistency
if isinstance(vault_config, str):
return {'path': vault_config}
elif isinstance(vault_config, dict):
return vault_config
else:
raise click.UsageError(f"Invalid vault configuration format for '{vault_name}'")
def _get_vault_and_path(self, vault: Optional[str] = None) -> tuple[str, Path]:
vault_name = vault or self.default_vault
@@ -51,22 +89,56 @@ class OnyxCLI:
vault_path = self._get_vault_path(vault_name)
return vault_name, vault_path
def set_default_vault(self, vault_name: str, vault_path: Optional[str] = None, path_prefix: Optional[str] = None):
"""Set the default vault and optionally configure its path and path_prefix.
Args:
vault_name: Name of the vault to set as default
vault_path: Optional path to the vault directory
path_prefix: Optional path prefix for resolving relative paths in frontmatter
"""
config = yaml.safe_load(self.config_file.read_text(encoding='utf-8-sig'))
# Set the default vault
config['default_vault'] = vault_name
# Update vault configuration if path is provided
if vault_path:
if 'vaults' not in config:
config['vaults'] = {}
# Create vault config dict
vault_config = {'path': str(Path(vault_path).resolve())}
# Add path_prefix if provided
if path_prefix:
vault_config['path_prefix'] = str(Path(path_prefix).resolve())
config['vaults'][vault_name] = vault_config
# Write updated config
self.config_file.write_text(yaml.dump(config, default_flow_style=False), encoding='utf-8-sig')
# Update instance variables
self.default_vault = vault_name
if vault_path:
self.vault_path = Path(vault_path).resolve()
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(encoding='utf-8-sig'))
vault_path = config.get('vaults', {}).get(self.default_vault)
if not vault_path:
try:
vault_config = self._get_vault_config(self.default_vault)
except click.UsageError:
raise click.UsageError(
f"Vault '{self.default_vault}' not found in config. Please set it up with:\n"
f"onyx set-default \"{self.default_vault}\" --path \"path/to/vault\""
)
click.echo(f"Default vault: {self.default_vault}")
click.echo(f"Path: {vault_path}")
click.echo(f"Path: {vault_config['path']}")
def _get_template_folder(self, vault_path: Path) -> Optional[Path]:
"""
@@ -256,21 +328,7 @@ class OnyxCLI:
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 with date navigation."""
vault_name, vault_path = self._get_vault_and_path(vault)
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(encoding='utf-8-sig'))
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
settings = self._resolve_periodic_settings(vault_name, vault_path, note_type)
# Date calculation
base_date = None
@@ -317,22 +375,11 @@ class OnyxCLI:
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'])
# Handle week format specially for ISO weeks
# Handle week and quarter formats specially (no direct strftime equivalent)
filename = None
if 'W' in settings['format'] and '[W]' in settings['format']:
if note_type == 'weekly' and 'W' in settings['format'] and '[W]' in settings['format']:
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 = base_date.strftime('%G') # ISO year (4 digits)
@@ -340,6 +387,11 @@ class OnyxCLI:
year = base_date.strftime('%g') # ISO year (2 digits)
week = base_date.strftime('%V') # ISO week number
filename = f"{year}-W{week}"
elif note_type == 'quarterly' and 'Q' in settings['format']:
year_format = 'yyyy' if 'yyyy' in settings['format'] else ('YYYY' if 'YYYY' in settings['format'] else 'yy')
year = base_date.strftime('%Y') if year_format in ('yyyy', 'YYYY') else base_date.strftime('%y')
quarter = (base_date.month - 1) // 3 + 1
filename = f"{year}-Q{quarter}"
else:
try:
filename = base_date.strftime(date_format)
@@ -517,7 +569,7 @@ class OnyxCLI:
self._update_frontmatter(note_path, updates)
click.echo(f"Updated frontmatter for {note_name}")
def frontmatter_view(self, note_name: str, keys: tuple, value: str = None, vault: str = None, open_file: bool = False):
def frontmatter_view(self, note_name: str, keys: tuple, value: str = None, vault: str = None, open_file: bool = False, output_path: Union[bool, str, None] = None):
vault_name, vault_path = self._get_vault_and_path(vault)
note_path = vault_path / note_name
if not note_path.suffix:
@@ -557,7 +609,26 @@ class OnyxCLI:
else:
# If single key requested and no value check, print raw value
if len(keys) == 1 and len(sub_keys) == 1:
click.echo(str(frontmatter[k]))
val = str(frontmatter[k])
# Handle path resolution if requested
if output_path is not None:
# Determine prefix
prefix = ""
if isinstance(output_path, str):
# Use provided custom prefix
prefix = output_path
elif output_path is True:
# Use prefix from config
vault_config = self._get_vault_config(vault_name)
prefix = vault_config.get('path_prefix', '')
if prefix:
# Join prefix and value using OS separator
# Normalize separators to handle potential mix of forward/backslashes
val = str(Path(prefix) / val)
click.echo(val)
else:
click.echo(yaml.dump({k: frontmatter[k]}, default_flow_style=False).strip())
@@ -697,8 +768,90 @@ class OnyxCLI:
'template': ''
}
def _resolve_periodic_settings(self, vault_name: str, vault_path: Path, note_type: str) -> Dict[str, Any]:
"""
Resolve folder/format/template settings for a periodic note type.
Priority (highest first):
1. onyx's own config (`onyx periodic --edit`, stored in ~/.onyx-cli/config.yaml)
2. Obsidian's Periodic Notes plugin (or core Daily Notes plugin for 'daily')
3. Built-in defaults for that note type
Each note type is resolved independently - a type with no plugin/config data
never inherits another type's folder or template.
"""
settings = dict(self._PERIODIC_DEFAULTS.get(note_type, self._PERIODIC_DEFAULTS['daily']))
# Layer: Obsidian plugin auto-detection
if note_type == 'daily':
settings.update(self._get_daily_note_settings(vault_path))
else:
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'))
note_config = config.get(note_type, {})
if note_config.get('enabled', False):
if note_config.get('format'):
settings['format'] = note_config['format']
if 'folder' in note_config:
settings['folder'] = note_config.get('folder', '')
if 'template' in note_config:
settings['template'] = note_config.get('template', '')
except (json.JSONDecodeError, KeyError):
pass
# Layer: onyx's own config.yaml (explicit user intent, wins over everything)
try:
vault_config = self._get_vault_config(vault_name)
except click.UsageError:
vault_config = {}
user_settings = (vault_config.get('periodic_notes') or {}).get(note_type, {})
for key in ('folder', 'format', 'template'):
if user_settings.get(key):
settings[key] = user_settings[key]
return settings
def set_periodic_config(self, note_type: str, folder: str = None, format: str = None,
template: str = None, vault: str = None):
"""Persist folder/format/template overrides for a periodic note type in onyx's own config."""
vault_name, _ = self._get_vault_and_path(vault)
config = yaml.safe_load(self.config_file.read_text(encoding='utf-8-sig'))
vaults = config.setdefault('vaults', {})
vault_entry = vaults.get(vault_name)
if isinstance(vault_entry, str):
vault_entry = {'path': vault_entry}
elif not isinstance(vault_entry, dict):
raise click.UsageError(f"Vault '{vault_name}' not found in config")
periodic = vault_entry.setdefault('periodic_notes', {})
type_entry = periodic.setdefault(note_type, {})
if folder is not None:
type_entry['folder'] = folder
if format is not None:
type_entry['format'] = format
if template is not None:
type_entry['template'] = template
vaults[vault_name] = vault_entry
config['vaults'] = vaults
self.config_file.write_text(yaml.dump(config, default_flow_style=False), encoding='utf-8-sig')
click.echo(f"Updated {note_type} note settings for vault '{vault_name}'")
def print_periodic_config(self, note_type: str, vault: str = None):
"""Print the resolved folder/format/template settings for a periodic note type."""
vault_name, vault_path = self._get_vault_and_path(vault)
settings = self._resolve_periodic_settings(vault_name, vault_path, note_type)
click.echo(f"{note_type} note settings for vault '{vault_name}':")
click.echo(f" folder: {settings['folder'] or '(vault root)'}")
click.echo(f" format: {settings['format']}")
click.echo(f" template: {settings['template'] or '(none)'}")
# CLI Commands
@click.version_option(version='0.0.1', prog_name='onyx')
@click.group(name='onyx')
def cli():
"""Onyx - Interact with Obsidian vaults from the command line
@@ -719,7 +872,8 @@ def cli():
@cli.command()
@click.argument('vault_name')
@click.option('--path', help="Path to the vault directory")
def set_default(vault_name, path):
@click.option('--path-prefix', help="Base path prepended to relative frontmatter path values when using 'onyx frontmatter --view --output-path'")
def set_default(vault_name, path, path_prefix):
"""Set or switch the default vault
USAGE:
@@ -728,7 +882,7 @@ def set_default(vault_name, path):
# Convert Windows backslashes to forward slashes if needed
if path:
path = str(Path(path))
OnyxCLI().set_default_vault(vault_name, path)
OnyxCLI().set_default_vault(vault_name, path, path_prefix)
@cli.command()
def print_default():
@@ -757,7 +911,9 @@ def open(note_name, vault):
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."""
Folder, filename format, and template are resolved from onyx's own config
(see `onyx periodic --type daily`), falling back to Obsidian's Daily Notes
or Periodic Notes plugin settings, then to built-in defaults."""
OnyxCLI().daily_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@@ -766,7 +922,9 @@ def daily(vault, date, next_, previous):
@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 weekly(vault, date, next_, previous):
"""Create or open a weekly note for a specific date, next, or previous week"""
"""Create or open a weekly note for a specific date, next, or previous week
Folder, filename format, and template are configurable via `onyx periodic --type weekly`."""
OnyxCLI().weekly_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@@ -775,7 +933,9 @@ def weekly(vault, date, next_, previous):
@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 monthly(vault, date, next_, previous):
"""Create or open a monthly note for a specific date, next, or previous month"""
"""Create or open a monthly note for a specific date, next, or previous month
Folder, filename format, and template are configurable via `onyx periodic --type monthly`."""
OnyxCLI().monthly_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@@ -784,7 +944,9 @@ def monthly(vault, date, next_, previous):
@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 quarterly(vault, date, next_, previous):
"""Create or open a quarterly note for a specific date, next, or previous quarter"""
"""Create or open a quarterly note for a specific date, next, or previous quarter
Folder, filename format, and template are configurable via `onyx periodic --type quarterly`."""
OnyxCLI().quarterly_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@@ -793,9 +955,43 @@ def quarterly(vault, date, next_, previous):
@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 yearly(vault, date, next_, previous):
"""Create or open a yearly note for a specific date, next, or previous year"""
"""Create or open a yearly note for a specific date, next, or previous year
Folder, filename format, and template are configurable via `onyx periodic --type yearly`."""
OnyxCLI().yearly_note(vault, date=date, next_=next_, previous=previous)
@cli.command()
@click.option('--type', 'note_type', required=True,
type=click.Choice(['daily', 'weekly', 'monthly', 'quarterly', 'yearly']),
help="Periodic note type to configure")
@click.option('--view', is_flag=True, help="View the resolved settings")
@click.option('--edit', is_flag=True, help="Edit onyx's own settings for this note type")
@click.option('--folder', help="Folder where notes of this type are stored (relative to vault root)")
@click.option('--format', 'note_format', help="Moment.js-style filename format, e.g. YYYY-MM-DD, YYYY-[W]WW")
@click.option('--template', help="Path to template file (relative to vault root)")
@click.option('--vault', help="Vault name (if not using default)")
def periodic(note_type, view, edit, folder, note_format, template, vault):
"""View or edit onyx's own folder/format/template settings for a periodic note type.
These settings take priority over anything detected from Obsidian's Daily Notes
or Periodic Notes plugins, and are the only source of truth for note types that
plugin isn't configured for.
USAGE:
onyx periodic --type weekly --view
onyx periodic --type weekly --edit --folder "periodic/weekly" --format "YYYY-[W]WW" --template "resources/template/weekly-note.md"
"""
if sum([view, edit]) != 1:
raise click.UsageError("Exactly one of --view or --edit must be specified")
cli = OnyxCLI()
if edit:
if not any([folder, note_format, template]):
raise click.UsageError("Provide at least one of --folder, --format, --template with --edit")
cli.set_periodic_config(note_type, folder=folder, format=note_format, template=template, vault=vault)
else:
cli.print_periodic_config(note_type, vault)
@cli.command()
@click.argument('note_name')
@click.option('--content', default="", help="Content to write to the note")
@@ -803,10 +999,13 @@ def yearly(vault, date, next_, previous):
@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")
@click.option('--template', help="Template to use")
@click.option('--template', help="Template name (without extension) from the vault's Templater or core Templates folder; using this implies --open")
def create(note_name, content, vault, overwrite, append, open_after, template):
"""Create or modify a note in the vault
--template looks up the vault's Templater (or core Templates) folder and
prepends its content; the note is then opened automatically.
USAGE:
onyx create "my-note"
onyx create "my-note" --content "Some content" --open
@@ -855,7 +1054,8 @@ def delete(note_path, vault):
@click.option('--value', multiple=True, help="Value to set or check for")
@click.option('--open', 'open_file', is_flag=True, help="Open the file referenced in the value")
@click.option('--vault', help="Vault name (if not using default)")
def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_file, vault):
@click.option('--output-path', is_flag=False, flag_value=True, default=None, help="Resolve relative paths. Can be a flag (uses config prefix) or a string (custom prefix).")
def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_file, vault, output_path):
"""Manage YAML frontmatter in notes
Must specify exactly one action: --edit, --view, --clear, or --delete
@@ -880,17 +1080,11 @@ def frontmatter_command(note_name, edit, view, clear, delete, key, value, open_f
# For view, we ignore value unless it's for checking existence, which is complex with multiple keys
# For now, let's pass single value if provided, but view supports multiple keys
val = value[0] if value else None
cli.frontmatter_view(note_name, key, val, vault, open_file)
cli.frontmatter_view(note_name, key, val, vault, open_file, output_path)
elif clear:
cli.frontmatter_clear(note_name, key, 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()
Binary file not shown.
+132 -13
View File
@@ -3,9 +3,10 @@ import unittest
import yaml
import shutil
from pathlib import Path
from src.onyx import OnyxCLI
from src.onyx import OnyxCLI, cli
from unittest.mock import patch, MagicMock
import click
from click.testing import CliRunner
from datetime import datetime
class TestOnyxCLI(unittest.TestCase):
@@ -140,8 +141,8 @@ Test content"""
# 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')
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(encoding='utf-8-sig')
frontmatter = yaml.safe_load(content.split('---')[1])
@@ -150,38 +151,38 @@ Test content"""
# 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())
self.cli.frontmatter_view(test_note, ('tags',))
mock_echo.assert_called_with("['test', 'new']")
# 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',), 'test')
mock_echo.assert_called_with('tags: true')
self.cli.frontmatter_view(test_note, 'tags', 'nonexistent')
mock_echo.assert_called_with('false')
self.cli.frontmatter_view(test_note, ('tags',), 'nonexistent')
mock_echo.assert_called_with('tags: false')
# Test frontmatter --clear
self.cli.frontmatter_clear(test_note, 'tags')
self.cli.frontmatter_clear(test_note, ('tags',))
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
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')
self.cli.frontmatter_clear(test_note, ('status,title',))
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
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')
self.cli.frontmatter_delete(test_note, ('tags',))
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
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')
self.cli.frontmatter_delete(test_note, ('status,title',))
content = (self.test_dir / test_note).read_text(encoding='utf-8-sig')
# After deleting all keys, there should be no frontmatter section
self.assertNotIn('---', content)
@@ -217,6 +218,59 @@ Test content"""
# Daily note should be empty since no template is configured
self.assertEqual(daily_note.read_text(encoding='utf-8-sig'), '')
def test_weekly_note_does_not_inherit_daily_folder(self):
"""Regression: weekly notes must not silently reuse the daily note's folder/template."""
obsidian_dir = self.test_dir / '.obsidian'
obsidian_dir.mkdir(parents=True, exist_ok=True)
(obsidian_dir / 'daily-notes.json').write_text(
'{"format": "YYYY-MM-DD", "folder": "periodic/daily", "template": "templates/daily.md"}',
encoding='utf-8-sig'
)
self.cli.weekly_note(date="2025-11-27")
weekly_note = self.test_dir / '2025-W48.md'
self.assertTrue(weekly_note.exists())
self.assertFalse((self.test_dir / 'periodic' / 'daily' / '2025-W48.md').exists())
def test_periodic_config_edit_and_resolution(self):
"""onyx's own periodic config wins over plugin/defaults and is used by weekly_note()."""
template_path = self.test_dir / 'templates' / 'weekly.md'
template_path.parent.mkdir(parents=True, exist_ok=True)
template_path.write_text('# Weekly template', encoding='utf-8-sig')
self.cli.set_periodic_config(
'weekly', folder='periodic/weekly', format='YYYY-[W]WW', template='templates/weekly.md'
)
self.cli.weekly_note(date="2025-11-27")
weekly_note = self.test_dir / 'periodic' / 'weekly' / '2025-W48.md'
self.assertTrue(weekly_note.exists())
self.assertEqual(weekly_note.read_text(encoding='utf-8-sig'), '# Weekly template')
config = yaml.safe_load(self.cli.config_file.read_text(encoding='utf-8-sig'))
saved = config['vaults']['test_vault']['periodic_notes']['weekly']
self.assertEqual(saved['folder'], 'periodic/weekly')
self.assertEqual(saved['format'], 'YYYY-[W]WW')
self.assertEqual(saved['template'], 'templates/weekly.md')
def test_periodic_config_view(self):
"""print_periodic_config reports the resolved settings, not raw config fragments."""
self.cli.set_periodic_config('monthly', folder='periodic/monthly')
with patch('click.echo') as mock_echo:
self.cli.print_periodic_config('monthly')
printed = '\n'.join(call.args[0] for call in mock_echo.call_args_list)
self.assertIn('periodic/monthly', printed)
self.assertIn('YYYY-MM', printed)
def test_quarterly_note_filename(self):
"""Quarterly notes must resolve the actual quarter number, not a literal 'Q'."""
self.cli.quarterly_note(date="2025-11-27")
self.assertTrue((self.test_dir / '2025-Q4.md').exists())
@patch('subprocess.run')
@patch('os.startfile')
def test_open_note(self, mock_startfile, mock_run):
@@ -251,5 +305,70 @@ Test content"""
with self.assertRaises(click.UsageError):
self.cli.delete_note('nonexistent.md')
def test_frontmatter_path_resolution(self):
"""Test frontmatter path resolution with --output-path"""
# Create a test note with a relative path
note_content = """---
path: Projects/my-project
---
Test content"""
test_note = 'path_test.md'
self.cli.create_note(test_note, note_content)
# Setup vault with path prefix
prefix = str(self.test_dir / 'prefix_root')
self.cli.set_default_vault('test_vault', str(self.test_dir), path_prefix=prefix)
# Test 1: No --output-path (should return raw value)
with patch('click.echo') as mock_echo:
self.cli.frontmatter_view(test_note, ('path',), output_path=None)
mock_echo.assert_called_with('Projects/my-project')
# Test 2: --output-path flag (should use config prefix)
expected_path = str(Path(prefix).resolve() / 'Projects/my-project')
with patch('click.echo') as mock_echo:
self.cli.frontmatter_view(test_note, ('path',), output_path=True)
mock_echo.assert_called_with(expected_path)
# Test 3: --output-path with custom value
custom_prefix = str(self.test_dir / 'custom')
expected_custom_path = str(Path(custom_prefix) / 'Projects/my-project')
with patch('click.echo') as mock_echo:
self.cli.frontmatter_view(test_note, ('path',), output_path=custom_prefix)
mock_echo.assert_called_with(expected_custom_path)
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(encoding='utf-8-sig'))
self.assertEqual(config['default_vault'], 'new_vault')
# Check new dict structure
self.assertEqual(config['vaults']['new_vault']['path'], str(self.test_dir.resolve()))
# Test updating with path_prefix
prefix = "C:\\Users\\test"
self.cli.set_default_vault('new_vault', str(self.test_dir), path_prefix=prefix)
config = yaml.safe_load(self.cli.config_file.read_text(encoding='utf-8-sig'))
self.assertEqual(config['vaults']['new_vault']['path_prefix'], str(Path(prefix).resolve()))
def test_cli_version_flag(self):
"""onyx --version must work at the root command group (no separate 'version' subcommand)."""
result = CliRunner().invoke(cli, ['--version'])
self.assertEqual(result.exit_code, 0)
self.assertIn('onyx, version', result.output)
self.assertNotIn('version', [c for c in cli.commands])
def test_print_default_shows_path_not_raw_dict(self):
"""Regression: print_default must print the path string, not the dict, for long-form vault configs."""
self.cli.set_default_vault('test_vault', str(self.test_dir.resolve()), path_prefix=str(self.test_dir))
with patch('click.echo') as mock_echo:
self.cli.print_default()
printed = '\n'.join(call.args[0] for call in mock_echo.call_args_list)
self.assertIn(str(self.test_dir.resolve()), printed)
self.assertNotIn('path_prefix', printed)
if __name__ == '__main__':
unittest.main()