Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/+touch-readonly.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow ``Path.touch()`` to update timestamps on existing read-only files.
3 changes: 1 addition & 2 deletions path/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1415,8 +1415,7 @@ def touch(self) -> Self:
"""Set the access/modified times of this file to the current time.
Create the file if it does not exist.
"""
os.close(os.open(self, os.O_WRONLY | os.O_CREAT, 0o666))
os.utime(self, None)
pathlib.Path(self).touch()
return self

def remove(self) -> Self:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,20 @@ class TestScratchDir:
Tests that run in a temporary directory (does not test TempDir class)
"""

@pytest.mark.skipif(os.name == 'nt', reason='POSIX file permissions')
def test_touch_readonly_file(self, tmp_path):
target = Path(tmp_path / 'readonly.txt')
target.write_text('preserved content')
target.utime((1_000_000_000, 1_000_000_000))
target.chmod(0o444)
try:
assert target.touch() is target
assert target.stat().st_mtime > 1_000_000_000
assert target.stat().st_mode & 0o777 == 0o444
assert target.read_text(encoding='utf-8') == 'preserved content'
finally:
target.chmod(0o644)

def test_context_manager(self, tmpdir):
"""Can be used as context manager for chdir."""
d = Path(tmpdir)
Expand Down