Skip to content

Commit

Permalink
fmt: fix removal of used selective and alias imports in modules in `$…
Browse files Browse the repository at this point in the history
…VMODULES` dirs (#20977)
  • Loading branch information
ttytm committed Mar 8, 2024
1 parent a867ed6 commit 8ddceab
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
13 changes: 7 additions & 6 deletions vlib/v/fmt/fmt.v
Expand Up @@ -71,8 +71,8 @@ pub fn fmt(file ast.File, mut table ast.Table, pref_ &pref.Preferences, is_debug
out: strings.new_builder(1000)
out_imports: strings.new_builder(200)
}
for vpath in os.vmodules_paths() {
if file.path.starts_with(vpath) {
for p in os.vmodules_paths() {
if file.path.starts_with(os.real_path(p)) {
f.inside_vmodules = true
break
}
Expand Down Expand Up @@ -374,11 +374,12 @@ pub fn (mut f Fmt) imports(imports []ast.Import) {
}

pub fn (f Fmt) imp_stmt_str(imp ast.Import) string {
if f.inside_vmodules {
return imp.source_name
normalized_mod := if f.inside_vmodules {
imp.source_name
} else {
mod := if imp.mod.len == 0 { imp.alias } else { imp.mod }
mod.all_after('src.') // Ignore the 'src.' folder prefix since src/ folder is root of code
}
mod := if imp.mod.len == 0 { imp.alias } else { imp.mod }
normalized_mod := mod.all_after('src.') // Ignore the 'src.' folder prefix since src/ folder is root of code
is_diff := imp.alias != normalized_mod && !normalized_mod.ends_with('.' + imp.alias)
mut imp_alias_suffix := if is_diff { ' as ${imp.alias}' } else { '' }
mut syms := imp.syms.map(it.name).filter(f.import_syms_used[it])
Expand Down
26 changes: 26 additions & 0 deletions vlib/v/fmt/fmt_vmodules_test.v
@@ -0,0 +1,26 @@
import os

const vexe = os.quoted_path(@VEXE)
const vmodules_tdir = os.join_path(os.vtmp_dir(), 'fmt_vmodules_test')
const module_tdir = os.join_path(vmodules_tdir, 'foo')

fn testsuite_begin() {
os.mkdir_all(module_tdir) or {}
os.setenv('VMODULES', vmodules_tdir, true)
}

fn testsuite_end() {
os.rmdir_all(vmodules_tdir) or {}
}

fn test_fmt_vmodules() {
tfile_content := [
'import x.json2 as json',
'import datatypes { Stack }',
'',
'const foo = Stack[string]{}',
'',
].join_lines()
os.write_file(os.join_path(module_tdir, 'main.v'), tfile_content)!
os.execute_opt('${vexe} fmt -c ${module_tdir}') or { assert false, err.msg() }
}

0 comments on commit 8ddceab

Please sign in to comment.