Repository: asottile/babi

Issue:
TODO: make directories if they don't exist
This issue is equivalent to the comment in `babi/screen.py` at line 490. I would like to work on this to resolve the TODO-comment.

Discussion:

Patch:
diff --git a/babi/screen.py b/babi/screen.py
index bca6656..80c6d7a 100644
--- a/babi/screen.py
+++ b/babi/screen.py
@@ -487,7 +487,6 @@ class Screen:
     def save(self) -> PromptResult | None:
         self.file.finalize_previous_action()
 
-        # TODO: make directories if they don't exist
         # TODO: maybe use mtime / stat as a shortcut for hashing below
         # TODO: strip trailing whitespace?
         # TODO: save atomically?
@@ -513,6 +512,7 @@ class Screen:
             return PromptResult.CANCELLED
 
         try:
+            os.makedirs(os.path.dirname(self.file.filename), exist_ok=True)
             with open(
                 self.file.filename, 'w', encoding='UTF-8', newline='',
             ) as f:


Test patch:
diff --git a/tests/features/save_test.py b/tests/features/save_test.py
index 78bcde8..5465a53 100644
--- a/tests/features/save_test.py
+++ b/tests/features/save_test.py
@@ -276,3 +276,17 @@ def test_vim_force_exit(run, tmpdir):
         trigger_command_mode(h)
         h.press_and_enter(':q!')
         h.await_exit()
+
+
+def test_save_on_exit_with_not_existing_directory(run, tmpdir):
+    f = tmpdir.join('test/nested/dirs/f')
+    with run(str(f)) as fake_h:
+        fake_h.press('hello')
+        fake_h.await_text('hello')
+        fake_h.press('^X')
+        fake_h.await_text('file is modified - save [yes, no]?')
+        fake_h.press('y')
+        fake_h.await_text('enter filename: ')
+        fake_h.press('Enter')
+        fake_h.await_exit()
+    assert f.read() == 'hello\n'