Skip to content

Commit 8ddceab

Browse files
authored
fmt: fix removal of used selective and alias imports in modules in $VMODULES dirs (#20977)
1 parent a867ed6 commit 8ddceab

File tree

2 files changed

+33
-6
lines changed

2 files changed

+33
-6
lines changed

vlib/v/fmt/fmt.v

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,8 @@ pub fn fmt(file ast.File, mut table ast.Table, pref_ &pref.Preferences, is_debug
7171
out: strings.new_builder(1000)
7272
out_imports: strings.new_builder(200)
7373
}
74-
for vpath in os.vmodules_paths() {
75-
if file.path.starts_with(vpath) {
74+
for p in os.vmodules_paths() {
75+
if file.path.starts_with(os.real_path(p)) {
7676
f.inside_vmodules = true
7777
break
7878
}
@@ -374,11 +374,12 @@ pub fn (mut f Fmt) imports(imports []ast.Import) {
374374
}
375375

376376
pub fn (f Fmt) imp_stmt_str(imp ast.Import) string {
377-
if f.inside_vmodules {
378-
return imp.source_name
377+
normalized_mod := if f.inside_vmodules {
378+
imp.source_name
379+
} else {
380+
mod := if imp.mod.len == 0 { imp.alias } else { imp.mod }
381+
mod.all_after('src.') // Ignore the 'src.' folder prefix since src/ folder is root of code
379382
}
380-
mod := if imp.mod.len == 0 { imp.alias } else { imp.mod }
381-
normalized_mod := mod.all_after('src.') // Ignore the 'src.' folder prefix since src/ folder is root of code
382383
is_diff := imp.alias != normalized_mod && !normalized_mod.ends_with('.' + imp.alias)
383384
mut imp_alias_suffix := if is_diff { ' as ${imp.alias}' } else { '' }
384385
mut syms := imp.syms.map(it.name).filter(f.import_syms_used[it])

vlib/v/fmt/fmt_vmodules_test.v

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import os
2+
3+
const vexe = os.quoted_path(@VEXE)
4+
const vmodules_tdir = os.join_path(os.vtmp_dir(), 'fmt_vmodules_test')
5+
const module_tdir = os.join_path(vmodules_tdir, 'foo')
6+
7+
fn testsuite_begin() {
8+
os.mkdir_all(module_tdir) or {}
9+
os.setenv('VMODULES', vmodules_tdir, true)
10+
}
11+
12+
fn testsuite_end() {
13+
os.rmdir_all(vmodules_tdir) or {}
14+
}
15+
16+
fn test_fmt_vmodules() {
17+
tfile_content := [
18+
'import x.json2 as json',
19+
'import datatypes { Stack }',
20+
'',
21+
'const foo = Stack[string]{}',
22+
'',
23+
].join_lines()
24+
os.write_file(os.join_path(module_tdir, 'main.v'), tfile_content)!
25+
os.execute_opt('${vexe} fmt -c ${module_tdir}') or { assert false, err.msg() }
26+
}

0 commit comments

Comments
 (0)