git-project-manager/internal/remotes/remotes.go

150 lines
3.1 KiB
Go

package remotes
import (
"fmt"
"strings"
"time"
"github.com/go-git/go-git/v5"
"github.com/pterm/pterm"
"github.com/xanzy/go-gitlab"
)
// Will determine number of total projects,
// then based on projectsPerPage (request) and
// projectsPerGoroutine, will spin off goroutines
// with offsets
const (
projectsPerPage = 20
projectsPerGoroutine = 200
)
type Project struct {
ID int
Description string
SSHURLToRepo string
HTTPURLToRepo string
WebURL string
Name string
NameWithNamespace string
Path string
PathWithNamespace string
AvatarURL string
LastActivityAt time.Time
Readme string
Remote string
Owner string
Languages *ProjectLanguages
gitRepo *git.Repository
}
type ProjectLanguages []*ProjectLanguage
type ProjectLanguage struct {
Name string
Percentage float32
}
type User struct {
ID int
Username string
Email string
Name string
AvatarURL string
}
func (c *Client) Api() *gitlab.Client {
return c.apiClient
}
func (p *Project) String() string {
var projectString string
if p != nil {
projectString = fmt.Sprintf("%s (%s)", p.Path, p.PathWithNamespace)
}
return projectString
}
func (p *Project) GetLanguage() *ProjectLanguage {
if p.Languages == nil {
return nil
}
var lang *ProjectLanguage
var maxPcnt float32
for _, p := range *p.Languages {
if p.Percentage > maxPcnt {
lang = p
}
maxPcnt = p.Percentage
}
return lang
}
func (p *Project) SanitizedPath() string {
return strings.Trim(p.PathWithNamespace, " '\"%<>|`")
}
func (p *Project) SetRepo(r *git.Repository) {
p.gitRepo = r
}
func (p *Project) GetRepo() *git.Repository {
return p.gitRepo
}
func (c *Client) GetTotalProjects(opts *gitlab.ListProjectsOptions) int {
reqOpts := *opts
reqOpts.ListOptions = gitlab.ListOptions{
Page: 1,
PerPage: 1,
}
var projects int
if _, r, e := c.apiClient.Projects.ListProjects(opts, gitlab.WithContext(c.Ctx)); e == nil {
projects = r.TotalItems
}
return projects
}
// Returns a list of projects along with the next page and an error
// if there was an error
func (c *Client) ListProjects(opts *gitlab.ListProjectsOptions) (
[]*Project, *gitlab.Response, error) {
pList := make([]*Project, 0)
projects, resp, err := c.apiClient.Projects.ListProjects(
opts,
gitlab.WithContext(c.Ctx),
)
if err == nil {
pList = append(pList, c.handleProjects(projects)...)
}
return pList, resp, err
}
// A nil return indicates an API error or GitLab doesn't know what
// language the project uses.
func (c *Client) GetProjectLanguages(project *gitlab.Project) *ProjectLanguages {
l, _, e := c.apiClient.Projects.GetProjectLanguages(project.ID, gitlab.WithContext(c.Ctx))
if e != nil {
pterm.Error.Printfln("Failed requesting project languages: %s", e.Error())
return nil
}
var pLangs ProjectLanguages
pLangs = make([]*ProjectLanguage, len(*l))
var i int
for name, pcnt := range *l {
pLangs[i] = &ProjectLanguage{
Name: name,
Percentage: pcnt,
}
i++
}
return &pLangs
}