fix: write notes and config as LF without BOM on every OS

This commit is contained in:
olivier committed 2026-10-19 11:21:03 -04:00
1 parent 466fef3c23
commit d77fac61c8
2 files changed
+36 -11

No files matched your search

+22 -11
View File
@@ -12,6 +12,18 @@ import re
from typing import List, Union, Optional, Dict, Any from typing import List, Union, Optional, Dict, Any
from urllib.parse import quote from urllib.parse import quote
def _write_text(path: Path, text: str, mode: str = 'w') -> None:
"""Write UTF-8 without BOM and with LF line endings on every OS.
Python's text mode would otherwise translate '\\n' to os.linesep (CRLF on
Windows), and 'utf-8-sig' would prepend a BOM before the frontmatter.
Reads keep 'utf-8-sig' so files that already carry a BOM still parse.
"""
with path.open(mode, encoding='utf-8', newline='\n') as f:
f.write(text)
class OnyxCLI: class OnyxCLI:
_PERIODIC_DEFAULTS: Dict[str, Dict[str, str]] = { _PERIODIC_DEFAULTS: Dict[str, Dict[str, str]] = {
'daily': {'format': 'YYYY-MM-DD', 'folder': '', 'template': ''}, 'daily': {'format': 'YYYY-MM-DD', 'folder': '', 'template': ''},
@@ -37,7 +49,7 @@ class OnyxCLI:
def _ensure_config_exists(self): def _ensure_config_exists(self):
self.config_file.parent.mkdir(parents=True, exist_ok=True) self.config_file.parent.mkdir(parents=True, exist_ok=True)
if not self.config_file.exists(): if not self.config_file.exists():
self.config_file.write_text(yaml.dump({'default_vault': None, 'vaults': {}}), encoding='utf-8-sig') _write_text(self.config_file, yaml.dump({'default_vault': None, 'vaults': {}}))
def _load_default_vault(self): def _load_default_vault(self):
if self.config_file.exists(): if self.config_file.exists():
@@ -117,7 +129,7 @@ class OnyxCLI:
config['vaults'][vault_name] = vault_config config['vaults'][vault_name] = vault_config
# Write updated config # Write updated config
self.config_file.write_text(yaml.dump(config, default_flow_style=False), encoding='utf-8-sig') _write_text(self.config_file, yaml.dump(config, default_flow_style=False))
# Update instance variables # Update instance variables
self.default_vault = vault_name self.default_vault = vault_name
@@ -209,10 +221,9 @@ class OnyxCLI:
else: else:
mode = 'w' mode = 'w'
with note_path.open(mode, encoding='utf-8-sig') as f: if mode == 'a':
if append and note_path.exists(): content = '\n' + content
f.write('\n') _write_text(note_path, content, mode)
f.write(content)
click.echo(f"Note {'updated' if note_path.exists() else 'created'}: {note_path}") click.echo(f"Note {'updated' if note_path.exists() else 'created'}: {note_path}")
@@ -485,7 +496,7 @@ class OnyxCLI:
content = md_file.read_text(encoding='utf-8-sig') content = md_file.read_text(encoding='utf-8-sig')
updated_content = re.sub(old_link_pattern, new_link, content) updated_content = re.sub(old_link_pattern, new_link, content)
if updated_content != content: if updated_content != content:
md_file.write_text(updated_content, encoding='utf-8-sig') _write_text(md_file, updated_content)
click.echo(f"Moved {current_path} to {new_path}") click.echo(f"Moved {current_path} to {new_path}")
@@ -529,7 +540,7 @@ class OnyxCLI:
new_content += '---\n' new_content += '---\n'
new_content += rest_content if fm_length else content new_content += rest_content if fm_length else content
note_path.write_text(new_content, encoding='utf-8-sig') _write_text(note_path, new_content)
def frontmatter_edit(self, note_name: str, keys: tuple, values: tuple = None, vault: str = None): def frontmatter_edit(self, note_name: str, keys: tuple, values: tuple = None, vault: str = None):
vault_name, vault_path = self._get_vault_and_path(vault) vault_name, vault_path = self._get_vault_and_path(vault)
@@ -711,7 +722,7 @@ class OnyxCLI:
else: else:
new_content = rest_content new_content = rest_content
note_path.write_text(new_content, encoding='utf-8-sig') _write_text(note_path, new_content)
click.echo(f"Deleted frontmatter keys from {note_name}") click.echo(f"Deleted frontmatter keys from {note_name}")
else: else:
click.echo("No matching keys found in frontmatter") click.echo("No matching keys found in frontmatter")
@@ -837,7 +848,7 @@ class OnyxCLI:
vaults[vault_name] = vault_entry vaults[vault_name] = vault_entry
config['vaults'] = vaults config['vaults'] = vaults
self.config_file.write_text(yaml.dump(config, default_flow_style=False), encoding='utf-8-sig') _write_text(self.config_file, yaml.dump(config, default_flow_style=False))
click.echo(f"Updated {note_type} note settings for vault '{vault_name}'") click.echo(f"Updated {note_type} note settings for vault '{vault_name}'")
def print_periodic_config(self, note_type: str, vault: str = None): def print_periodic_config(self, note_type: str, vault: str = None):
@@ -851,7 +862,7 @@ class OnyxCLI:
# CLI Commands # CLI Commands
@click.version_option(version='0.1.0', prog_name='onyx') @click.version_option(version='0.1.1', prog_name='onyx')
@click.group(name='onyx') @click.group(name='onyx')
def cli(): def cli():
"""Onyx - Interact with Obsidian vaults from the command line """Onyx - Interact with Obsidian vaults from the command line
+14
View File
@@ -51,6 +51,20 @@ class TestOnyxCLI(unittest.TestCase):
note_path = self.test_dir / 'test.md' note_path = self.test_dir / 'test.md'
self.assertTrue(note_path.exists()) self.assertTrue(note_path.exists())
def test_writes_keep_lf_without_bom(self):
"""Append and frontmatter edits write LF, no BOM, even on Windows"""
note_path = self.test_dir / 'lf.md'
note_path.write_bytes(b'---\nstatus: draft\n---\n# Journal\n')
self.cli.create_note('lf.md', '### 10:00 - Entry\nline', append=True)
self.cli.frontmatter_edit('lf', ('status',), ('done',))
data = note_path.read_bytes()
self.assertNotIn(b'\r', data)
self.assertFalse(data.startswith(b'\xef\xbb\xbf'))
self.assertIn(b'status: done', data)
self.assertTrue(data.endswith(b'# Journal\n\n### 10:00 - Entry\nline'))
@unittest.skip("Method export_to_csv not implemented") @unittest.skip("Method export_to_csv not implemented")
def test_export_to_csv(self): def test_export_to_csv(self):
"""Test exporting note frontmatter to CSV""" """Test exporting note frontmatter to CSV"""