Skip to content

Commit

Permalink
Add options to command line
Browse files Browse the repository at this point in the history
Closes #1
  • Loading branch information
umutphp committed May 23, 2020
1 parent cdfeccc commit 5e2db32
Show file tree
Hide file tree
Showing 6 changed files with 168 additions and 18 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,28 @@
# github-stats
Command-line tool to get the total traffics statistics on your GitHub account

## How To Use

```bash
github-stats --token A_Valid_Personal_Access_Token
```

For details please use `--help` as argument;

```bash
$ go run main.go --help
NAME:
github-stats - Get the total visit stats of your GitHub repositories
USAGE:
github-stats [global options]
AUTHOR:
Umut Işık <[email protected]>
OPTIONS:
--day value, -d value The number of days from today to show the stats (default: 0)
--verbose value, -v value Show verbose output or not. 1 for verbose. Default is 0 (default: 0)
--token value, -t value Personal access token got from GitHub to use the API
```

## How To Contribute

All kind of contributions are ok for me :).
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ go 1.14

require (
github.com/google/go-github/v31 v31.0.0
github.com/urfave/cli/v2 v2.2.0
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
)
13 changes: 13 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=
github.com/google/go-github/v31 v31.0.0 h1:JJUxlP9lFK+ziXKimTCprajMApV1ecWD4NB6CCb0plo=
github.com/google/go-github/v31 v31.0.0/go.mod h1:NQPZol8/1sMoWYGN2yaALIBytu17gAWfhbweiEed3pM=
github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/urfave/cli v1.22.4 h1:u7tSpNPPswAFymm8IehJhy4uJMlUuU/GmqSkvJ1InXA=
github.com/urfave/cli/v2 v2.2.0 h1:JTTnM6wKzdA0Jqodd966MVj4vWbbquZykeX1sKbe2C4=
github.com/urfave/cli/v2 v2.2.0/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
Expand All @@ -21,3 +32,5 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
59 changes: 59 additions & 0 deletions lib/app/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package app

import (
ucli "github.com/urfave/cli/v2"
)

func New() *ucli.App {
app := &ucli.App{
Name: "github-stats",
Usage: "Get the total visit stats of your GitHub repositories",
UsageText: "github-stats [global options]",
Authors: []*ucli.Author{
{Name: "Umut Işık", Email: "[email protected]"},
},
Flags: []ucli.Flag {
&ucli.IntFlag{
Name: "day",
Aliases: []string{"d"},
Usage: "The number of days from today to show the stats",
Value: 0,
},
&ucli.IntFlag{
Name: "verbose",
Aliases: []string{"v"},
Usage: "Show verbose output or not. 1 for verbose. Default is 0",
Value: 1,
},
&ucli.StringFlag{
Name: "token",
Aliases: []string{"t"},
Value: "",
Usage: "Personal access token got from GitHub to use the API",
Required: true,
},
},
}

app.CustomAppHelpTemplate = `
NAME:
{{.Name}}{{if .Usage}} - {{.Usage}}{{end}}
USAGE:
{{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}
VERSION:
{{.Version}}{{end}}{{end}}{{if .Description}}
DESCRIPTION:
{{.Description}}{{end}}{{if len .Authors}}
AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}:
{{range $index, $author := .Authors}}{{if $index}}
{{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}}
OPTIONS:
{{range $index, $option := .VisibleFlags}}{{if $index}}
{{end}}{{$option}}{{end}}{{end}}{{if .Copyright}}
COPYRIGHT:
{{.Copyright}}{{end}}
`

return app
}
59 changes: 44 additions & 15 deletions lib/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ package cli
import (
"fmt"
"context"
"log"
"errors"
"io"
"time"
"math"

"golang.org/x/oauth2"
"github.com/google/go-github/v31/github"
Expand All @@ -15,6 +14,8 @@ import (
type CLI struct {
username string
token string
day int
verbose int
client *github.Client
context context.Context
accountTotalChannel chan int
Expand All @@ -23,12 +24,16 @@ type CLI struct {
haltChannel chan int
}

func New() CLI {
func New(token string) CLI {
cli := CLI{
username: "",
token: "07a4574f57fdbe125f37afab2264b64a9cde8d82",
token: "",
day: 0,
verbose: 1,
}

cli.SetToken(token)

cli.context = context.Background()
tokenSource := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: cli.token},
Expand All @@ -45,10 +50,22 @@ func New() CLI {
return cli
}

func (cli *CLI) SetToken(token string) {
cli.token = token
}

func (cli *CLI) SetDay(day int) {
cli.day = day
}

func (cli *CLI) SetVerbose(verbose int) {
cli.verbose = verbose
}

func (cli *CLI) Initialize() bool {
user, _, err := cli.client.Users.Get(cli.context, "")
if err != nil {
fmt.Printf("client.Users.Get() faled with '%s'\n", err)
fmt.Println("GitHub API authentication failed. Token may be invalid.")
return false
}

Expand All @@ -61,31 +78,41 @@ func (cli *CLI) GetRepos() []*github.Repository {
repos, _, err := cli.client.Repositories.List(cli.context, cli.username, nil)

if err != nil {
log.Fatal(err)
fmt.Println("Cannot fetch repositories from GitHub. Error message:", err)
return []*github.Repository{}
}

if len(repos) == 0 {
log.Fatal(errors.New("User has no repositories"))
fmt.Println("User has no repositories")
return []*github.Repository{}
}

return repos
}

func (cli *CLI) RepoStat(w io.Writer) {
for repo := range cli.repoChannel {
fmt.Print(".")
if cli.verbose == 1 {
fmt.Print(".")
}

stats,_,_ := cli.client.Repositories.ListTrafficViews(cli.context, cli.username, repo.GetName(), nil)

viewCount := 0
uniqueCount := 0
dayDiff := int(math.Abs(float64(cli.day))) + 1

for _,view := range stats.Views {
if (view.GetTimestamp().After(time.Now().UTC().AddDate(0, 0, -1))) {
if (view.GetTimestamp().After(time.Now().UTC().AddDate(0, 0, -dayDiff))) {
uniqueCount += view.GetUniques()
viewCount += view.GetCount()
}
}

fmt.Fprintf(w, "%s\t%d\t%d\t\n", repo.GetFullName(), viewCount, uniqueCount)
if cli.verbose == 1 {
fmt.Fprintf(w, "%s\t%d\t%d\t\n", repo.GetFullName(), viewCount, uniqueCount)
}

cli.accountTotalChannel <- viewCount
cli.accountUniqueChannel <- uniqueCount
}
Expand All @@ -94,15 +121,18 @@ func (cli *CLI) RepoStat(w io.Writer) {
}

func (cli *CLI) Execute(w io.Writer) {
fmt.Print("Checking repositories ")

repos := cli.GetRepos()
repoCount := len(repos)

cli.accountTotalChannel = make(chan int, repoCount)
cli.accountUniqueChannel = make(chan int, repoCount)

fmt.Fprintf(w, "Repository\tTotal View\tUnique View\t\n")
if cli.verbose == 1 {
fmt.Fprintf(w, "Repository\tTotal View\tUnique View\t\n")
}

fmt.Print("Checking repositories ")
for i:=0;i<repoCount;i++ {
go cli.RepoStat(w)
}
Expand All @@ -128,8 +158,6 @@ func (cli *CLI) Finiliaze(
close(cli.haltChannel)
close(cli.accountTotalChannel)
close(cli.accountUniqueChannel)
fmt.Println("")
fmt.Println("")
}
}

Expand All @@ -143,5 +171,6 @@ func (cli *CLI) Finiliaze(
unique += u
}

fmt.Fprintf(w, "Total\t%d\t%d\t\n", total, unique)
fmt.Fprintln(w, "")
fmt.Fprintln(w, "Total View:", total, ", Unique View:", unique)
}
28 changes: 25 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,38 @@ package main
import (
"os"
"text/tabwriter"
"fmt"

"github-stats/lib/cli"
"github-stats/lib/app"

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

func main() {
CLI := cli.New()
w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
defer w.Flush()
application := app.New()

application.Action = func(c *ucli.Context) error {
CLI := cli.New(c.String("token"))

CLI.SetDay(c.Int("day"))

if c.Int("verbose") == 0 {
CLI.SetVerbose(c.Int("verbose"))
}

if CLI.Initialize() == true {
CLI.Execute(w)
}
return nil
}

err := application.Run(os.Args)

if CLI.Initialize() == true {
CLI.Execute(w)
if err != nil {
fmt.Println(err)
return
}
}

0 comments on commit 5e2db32

Please sign in to comment.