Skip to content

Commit

Permalink
move utility to gencommon
Browse files Browse the repository at this point in the history
  • Loading branch information
drshriveer committed Jan 24, 2024
1 parent 1dacbdf commit e1b9023
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 20 deletions.
18 changes: 18 additions & 0 deletions gencommon/packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gencommon

import (
"errors"
"fmt"
"go/ast"
"path"
"strings"
Expand Down Expand Up @@ -77,3 +78,20 @@ func FindPackageWithFile(pkgs []*packages.Package, fileName string) (*packages.P
}
return nil, errors.New("package for " + fileName + " Not found")
}

// PackageNameFromPath returns a fully-qualified package path from a given filename.
// TODO: cache this per directory.
func PackageNameFromPath(fileName string) (string, error) {
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedFiles,
}

pkgs, err := packages.Load(cfg, fileName)
if err != nil {
return "", err
}
for _, pkg := range pkgs {
return pkg.PkgPath, nil
}
return "", fmt.Errorf("package for path %s not found", fileName)
}
22 changes: 2 additions & 20 deletions gogenproto/gen/generate.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package gen

import (
"fmt"
"io/fs"
"log"
"os/exec"
"path/filepath"
"strings"

"golang.org/x/tools/go/packages"
"github.com/drshriveer/gtools/gencommon"
)

// Logger is the name-spaced logger for this script.
Expand Down Expand Up @@ -64,7 +63,7 @@ func (g Generate) Run() error {
return err
}
for _, path := range protoImportPaths {
pkg, err := PackageNameFromPath(filepath.Dir(path))
pkg, err := gencommon.PackageNameFromPath(filepath.Dir(path))
if err != nil {
return err
}
Expand Down Expand Up @@ -123,20 +122,3 @@ func (lw logPipe) Write(p []byte) (n int, err error) {
Logger.Println(toLog)
return len(p), nil
}

// PackageNameFromPath returns a fully-qualified package path from a given filename.
// TODO: cache this per directory.
func PackageNameFromPath(fileName string) (string, error) {
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedFiles,
}

pkgs, err := packages.Load(cfg, fileName)
if err != nil {
return "", err
}
for _, pkg := range pkgs {
return pkg.PkgPath, nil
}
return "", fmt.Errorf("package for path %s not found", fileName)
}

0 comments on commit e1b9023

Please sign in to comment.