Skip to content

Instantly share code, notes, and snippets.

@hackerzhut
Created December 16, 2022 14:47
Show Gist options
  • Save hackerzhut/c638ba007ac693b60ba57b8114a6ba6f to your computer and use it in GitHub Desktop.
Save hackerzhut/c638ba007ac693b60ba57b8114a6ba6f to your computer and use it in GitHub Desktop.
scan gitlab for libraries used
package main
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/google/go-querystring/query"
)
type searchOptions struct {
// Replace "YOUR_PRIVATE_TOKEN" with a personal access token
PrivateToken string `url:"private_token"`
// Replace "OWNER" and "REPO" with the owner and repository name
Project string `url:"project"`
// Set the search query. We use a wildcard to match any file that ends in ".go" or ".java".
Query string `url:"query"`
}
func main() {
// Replace "GITLAB_HOSTNAME" with the hostname of your GitLab instance
baseURL := "https://GITLAB_HOSTNAME/api/v4/search"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Set the search options
opts := searchOptions{
PrivateToken: "YOUR_PRIVATE_TOKEN",
Project: "OWNER/REPO",
Query: "*.go OR *.java",
}
// Encode the search options as a query string
v, _ := query.Values(opts)
url := baseURL + "?" + v.Encode()
// Perform the search
req, _ := http.NewRequest("GET", url, nil)
req = req.WithContext(ctx)
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
fmt.Printf("Error searching repository: %v\n", err)
return
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
// The search response contains a list of search results, each of which has a
// "blob_path" field that contains the file path of the result.
// We can use this to determine the language of the file.
for _, item := range searchResults(body) {
path := item["blob_path"].(string)
if strings.HasSuffix(path, ".go") {
// This is a Go file, so we can extract the imported packages from the
// "content" field, which contains the contents of the file.
imports := extractGoImports(item["content"].(string))
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
// "content" field
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment