Skip to content

Commit

Permalink
Preserve journal file permissions.
Browse files Browse the repository at this point in the history
Fixes jbms#231
  • Loading branch information
falsifian committed Mar 21, 2024
1 parent c2c4c55 commit 2288f7b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
13 changes: 12 additions & 1 deletion beancount_import/journal_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,11 +235,22 @@ def get_partially_booked_entries(pre_booking_entries: Entries,


class _AtomicWriter(atomicwrites.AtomicWriter):
"""Wrapper that calls `os.stat` after close but before the rename."""
"""Wrapper that preserves permissions and calls `os.stat` after close.
Two changes on top of AtomicWriter:
- Preserve permissions of the file.
- Calls `os.stat` after close but before the rename.
"""

def __init__(self, path, **kwargs):
super().__init__(path, **kwargs)
self.stat_result_after_close = None
self._permissions = os.stat(path).st_mode

def get_fileobject(self, **kwargs):
f = super().get_fileobject(**kwargs)
os.chmod(f.name, mode=self._permissions)
return f

def sync(self, f):
super().sync(f)
Expand Down
25 changes: 25 additions & 0 deletions beancount_import/journal_editor_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
from beancount.core.data import Transaction, Posting, EMPTY_SET
from beancount.core.number import MISSING, Decimal
from beancount.core.amount import Amount
import os
import pytest
import py
import stat

from . import journal_editor
from . import test_util
Expand Down Expand Up @@ -139,6 +141,29 @@ def test_simple(tmpdir):
""")
check_journal_entries(editor)

def test_permissions(tmpdir):
journal_path = create_journal(
tmpdir, """
2015-02-01 * "Test transaction"
Assets:Account-A 100 USD
Assets:Account-B
""")
# Set unusual permissions. We'll check that they are preserved.
os.chmod(journal_path, mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXGRP)
# In case the OS doesn't support arbitrary inputs to os.chmod,
# check what we were actually able to set the mode to.
original_mode = os.stat(journal_path).st_mode
editor = journal_editor.JournalEditor(journal_path)
stage = editor.stage_changes()
old_entry = editor.entries[0]
new_entry = old_entry._replace(postings=[
old_entry.postings[0]._replace(meta=dict(note="Hello")),
old_entry.postings[1],
])
stage.change_entry(old_entry, new_entry)
result = stage.apply()
assert os.stat(journal_path).st_mode == original_mode


def test_transaction_add_meta(tmpdir):
journal_path = create_journal(
Expand Down

0 comments on commit 2288f7b

Please sign in to comment.