Skip to content

Commit 76b1b81

Browse files
chryslewebknjaz
authored andcommitted
Render temporary requirements.txt from requirements.json
1 parent 6f26943 commit 76b1b81

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

piptools/scripts/compile.py

Lines changed: 8 additions & 2 deletions
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
@@ -312,7 +313,7 @@ def cli(
312313
# Proxy with a LocalRequirementsRepository if --upgrade is not specified
313314
# (= default invocation)
314315
output_file_exists = os.path.exists(output_file.name)
315-
if not (upgrade or json) and output_file_exists:
316+
if not upgrade and output_file_exists:
316317
output_file_is_empty = os.path.getsize(output_file.name) == 0
317318
if upgrade_install_reqs and output_file_is_empty:
318319
log.warning(
@@ -323,11 +324,16 @@ def cli(
323324
"as any existing content is truncated."
324325
)
325326

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

piptools/utils.py

Lines changed: 16 additions & 0 deletions
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

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

0 commit comments

Comments
 (0)