Skip to content

Commit

Permalink
fix: go fmt and lint
Browse files Browse the repository at this point in the history
Signed-off-by: Norman <[email protected]>
  • Loading branch information
n0izn0iz committed Jan 8, 2025
1 parent f5b7afc commit fba50a7
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 184 deletions.
132 changes: 19 additions & 113 deletions examples/no_cycles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,11 @@ package examples_test

import (
"fmt"
"io/fs"
"os"
pathlib "path"
"path/filepath"
"slices"
"strings"
"testing"

"github.com/gnolang/gno/gnovm"
"github.com/gnolang/gno/gnovm/pkg/gnoenv"
"github.com/gnolang/gno/gnovm/pkg/packages"
"github.com/stretchr/testify/require"
Expand All @@ -20,29 +16,17 @@ var injectedTestingLibs = []string{"encoding/json", "fmt", "os", "internal/os_te

// TestNoCycles checks that there is no import cycles in stdlibs and non-draft examples
func TestNoCycles(t *testing.T) {
// find stdlibs
gnoRoot := gnoenv.RootDir()
pkgs, err := listPkgs(packages.Pkg{
Dir: filepath.Join(gnoRoot, "gnovm", "stdlibs"),
Name: "",
})
// find examples and stdlibs
cfg := &packages.LoadConfig{SelfContained: true, Deps: true}
pkgs, err := packages.Load(cfg, filepath.Join(gnoenv.RootDir(), "examples", "..."))
require.NoError(t, err)

// find examples
examples, err := packages.ListPkgs(filepath.Join(gnoRoot, "examples"))
require.NoError(t, err)
for _, example := range examples {
if example.Draft {
continue
}
examplePkgs, err := listPkgs(example)
require.NoError(t, err)
pkgs = append(pkgs, examplePkgs...)
}

// detect cycles
visited := make(map[string]bool)
for _, p := range pkgs {
if p.Draft {
continue
}
require.NoError(t, detectCycles(p, pkgs, visited))
}
}
Expand Down Expand Up @@ -73,7 +57,7 @@ func TestNoCycles(t *testing.T) {
// - foo_pkg/foo.go imports bar_pkg
//
// - bar_pkg/bar_test.go imports foo_pkg
func detectCycles(root testPkg, pkgs []testPkg, visited map[string]bool) error {
func detectCycles(root *packages.Package, pkgs []*packages.Package, visited map[string]bool) error {
// check cycles in package's sources
stack := []string{}
if err := visitPackage(root, pkgs, visited, stack); err != nil {
Expand All @@ -86,8 +70,8 @@ func detectCycles(root testPkg, pkgs []testPkg, visited map[string]bool) error {

// check cycles in tests' imports by marking the current package as visited while visiting the tests' imports
// we also consider PackageSource imports here because tests can call package code
visited = map[string]bool{root.PkgPath: true}
stack = []string{root.PkgPath}
visited = map[string]bool{root.ImportPath: true}
stack = []string{root.ImportPath}
if err := visitImports([]packages.FileKind{packages.FileKindPackageSource, packages.FileKindTest}, root, pkgs, visited, stack); err != nil {
return fmt.Errorf("test import: %w", err)
}
Expand All @@ -96,14 +80,14 @@ func detectCycles(root testPkg, pkgs []testPkg, visited map[string]bool) error {
}

// visitImports resolves and visits imports by kinds
func visitImports(kinds []packages.FileKind, root testPkg, pkgs []testPkg, visited map[string]bool, stack []string) error {
func visitImports(kinds []packages.FileKind, root *packages.Package, pkgs []*packages.Package, visited map[string]bool, stack []string) error {
for _, imp := range root.Imports.Merge(kinds...) {
if slices.Contains(injectedTestingLibs, imp.PkgPath) {
if slices.Contains(injectedTestingLibs, imp) {
continue
}
idx := slices.IndexFunc(pkgs, func(p testPkg) bool { return p.PkgPath == imp.PkgPath })
idx := slices.IndexFunc(pkgs, func(p *packages.Package) bool { return p.ImportPath == imp })
if idx == -1 {
return fmt.Errorf("import %q not found for %q tests", imp.PkgPath, root.PkgPath)
return fmt.Errorf("import %q not found for %q tests", imp, root.ImportPath)
}
if err := visitPackage(pkgs[idx], pkgs, visited, stack); err != nil {
return fmt.Errorf("test import error: %w", err)
Expand All @@ -114,98 +98,20 @@ func visitImports(kinds []packages.FileKind, root testPkg, pkgs []testPkg, visit
}

// visitNode visits a package and its imports recursively. It only considers imports in PackageSource
func visitPackage(pkg testPkg, pkgs []testPkg, visited map[string]bool, stack []string) error {
if slices.Contains(stack, pkg.PkgPath) {
return fmt.Errorf("cycle detected: %s -> %s", strings.Join(stack, " -> "), pkg.PkgPath)
func visitPackage(pkg *packages.Package, pkgs []*packages.Package, visited map[string]bool, stack []string) error {
if slices.Contains(stack, pkg.ImportPath) {
return fmt.Errorf("cycle detected: %s -> %s", strings.Join(stack, " -> "), pkg.ImportPath)
}
if visited[pkg.PkgPath] {
if visited[pkg.ImportPath] {
return nil
}

visited[pkg.PkgPath] = true
stack = append(stack, pkg.PkgPath)
visited[pkg.ImportPath] = true
stack = append(stack, pkg.ImportPath)

if err := visitImports([]packages.FileKind{packages.FileKindPackageSource}, pkg, pkgs, visited, stack); err != nil {
return err
}

return nil
}

type testPkg struct {
Dir string
PkgPath string
Imports packages.ImportsMap
}

// listPkgs lists all packages in rootMod
func listPkgs(rootMod packages.Pkg) ([]testPkg, error) {
res := []testPkg{}
rootDir := rootMod.Dir
visited := map[string]struct{}{}
if err := fs.WalkDir(os.DirFS(rootDir), ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if !strings.HasSuffix(d.Name(), ".gno") {
return nil
}
subPath := filepath.Dir(path)
dir := filepath.Join(rootDir, subPath)
if _, ok := visited[dir]; ok {
return nil
}
visited[dir] = struct{}{}

subPkgPath := pathlib.Join(rootMod.Name, subPath)

pkg := testPkg{
Dir: dir,
PkgPath: subPkgPath,
}

memPkg, err := readPkg(pkg.Dir, pkg.PkgPath)
if err != nil {
return fmt.Errorf("read pkg %q: %w", pkg.Dir, err)
}
pkg.Imports, err = packages.Imports(memPkg, nil)
if err != nil {
return fmt.Errorf("list imports of %q: %w", memPkg.Path, err)
}

res = append(res, pkg)
return nil
}); err != nil {
return nil, fmt.Errorf("walk dirs at %q: %w", rootDir, err)
}
return res, nil
}

// readPkg reads the sources of a package. It includes all .gno files but ignores the package name
func readPkg(dir string, pkgPath string) (*gnovm.MemPackage, error) {
list, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
memPkg := &gnovm.MemPackage{Path: pkgPath}
for _, entry := range list {
fpath := filepath.Join(dir, entry.Name())
if !strings.HasSuffix(fpath, ".gno") {
continue
}
fname := filepath.Base(fpath)
bz, err := os.ReadFile(fpath)
if err != nil {
return nil, err
}
memPkg.Files = append(memPkg.Files,
&gnovm.MemFile{
Name: fname,
Body: string(bz),
})
}
return memPkg, nil
}
32 changes: 0 additions & 32 deletions gnovm/cmd/gno/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@ import (
"flag"
"fmt"
goio "io"
"log"
"path/filepath"
"strings"
"time"

"github.com/gnolang/gno/gnovm/pkg/gnoenv"
Expand Down Expand Up @@ -248,32 +245,3 @@ func execTest(cfg *testCfg, args []string, io commands.IO) error {

return nil
}

// attempts to determine the full gno pkg path by analyzing the directory.
func pkgPathFromRootDir(pkgPath, rootDir string) string {
abPkgPath, err := filepath.Abs(pkgPath)
if err != nil {
log.Printf("could not determine abs path: %v", err)
return ""
}
abRootDir, err := filepath.Abs(rootDir)
if err != nil {
log.Printf("could not determine abs path: %v", err)
return ""
}
abRootDir += string(filepath.Separator)
if !strings.HasPrefix(abPkgPath, abRootDir) {
return ""
}
impPath := strings.ReplaceAll(abPkgPath[len(abRootDir):], string(filepath.Separator), "/")
for _, prefix := range [...]string{
"examples/",
"gnovm/stdlibs/",
"gnovm/tests/stdlibs/",
} {
if strings.HasPrefix(impPath, prefix) {
return impPath[len(prefix):]
}
}
return ""
}
2 changes: 1 addition & 1 deletion gnovm/pkg/doc/dirs.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func packageImportsRecursive(root string, pkgPath string) []string {

for _, imp := range sub {
if !slices.Contains(res, imp) {
res = append(res, imp) //nolint:makezero
res = append(res, imp)
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion gnovm/pkg/gnolang/debugger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/gnolang/gno/gnovm/pkg/gnoenv"
"github.com/gnolang/gno/gnovm/pkg/gnolang"
"github.com/gnolang/gno/gnovm/pkg/packages"
"github.com/gnolang/gno/gnovm/pkg/test"
)

Expand Down Expand Up @@ -39,7 +40,7 @@ func evalTest(debugAddr, in, file string) (out, err string) {
err = strings.TrimSpace(strings.ReplaceAll(err, "../../tests/files/", "files/"))
}()

_, testStore := test.Store(gnoenv.RootDir(), false, stdin, stdout, stderr)
_, testStore := test.Store(gnoenv.RootDir(), map[string]*packages.Package{}, false, stdin, stdout, stderr)

f := gnolang.MustReadFile(file)

Expand Down
5 changes: 3 additions & 2 deletions gnovm/pkg/gnolang/files_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"testing"

"github.com/gnolang/gno/gnovm/pkg/gnolang"
"github.com/gnolang/gno/gnovm/pkg/packages"
"github.com/gnolang/gno/gnovm/pkg/test"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -46,7 +47,7 @@ func TestFiles(t *testing.T) {
Sync: *withSync,
}
o.BaseStore, o.TestStore = test.Store(
rootDir, true,
rootDir, make(map[string]*packages.Package), true,
nopReader{}, o.WriterForStore(), io.Discard,
)
return o
Expand Down Expand Up @@ -121,7 +122,7 @@ func TestStdlibs(t *testing.T) {
capture = new(bytes.Buffer)
out = capture
}
opts = test.NewTestOptions(rootDir, nopReader{}, out, out)
opts = test.NewTestOptions(rootDir, make(map[string]*packages.Package), nopReader{}, out, out)
opts.Verbose = true
return
}
Expand Down
14 changes: 14 additions & 0 deletions gnovm/pkg/gnomod/parse_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gnomod

import (
"os"
"path/filepath"
"testing"

Expand Down Expand Up @@ -237,3 +238,16 @@ func TestParseGnoMod(t *testing.T) {
})
}
}

func createGnoModPkg(t *testing.T, dirPath, pkgName, modData string) {
t.Helper()

// Create package dir
pkgDirPath := filepath.Join(dirPath, pkgName)
err := os.MkdirAll(pkgDirPath, 0o755)
require.NoError(t, err)

// Create gno.mod
err = os.WriteFile(filepath.Join(pkgDirPath, "gno.mod"), []byte(modData), 0o644)
require.NoError(t, err)
}
2 changes: 1 addition & 1 deletion gnovm/pkg/packages/analyze_packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ func readPkg(pkgDir string, importPath string) *Package {
// TODO: check if stdlib

pkg.Root, err = gnomod.FindRootDir(pkgDir)
if err == gnomod.ErrGnoModNotFound {
if errors.Is(err, gnomod.ErrGnoModNotFound) {
return pkg
}
if err != nil {
Expand Down
34 changes: 0 additions & 34 deletions gnovm/pkg/packages/importer.go

This file was deleted.

0 comments on commit fba50a7

Please sign in to comment.