Created
December 17, 2021 18:19
-
-
Save klingtnet/ced6dd4052de85d163013333fee9f787 to your computer and use it in GitHub Desktop.
List all packages in a Go module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/fs" | |
"log" | |
"os" | |
"path/filepath" | |
"sort" | |
"strings" | |
) | |
func run(root string) error { | |
var packages []string | |
err := fs.WalkDir(os.DirFS(root), ".", func(path string, d fs.DirEntry, err error) error { | |
if err != nil { | |
return err | |
} | |
if !d.IsDir() { | |
return nil | |
} | |
parts := strings.Split(path, string(filepath.Separator)) | |
if len(parts) < 1 { | |
return nil | |
} | |
// packageName := parts[len(parts)-1] | |
for _, part := range parts { | |
switch part { | |
case "internal", "testdata", "test", "vendor": | |
return filepath.SkipDir | |
} | |
} | |
sourceFiles, err := fs.Glob(os.DirFS(filepath.Join(root, path)), "*.go") | |
if err != nil { | |
return err | |
} | |
if len(sourceFiles) < 1 { | |
return nil | |
} | |
for _, sourceFile := range sourceFiles { | |
if strings.Contains("_test", sourceFile) { | |
return nil | |
} | |
} | |
packages = append(packages, path) | |
return nil | |
}) | |
sort.Strings(packages) | |
for _, packageName := range packages { | |
fmt.Println(packageName) | |
} | |
return err | |
} | |
func main() { | |
err := run(os.Args[1]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment