Skip to content

Commit 600795d

Browse files
committed
Render temporary requirements.txt from requirements.json
1 parent 0dc358d commit 600795d

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

piptools/scripts/compile.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
install_req_from_line,
2929
is_pinned_requirement,
3030
key_from_ireq,
31+
render_requirements_json_txt,
3132
)
3233
from ..writer import OutputWriter
3334
from . import options
@@ -309,7 +310,7 @@ def cli(
309310
# Proxy with a LocalRequirementsRepository if --upgrade is not specified
310311
# (= default invocation)
311312
output_file_exists = os.path.exists(output_file.name)
312-
if not (upgrade or json) and output_file_exists:
313+
if not upgrade and output_file_exists:
313314
output_file_is_empty = os.path.getsize(output_file.name) == 0
314315
if upgrade_install_reqs and output_file_is_empty:
315316
log.warning(
@@ -320,11 +321,16 @@ def cli(
320321
"as any existing content is truncated."
321322
)
322323

324+
if json:
325+
# Render contents of JSON output file to a temporary requirements
326+
# file in text format in order to make it readable by ``pip``
327+
tmpfile_name = render_requirements_json_txt(output_file.name)
328+
323329
# Use a temporary repository to ensure outdated(removed) options from
324330
# existing requirements.txt wouldn't get into the current repository.
325331
tmp_repository = PyPIRepository(pip_args, cache_dir=cache_dir)
326332
ireqs = parse_requirements(
327-
output_file.name,
333+
tmpfile_name if json else output_file.name,
328334
finder=tmp_repository.finder,
329335
session=tmp_repository.session,
330336
options=tmp_repository.options,

piptools/utils.py

+16
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import re
1010
import shlex
1111
import sys
12+
import tempfile
1213
from pathlib import Path
1314
from typing import Any, Callable, Iterable, Iterator, TypeVar, cast
1415

@@ -772,3 +773,18 @@ def is_path_relative_to(path1: Path, path2: Path) -> bool:
772773
except ValueError:
773774
return False
774775
return True
776+
777+
778+
def render_requirements_json_txt(filename: str) -> str:
779+
"""Render a given ``requirements.json`` file to a temporary
780+
``requirements.txt`` file and return its name.
781+
"""
782+
with open(filename, encoding="utf-8") as f:
783+
reqs = json.load(f)
784+
tmpfile = tempfile.NamedTemporaryFile(mode="w+t", encoding="utf-8", delete=False)
785+
for req in reqs:
786+
tmpfile.write(req["line"])
787+
tmpfile.write("\n")
788+
tmpfile.flush()
789+
790+
return tmpfile.name

0 commit comments

Comments
 (0)