Skip to content

Commit

Permalink
detect user activity based on commits
Browse files Browse the repository at this point in the history
  • Loading branch information
pPrecel committed Oct 27, 2023
1 parent 1ddf7a0 commit 7c6a81d
Show file tree
Hide file tree
Showing 22 changed files with 482 additions and 233 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.out/
tmp/
.vscode/
.DS_Store

# examples
examples/with-template/report/
Expand Down
65 changes: 35 additions & 30 deletions cmd/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ package cmd
import (
"errors"
"fmt"
"time"

gh "github.com/google/go-github/v53/github"
"github.com/pPrecel/PKUP/internal/logo"
"github.com/pPrecel/PKUP/internal/token"
"github.com/pPrecel/PKUP/internal/view"
Expand All @@ -17,18 +15,21 @@ import (
)

const (
logTimeFormat = time.DateTime
logTimeFormat = "02.01.2006 15:04:05"
)

func NewGenCommand(opts *Options) *cli.Command {
since, until := period.GetLastPKUP()
actionsOpts := &genActionOpts{
Options: opts,
since: *cli.NewTimestamp(since),
until: *cli.NewTimestamp(until),
}

return &cli.Command{
Name: "gen",
Usage: "Generates .diff files with all users merged content in the last PKUP period",
UsageText: "pkup gen --token <personal-access-token> \\\n" +
Name: "gen",
Usage: "Generates .diff and report files with all users merged content in the last PKUP period",
UsageText: "pkup gen \\\n" +
"\t\t--username <username> \\\n" +
"\t\t--repo <org1>/<repo1> \\\n" +
"\t\t--repo <org2>/<repo2>",
Expand Down Expand Up @@ -80,65 +81,69 @@ func genCommandAction(ctx *cli.Context, opts *genActionOpts) error {
multiView := view.NewMultiTaskView(opts.Log, opts.ci)
log := opts.Log.WithWriter(multiView.NewWriter())

warnOnNewRelease(client, opts)
if !opts.ci {
warnOnNewRelease(client, opts)
}

mergedAfter, mergedBefore := period.GetLastPKUP(opts.perdiod)
log.Info("generating artifacts for the actual PKUP period", log.Args(
"after", mergedAfter.Local().Format(logTimeFormat),
"before", mergedBefore.Local().Format(logTimeFormat),
"since", opts.since.Value().Local().Format(logTimeFormat),
"until", opts.until.Value().Local().Format(logTimeFormat),
))

authors, err := client.GetUserSignatures(opts.username)
if err != nil {
return fmt.Errorf("failed to resolve '%s' user: %s", opts.username, err.Error())
}

reportResults := []report.Result{}
for org, repos := range opts.repos {
for i := range repos {
org := org
repo := repos[i]

valChan := make(chan []*gh.PullRequest)
valChan := make(chan *github.CommitList)
errChan := make(chan error)
multiView.Add(fmt.Sprintf("%s/%s", org, repo), valChan, errChan)
go func() {
defer close(errChan)
defer close(valChan)

config := artifacts.Options{
Org: org,
Repo: repo,
Username: opts.username,
Dir: opts.outputDir,
WithClosed: opts.withClosed,
MergedAfter: mergedAfter,
MergedBefore: mergedBefore,
Org: org,
Repo: repo,
Authors: authors,
Dir: opts.outputDir,
Since: *opts.since.Value(),
Until: *opts.until.Value(),
}

log.Debug("starting process for repo with config", log.Args(
"org", config.Org,
"repo", config.Repo,
"username", config.Username,
"authors", config.Authors,
"dir", config.Dir,
"withClosed", config.WithClosed,
"mergedAfter", config.MergedAfter.String(),
"mergedBefore", config.MergedBefore.String(),
"since", config.Since.String(),
"until", config.Until.String(),
))

prs, processErr := artifacts.GenUserArtifactsToDir(client, config)
commitList, processErr := artifacts.GenUserArtifactsToDir(client, config)

log.Debug("ending process for repo", log.Args(
"org", config.Org,
"repo", config.Repo,
"prs", prs,
"commits", len(commitList.Commits),
"error", processErr,
))
if processErr != nil {
errChan <- processErr
return
}

valChan <- prs
valChan <- commitList
reportResults = append(reportResults, report.Result{
Org: org,
Repo: repo,
PullRequests: prs,
Org: org,
Repo: repo,
CommitList: commitList,
})
}()
}
Expand All @@ -149,8 +154,8 @@ func genCommandAction(ctx *cli.Context, opts *genActionOpts) error {
err = report.Render(report.Options{
OutputDir: opts.outputDir,
TemplatePath: opts.templatePath,
PeriodFrom: mergedAfter,
PeriodTill: mergedBefore,
PeriodFrom: *opts.since.Value(),
PeriodTill: *opts.until.Value(),
Results: reportResults,
})
if err != nil {
Expand Down
40 changes: 18 additions & 22 deletions cmd/gen_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import (
"os"
"path/filepath"
"strings"
"time"

"github.com/pPrecel/PKUP/pkg/report"
"github.com/pterm/pterm"
"github.com/urfave/cli/v2"
)
Expand All @@ -30,27 +32,27 @@ func getGenFlags(opts *genActionOpts) []cli.Flag {
&cli.StringFlag{
Name: "username",
Usage: "GitHub user name",
Aliases: []string{"u", "user"},
Aliases: []string{"u"},
Required: true,
Destination: &opts.username,
Action: func(_ *cli.Context, username string) error {
if username == "" {
return fmt.Errorf("username '%s' is empty", username)
}

},
&cli.TimestampFlag{
Name: "since",
Usage: "timestamp used to get commits and render report - foramt " + report.PeriodFormat,
Layout: report.PeriodFormat,
Timezone: time.Local,
Action: func(_ *cli.Context, time *time.Time) error {
opts.since.SetTimestamp(*time)
return nil
},
},
&cli.IntFlag{
Name: "period",
Usage: "pkup period to render from 0 to -n",
Aliases: []string{"p"},
Destination: &opts.perdiod,
Action: func(_ *cli.Context, period int) error {
if period > 1 {
return fmt.Errorf("'%d' is not in range from 1 to -n", period)
}

&cli.TimestampFlag{
Name: "until",
Usage: "timestamp used to get commits and render report - foramt " + report.PeriodFormat,
Layout: report.PeriodFormat,
Timezone: time.Local,
Action: func(_ *cli.Context, t *time.Time) error {
opts.until.SetTimestamp(t.Add(time.Hour*24 - time.Second))
return nil
},
},
Expand Down Expand Up @@ -121,12 +123,6 @@ func getGenFlags(opts *genActionOpts) []cli.Flag {
return nil
},
},
&cli.BoolFlag{
Name: "with-closed",
Usage: "count closed (not merged) PullRequests",
Aliases: []string{"wc", "closed"},
Destination: &opts.withClosed,
},
&cli.BoolFlag{
Name: "ci",
Usage: "print output using standard log and JSON format",
Expand Down
5 changes: 3 additions & 2 deletions cmd/opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"

"github.com/pterm/pterm"
"github.com/urfave/cli/v2"
)

type Options struct {
Expand All @@ -22,14 +23,14 @@ type Options struct {
type genActionOpts struct {
*Options

perdiod int
since cli.Timestamp
until cli.Timestamp
outputDir string
token string
username string
enterpriseURL string
templatePath string
repos map[string][]string
withClosed bool
ci bool
}

Expand Down
6 changes: 2 additions & 4 deletions internal/file/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ package file
import (
"fmt"
"os"

gh "github.com/google/go-github/v53/github"
)

func BuildDiffFilename(pr *gh.PullRequest, org, repo string) string {
return fmt.Sprintf("%s_%s_%s.diff", org, repo, cutSHA(pr.GetMergeCommitSHA()))
func BuildDiffFilename(sha, org, repo string) string {
return fmt.Sprintf("%s_%s_%s.diff", org, repo, cutSHA(sha))
}

func Create(dir, filename, content string) error {
Expand Down
45 changes: 19 additions & 26 deletions internal/view/dynamic.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package view
import (
"fmt"
"io"
"strings"

gh "github.com/google/go-github/v53/github"
"github.com/pPrecel/PKUP/pkg/github"
"github.com/pkg/errors"
"github.com/pterm/pterm"
)
Expand Down Expand Up @@ -42,7 +43,7 @@ func (mtv *dynamicMultiView) NewWriter() io.Writer {
return mtv.multiPrinter.NewWriter()
}

func (mtv *dynamicMultiView) Add(name string, valuesChan chan []*gh.PullRequest, errorChan chan error) {
func (mtv *dynamicMultiView) Add(name string, valuesChan chan *github.CommitList, errorChan chan error) {
mtv.tasks[name] = taskChannels{
valuesChan: valuesChan,
errorChan: errorChan,
Expand Down Expand Up @@ -74,18 +75,18 @@ func selectChannelsForSpinners(workingSpinners map[string]*pterm.SpinnerPrinter,
if ok {
workingSpinners[taskName].Fail(err)
}
case PRs, ok := <-channels.valuesChan:
case commitList, ok := <-channels.valuesChan:
if ok {
if len(PRs) == 0 {
if len(commitList.Commits) == 0 {
workingSpinners[taskName].Warning(
fmt.Sprintf("skipping '%s' no user activity detected", taskName),
)
} else {
text := buildPRsTreeString(
text := buildTreeString(
fmt.Sprintf(
"found %d PRs for repo '%s'",
len(PRs), taskName),
prsToStringList(PRs),
"found %d commits for repo '%s'",
len(commitList.Commits), taskName),
commitsToStringList(commitList),
)
workingSpinners[taskName].Success(text)
}
Expand All @@ -96,11 +97,11 @@ func selectChannelsForSpinners(workingSpinners map[string]*pterm.SpinnerPrinter,
return true
}

func buildPRsTreeString(rootText string, PRs []string) string {
func buildTreeString(rootText string, values []string) string {
children := []pterm.TreeNode{}
for i := range PRs {
for i := range values {
children = append(children, pterm.TreeNode{
Text: PRs[i],
Text: values[i],
})
}

Expand Down Expand Up @@ -130,22 +131,14 @@ func startSpinnersWithPrinter(tasks map[string]taskChannels, multi *pterm.MultiP
return spinners, nil
}

func prsToStringList(prs []*gh.PullRequest) []string {
list := []string{}
for i := range prs {
pr := *prs[i]
func commitsToStringList(list *github.CommitList) []string {
stringList := []string{}
for i := range list.Commits {
commit := list.Commits[i]

title := fmt.Sprintf(" %s (#%d) %s", getStatePrefix(pr), pr.GetNumber(), pr.GetTitle())
list = append(list, title)
line := strings.Split(commit.GetCommit().GetMessage(), "\n")[0]
stringList = append(stringList, line)
}

return list
}

func getStatePrefix(pr gh.PullRequest) string {
if !pr.GetMergedAt().IsZero() {
return pterm.Magenta("[M]")
}

return pterm.Red("[C]")
return stringList
}
12 changes: 6 additions & 6 deletions internal/view/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"io"
"os"

gh "github.com/google/go-github/v53/github"
"github.com/pPrecel/PKUP/pkg/github"
"github.com/pterm/pterm"
)

Expand All @@ -25,7 +25,7 @@ func newStatic(log *pterm.Logger) MultiTaskView {
}
}

func (sv *staticView) Add(name string, valuesChan chan []*gh.PullRequest, errorChan chan error) {
func (sv *staticView) Add(name string, valuesChan chan *github.CommitList, errorChan chan error) {
sv.tasks[name] = taskChannels{
valuesChan: valuesChan,
errorChan: errorChan,
Expand Down Expand Up @@ -54,15 +54,15 @@ func selectChannelsForLogger(log *pterm.Logger, taskName string, channels taskCh
if ok {
log.Error(err.Error())
}
case PRs, ok := <-channels.valuesChan:
case commitList, ok := <-channels.valuesChan:
if ok {
if len(PRs) == 0 {
if len(commitList.Commits) == 0 {
log.Warn(
fmt.Sprintf("skipping '%s' no user activity detected", taskName),
)
} else {
text := fmt.Sprintf("found %d PRs for repo '%s'", len(PRs), taskName)
log.Info(text, log.Args("prs", prsToStringList(PRs)))
text := fmt.Sprintf("found %d commits for repo '%s'", len(commitList.Commits), taskName)
log.Info(text, log.Args("commits", commitsToStringList(commitList)))
}
}
default:
Expand Down
Loading

0 comments on commit 7c6a81d

Please sign in to comment.