Skip to content

Commit f293228

Browse files
committed
buffer output before opening file
Closes #93
1 parent c753854 commit f293228

File tree

2 files changed

+44
-21
lines changed

2 files changed

+44
-21
lines changed

jinja2cli/cli.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -412,32 +412,32 @@ def cli(opts: argparse.Namespace, args: Sequence[str]) -> int:
412412

413413
data.update(parse_kv_string(opts.D or []))
414414

415+
rendered = render(
416+
template_path,
417+
data,
418+
extensions,
419+
opts.strict,
420+
trim_blocks=opts.trim_blocks,
421+
lstrip_blocks=opts.lstrip_blocks,
422+
autoescape=opts.autoescape,
423+
variable_start_string=opts.variable_start,
424+
variable_end_string=opts.variable_end,
425+
block_start_string=opts.block_start,
426+
block_end_string=opts.block_end,
427+
comment_start_string=opts.comment_start,
428+
comment_end_string=opts.comment_end,
429+
line_statement_prefix=opts.line_statement_prefix,
430+
line_comment_prefix=opts.line_comment_prefix,
431+
newline_sequence=opts.newline_sequence,
432+
search_paths=opts.search_paths,
433+
)
434+
415435
if opts.outfile is None:
416436
out = sys.stdout
417437
else:
418438
out = open(opts.outfile, "w")
419439

420-
out.write(
421-
render(
422-
template_path,
423-
data,
424-
extensions,
425-
opts.strict,
426-
trim_blocks=opts.trim_blocks,
427-
lstrip_blocks=opts.lstrip_blocks,
428-
autoescape=opts.autoescape,
429-
variable_start_string=opts.variable_start,
430-
variable_end_string=opts.variable_end,
431-
block_start_string=opts.block_start,
432-
block_end_string=opts.block_end,
433-
comment_start_string=opts.comment_start,
434-
comment_end_string=opts.comment_end,
435-
line_statement_prefix=opts.line_statement_prefix,
436-
line_comment_prefix=opts.line_comment_prefix,
437-
newline_sequence=opts.newline_sequence,
438-
search_paths=opts.search_paths,
439-
)
440-
)
440+
out.write(rendered)
441441
out.flush()
442442
return 0
443443

tests/bats/cli.bats

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,3 +182,26 @@ require_toml() {
182182
[ "$status" -eq 0 ]
183183
[ "$output" = "hello" ]
184184
}
185+
186+
@test "output file preserved on render failure" {
187+
tmp_out="$(mktemp)"
188+
echo "original content" >"$tmp_out"
189+
190+
# Template with undefined var should fail with --strict
191+
run uv run jinja2 "$environ_dir/template.j2" "$environ_dir/empty.json" --format json --strict -o "$tmp_out"
192+
193+
[ "$status" -eq 1 ]
194+
[ "$(cat "$tmp_out")" = "original content" ]
195+
rm -f "$tmp_out"
196+
}
197+
198+
@test "same file for input and output works" {
199+
tmp_file="$(mktemp)"
200+
echo "hello {{ name }}" >"$tmp_file"
201+
202+
run uv run jinja2 -D name=world -o "$tmp_file" "$tmp_file"
203+
204+
[ "$status" -eq 0 ]
205+
[ "$(cat "$tmp_file")" = "hello world" ]
206+
rm -f "$tmp_file"
207+
}

0 commit comments

Comments
 (0)