-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.py
More file actions
58 lines (51 loc) · 2.38 KB
/
basic.py
File metadata and controls
58 lines (51 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import os
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from typing import Generator
from ..config import IConfig
from ..editor import IEditor
from ..file_info_extractor import IFileInfoExtractor
class TBasicEditorServiceForCodeRunner:
def __init__(self, config: IConfig, editor: IEditor, file_info_extractor: IFileInfoExtractor):
self._config: IConfig = config
self._editor: IEditor = editor
self._file_info_extractor: IFileInfoExtractor = file_info_extractor
self._temp_files: list[str] = []
@contextmanager
def get_file_for_run(self) -> Generator[str, None, None]:
file_path_abs: str = self._editor.get_current_file_name()
if not self._config.get_ignore_selection() and (selected_text := self._editor.get_selected_text()) is not None:
with NamedTemporaryFile(
"w",
encoding="utf-8",
dir=self._file_info_extractor.get_dir(file_path_abs),
prefix=self._config.get_coderunner_tempfile_prefix(),
suffix=self._file_info_extractor.get_file_ext(file_path_abs),
delete=False,
) as temp_file:
temp_file.write(selected_text)
temp_file.flush()
temp_file_abs_path: str = temp_file.name
# there should have been a temporary file deletion after the yield,
# but the problem is that vim.command runs asynchronously with the terminal,
# and I have no idea how to monitor the completion of the process,
# because at the moment, when deleting immediately after the yield,
# the file may not exist at the time of running the executable command.
self._temp_files.append(temp_file_abs_path)
yield temp_file_abs_path
else:
yield file_path_abs
def prepare_for_run(self) -> None:
if self._config.get_save_all_files_before_run():
self._editor.save_all_files()
return
if self._config.get_save_file_before_run():
self._editor.save_file()
return
def remove_coderunner_tempfiles(self) -> None:
for temp_file_abs_path in self._temp_files:
try:
os.unlink(temp_file_abs_path)
except OSError:
pass
self._temp_files.clear()