From 9d66b3472c2751339989802aafd9d97b9386a5d3 Mon Sep 17 00:00:00 2001 From: Turiiya <34311583+ttytm@users.noreply.github.com> Date: Sat, 16 Mar 2024 10:21:02 +0100 Subject: [PATCH] fmt: insert auto imports after shebang (#21038) --- vlib/v/fmt/fmt.v | 11 ++++++++--- vlib/v/fmt/tests/import_auto_with_shebang_expected.vv | 5 +++++ vlib/v/fmt/tests/import_auto_with_shebang_input.vv | 3 +++ 3 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 vlib/v/fmt/tests/import_auto_with_shebang_expected.vv create mode 100644 vlib/v/fmt/tests/import_auto_with_shebang_input.vv diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index ec0c904ef7b855..77a97d122297f8 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -97,9 +97,14 @@ pub fn fmt(file ast.File, mut table ast.Table, pref_ &pref.Preferences, is_debug } return res } - source_for_imports := res[..f.import_pos] + f.out_imports.str() - source_after_imports := res[f.import_pos..] - return source_for_imports + source_after_imports + mut import_start_pos := f.import_pos + if stmt := file.stmts[1] { + if stmt is ast.ExprStmt && stmt.expr is ast.Comment + && (stmt.expr as ast.Comment).text.starts_with('#!') { + import_start_pos = stmt.pos.len + } + } + return res[..import_start_pos] + f.out_imports.str() + res[import_start_pos..] } pub fn (mut f Fmt) process_file_imports(file &ast.File) { diff --git a/vlib/v/fmt/tests/import_auto_with_shebang_expected.vv b/vlib/v/fmt/tests/import_auto_with_shebang_expected.vv new file mode 100644 index 00000000000000..93d4fc265e5857 --- /dev/null +++ b/vlib/v/fmt/tests/import_auto_with_shebang_expected.vv @@ -0,0 +1,5 @@ +#!/usr/bin/env -S v + +import os + +os.join_path('a', 'b', 'c') diff --git a/vlib/v/fmt/tests/import_auto_with_shebang_input.vv b/vlib/v/fmt/tests/import_auto_with_shebang_input.vv new file mode 100644 index 00000000000000..2d302758b83efb --- /dev/null +++ b/vlib/v/fmt/tests/import_auto_with_shebang_input.vv @@ -0,0 +1,3 @@ +#!/usr/bin/env -S v +os.join_path('a','b','c') +