Skip to content

Commit

Permalink
Don't create temporary files
Browse files Browse the repository at this point in the history
  • Loading branch information
314eter committed Jan 5, 2021
1 parent 7eea60d commit d9ea2f5
Showing 1 changed file with 18 additions and 32 deletions.
50 changes: 18 additions & 32 deletions pipeline/compilers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import os
import shutil
import subprocess
from tempfile import NamedTemporaryFile

from django.contrib.staticfiles import finders
from django.contrib.staticfiles.storage import staticfiles_storage
Expand Down Expand Up @@ -114,37 +112,25 @@ def execute_command(self, command, cwd=None, stdout_captured=None):
# The first element in argument_list is the program that will be executed; if it is '', then
# a PermissionError will be raised. Thus empty arguments are filtered out from argument_list
argument_list = list(filter(None, argument_list))
stdout = None
try:
# We always catch stdout in a file, but we may not have a use for it.
temp_file_container = cwd or os.path.dirname(stdout_captured or "") or os.getcwd()
with NamedTemporaryFile('wb', delete=False, dir=temp_file_container) as stdout:
compiling = subprocess.Popen(argument_list, cwd=cwd,
stdout=stdout,
stderr=subprocess.PIPE)
_, stderr = compiling.communicate()
set_std_streams_blocking()

if compiling.returncode != 0:
stdout_captured = None # Don't save erroneous result.
raise CompilerError(
f"{argument_list!r} exit code {compiling.returncode}\n{stderr}",
command=argument_list,
error_output=stderr)
compiling = subprocess.run(
argument_list, cwd=cwd, check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
set_std_streams_blocking()

# User wants to see everything that happened.
if self.verbose:
with open(stdout.name, 'rb') as out:
print(out.read())
print(stderr)
except OSError as e:
stdout_captured = None # Don't save erroneous result.
raise CompilerError(e, command=argument_list,
error_output=str(e))
finally:
# Decide what to do with captured stdout.
if stdout:
if stdout_captured:
shutil.move(stdout.name, os.path.join(cwd or os.curdir, stdout_captured))
else:
os.remove(stdout.name)
print(compiling.stdout)
print(compiling.stderr)
except FileNotFoundError as e:
raise CompilerError(e, command=argument_list)
except subprocess.CalledProcessError as e:
raise CompilerError(
f"{argument_list!r} exit code {e.returncode}\n{e.stderr}",
command=e.cmd, error_output=e.stderr
)
else:
if stdout_captured:
with open(os.path.join(cwd or os.curdir, stdout_captured), 'wb') as f:
f.write(compiling.stdout)

0 comments on commit d9ea2f5

Please sign in to comment.