Skip to content

Commit 6dbbc3e

Browse files
committed
fix: cog restores the current directory
Without this fix, if the user code changed the directory, then cog wouldn't be able to write the output file.
1 parent 10de5fb commit 6dbbc3e

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

CHANGELOG.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ These are changes to Cog over time.
2121
Unreleased
2222
----------
2323

24+
- Embedded code can change the current directory, cog will change back to the
25+
original directory when the code is done.
26+
2427
- Dropped support for Python 3.7 and 3.8, and added 3.13.
2528

2629

cogapp/cogapp.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,8 @@ def process_file(self, file_in, file_out, fname=None, globals=None):
413413
file_name_out = file_out
414414
file_out = file_out_to_close = self.open_output_file(file_out)
415415

416+
start_dir = os.getcwd()
417+
416418
try:
417419
file_in = NumberedFileReader(file_in)
418420

@@ -592,6 +594,7 @@ def process_file(self, file_in, file_out, fname=None, globals=None):
592594
file_in_to_close.close()
593595
if file_out_to_close:
594596
file_out_to_close.close()
597+
os.chdir(start_dir)
595598

596599
# A regex for non-empty lines, used by suffixLines.
597600
re_non_empty_lines = re.compile(r"^\s*\S+.*$", re.MULTILINE)

cogapp/test_cogapp.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1409,6 +1409,37 @@ def test_verbosity2(self):
14091409
output, "Cogging unchanged.cog\nCogging changed.cog (changed)\n"
14101410
)
14111411

1412+
def test_change_dir(self):
1413+
# The code can change directories, cog will move us back.
1414+
d = {
1415+
"sub": {
1416+
"data.txt": "Hello!",
1417+
},
1418+
"test.cog": """\
1419+
//[[[cog
1420+
import os
1421+
os.chdir("sub")
1422+
cog.outl(open("data.txt").read())
1423+
//]]]
1424+
//[[[end]]]
1425+
""",
1426+
"test.out": """\
1427+
//[[[cog
1428+
import os
1429+
os.chdir("sub")
1430+
cog.outl(open("data.txt").read())
1431+
//]]]
1432+
Hello!
1433+
//[[[end]]]
1434+
""",
1435+
}
1436+
1437+
make_files(d)
1438+
self.cog.callable_main(["argv0", "-r", "test.cog"])
1439+
self.assertFilesSame("test.cog", "test.out")
1440+
output = self.output.getvalue()
1441+
self.assertIn("(changed)", output)
1442+
14121443

14131444
class CogTestLineEndings(TestCaseWithTempDir):
14141445
"""Tests for -U option (force LF line-endings in output)."""

0 commit comments

Comments
 (0)