update-go-mod/internal/cli/action_overlook.go

118 lines
2.2 KiB
Go
Raw Normal View History

2023-08-15 10:59:16 +00:00
package cli
import (
2023-08-15 12:18:48 +00:00
"context"
2023-08-15 10:59:16 +00:00
"fmt"
2023-08-15 11:26:34 +00:00
"os"
2023-08-15 10:59:16 +00:00
"regexp"
2023-08-15 11:26:34 +00:00
"sort"
2023-08-15 12:18:48 +00:00
"sync"
2023-08-15 11:26:34 +00:00
"text/tabwriter"
"time"
2023-08-15 10:59:16 +00:00
2023-08-15 12:18:48 +00:00
"github.com/sourcegraph/conc/pool"
2023-08-15 10:59:16 +00:00
"github.com/urfave/cli/v2"
)
2023-08-15 12:18:48 +00:00
const maxPoolGoroutine = 8
2023-08-15 10:59:16 +00:00
var reGitHub = regexp.MustCompile(`github\.com/([^/]*)/([^/]*)`)
2023-08-15 11:26:34 +00:00
type GitHubRepoData struct {
UpdatedAt time.Time
Name string
Star int
}
2023-08-15 10:59:16 +00:00
func (a *action) Overlook(c *cli.Context) error {
2023-08-15 12:00:22 +00:00
// Optional
if a.ghClient == nil {
return nil
}
2023-08-15 10:59:16 +00:00
a.getFlags(c)
mapImportedModules, err := a.runGetImportedModules(c)
if err != nil {
return err
}
2023-08-15 11:26:34 +00:00
if len(mapImportedModules) == 0 {
return nil
}
listGHRepoData := make([]GitHubRepoData, 0, len(mapImportedModules))
// To avoid duplicate
mGHRepoData := make(map[string]struct{})
2023-08-15 12:18:48 +00:00
p := pool.New().WithMaxGoroutines(maxPoolGoroutine)
var mMutex sync.RWMutex
var listMutex sync.Mutex
2023-08-15 10:59:16 +00:00
for module := range mapImportedModules {
2023-08-15 12:18:48 +00:00
module := module
p.Go(func() {
if !reGitHub.MatchString(module) {
return
}
parts := reGitHub.FindStringSubmatch(module)
if len(parts) != 3 {
return
}
ghRepoName := parts[0]
mMutex.RLock()
if _, ok := mGHRepoData[ghRepoName]; ok {
mMutex.RUnlock()
return
}
mMutex.RUnlock()
mMutex.Lock()
mGHRepoData[ghRepoName] = struct{}{}
mMutex.Unlock()
owner := parts[1]
repo := parts[2]
ghRepo, _, err := a.ghClient.Repositories.Get(context.Background(), owner, repo)
if err != nil {
a.log("Failed to get GitHub %s/%s: %s\n", owner, repo, err)
}
var ghStar int
if ghRepo.StargazersCount != nil {
ghStar = *ghRepo.StargazersCount
}
var ghUpdatedAt time.Time
if ghRepo.UpdatedAt != nil {
ghUpdatedAt = ghRepo.UpdatedAt.Time
}
listMutex.Lock()
listGHRepoData = append(listGHRepoData, GitHubRepoData{
UpdatedAt: ghUpdatedAt,
Name: ghRepoName,
Star: ghStar,
})
listMutex.Unlock()
2023-08-15 11:26:34 +00:00
})
}
2023-08-15 12:18:48 +00:00
p.Wait()
2023-08-15 11:26:34 +00:00
// Sort for consistency
sort.Slice(listGHRepoData, func(i, j int) bool {
return listGHRepoData[i].Name < listGHRepoData[j].Name
})
// Print
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
for _, r := range listGHRepoData {
fmt.Fprintf(w, "Module %s\t%d\t⭐\tLast updated %s\n", r.Name, r.Star, r.UpdatedAt.Format(time.DateOnly))
2023-08-15 10:59:16 +00:00
}
2023-08-15 11:26:34 +00:00
w.Flush()
2023-08-15 10:59:16 +00:00
return nil
}