Skip to content

Instantly share code, notes, and snippets.

@hackerzhut
Created December 16, 2022 14:38
Show Gist options
  • Save hackerzhut/a6bdacfd48d703dc50f7dc4e310886be to your computer and use it in GitHub Desktop.
Save hackerzhut/a6bdacfd48d703dc50f7dc4e310886be to your computer and use it in GitHub Desktop.
scan github for libraries used
package main
import (
"context"
"fmt"
"strings"
"github.com/google/go-github/v32/github"
"golang.org/x/oauth2"
)
func main() {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: "YOUR_ACCESS_TOKEN"},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
// Replace "OWNER" and "REPO" with the owner and repository name
result, _, err := client.Search.Code(ctx, "import repo:OWNER/REPO", nil)
if err != nil {
fmt.Printf("Error searching repository: %v\n", err)
return
}
// The CodeSearchResult.CodeResults field contains the list of code results
// returned by the search.
for _, codeResult := range result.CodeResults {
// The CodeResult.Path field contains the file path of the code result.
// We can use this to determine the language of the file.
path := *codeResult.Path
if strings.HasSuffix(path, ".go") {
// This is a Go file, so we can extract the imported packages from the
// CodeResult.Text field, which contains the contents of the file.
imports := extractGoImports(codeResult.Text)
fmt.Printf("Go imports in file %s: %v\n", path, imports)
} else if strings.HasSuffix(path, ".java") {
// This is a Java file, so we can extract the imported packages from the
// CodeResult.Text field, which contains the contents of the file.
imports := extractJavaImports(codeResult.Text)
fmt.Printf("Java imports in file %s: %v\n", path, imports)
}
}
}
// extractGoImports extracts the imported packages from the given Go source code.
func extractGoImports(src string) []string {
var imports []string
for _, line := range strings.Split(src, "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "import") {
continue
}
// Extract the package path from the import statement.
// For example, given "import "foo/bar"", this would return "foo/bar".
path := strings.Trim(line[len("import"):], " \"")
imports = append(imports, path)
}
return imports
}
// extractJavaImports extracts the imported packages from the given Java
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment