Skip to content

Instantly share code, notes, and snippets.

@ghandic
Last active March 8, 2018 17:04
Show Gist options
  • Save ghandic/dcfd6ac55cdc1a20e1bd12f3e7429f88 to your computer and use it in GitHub Desktop.
Save ghandic/dcfd6ac55cdc1a20e1bd12f3e7429f88 to your computer and use it in GitHub Desktop.
My first play around with go, so I converted my latest_blame.py to go
// Simply run this executable with the file url inside github and it will find the most recent blame on the file
// Env:
// docker run -it golang:1.8
// Install:
// mkdir -p $GOPATH/src/github.com/user/latest_blame
// curl https://gist.githubusercontent.com/ghandic/dcfd6ac55cdc1a20e1bd12f3e7429f88/raw/latest_blame.go > $GOPATH/src/github.com/user/latest_blame/latest_blame.go
// go get github.com/anaskhan96/soup
// go install github.com/user/latest_blame
// Use:
// latest_blame --url https://github.com/ghandic/confluenceapi/blob/master/README.md
package main
import (
"flag"
"fmt"
"github.com/anaskhan96/soup"
"strings"
"net/url"
"time"
)
func main() {
git_url := flag.String("url", "", "url to file stored on github")
flag.Parse()
//all_blame_dates := get_all_blame_dates(*git_url)
most_recent_blame := get_most_recent_blame(*git_url)
//fmt.Println("Repo supplied: ", *git_url)
//fmt.Println("All blame dates: ", all_blame_dates)
fmt.Println("Most recent blame: ", most_recent_blame)
}
func git_url_to_blame(git_url string) string {
// Give it a file url inside github and it will return the url for its blame
u, err := url.ParseRequestURI(git_url)
if err != nil {
fmt.Println("Unable to make request: ", err)
}
var git_path = strings.Split(u.EscapedPath(), "/")
git_path[3] = "blame"
return "https://" + u.Hostname() + strings.Join(git_path, "/")
}
func get_all_blame_dates(git_url string) []time.Time {
git_blame := git_url_to_blame(git_url)
resp, err := soup.Get(git_blame)
if err != nil {
fmt.Println("Unable to make request: ", err)
}
doc := soup.HTMLParse(resp)
blames := doc.FindAll("time-ago")
dates := map[time.Time]bool{}
for _, blame := range blames {
var t, _ = time.Parse(time.RFC3339, blame.Attrs()["datetime"])
dates[t] = true
}
var commit_dates []time.Time
for key, _ := range dates {
commit_dates = append(commit_dates, key)
}
return commit_dates
}
func get_most_recent_blame(git_url string) string {
bd := get_all_blame_dates(git_url)
latest := get_latest(bd)
latest_date := latest.Format("2006-01-02 15:04:05")
return latest_date
}
func get_latest(times []time.Time) time.Time {
var n, latest int64
for i := range times {
v := times[i].Unix()
if v>n {
n = v
latest = n
}
}
return time.Unix(latest, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment