github.com/pmoroney/dnscontrol@v0.2.4-0.20171024134423-fad98f73f44a/build/masterRelease/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "log" 6 "os" 7 "strings" 8 9 "fmt" 10 "time" 11 12 "github.com/google/go-github/github" 13 "golang.org/x/oauth2" 14 ) 15 16 const ( 17 owner = "StackExchange" 18 repo = "dnscontrol" 19 tag = "latest" 20 ) 21 22 func check(err error) { 23 if err != nil { 24 log.Fatal(err) 25 } 26 } 27 28 var bg = context.Background 29 30 var files = []string{"dnscontrol.exe", "dnscontrol-Linux", "dnscontrol-Darwin"} 31 32 func main() { 33 34 tok := os.Getenv("GITHUB_ACCESS_TOKEN") 35 if tok == "" { 36 log.Fatal("$GITHUB_ACCESS_TOKEN required") 37 } 38 c := github.NewClient(oauth2.NewClient(bg(), oauth2.StaticTokenSource(&oauth2.Token{AccessToken: tok}))) 39 40 log.Println("Getting release info") 41 rel, _, err := c.Repositories.GetReleaseByTag(bg(), owner, repo, tag) 42 check(err) 43 44 for _, f := range files { 45 log.Printf("--- %s", f) 46 47 var found github.ReleaseAsset 48 var exists bool 49 var foundOld bool 50 for _, ass := range rel.Assets { 51 if ass.GetName() == f { 52 exists = true 53 found = ass 54 } 55 if ass.GetName() == f+".old" { 56 foundOld = true 57 } 58 } 59 60 if foundOld { 61 log.Fatalf("%s.old was already found. Previous deploy likely failed. Please check and manually delete.", f) 62 } 63 if exists { 64 oldN := found.GetName() 65 n := oldN + ".old" 66 found.Name = &n 67 log.Printf("Renaming old asset %s(%d) to %s", oldN, found.GetID(), found.GetName()) 68 _, _, err = c.Repositories.EditReleaseAsset(bg(), owner, repo, found.GetID(), &found) 69 check(err) 70 } 71 72 log.Printf("Uploading new file %s", f) 73 upOpts := &github.UploadOptions{} 74 upOpts.Name = f 75 f, err := os.Open(f) 76 check(err) 77 _, _, err = c.Repositories.UploadReleaseAsset(bg(), owner, repo, rel.GetID(), upOpts, f) 78 check(err) 79 80 if exists { 81 log.Println("Deleting old asset") 82 _, err = c.Repositories.DeleteReleaseAsset(bg(), owner, repo, found.GetID()) 83 check(err) 84 } 85 } 86 87 log.Println("Editing release body") 88 body := strings.TrimSpace(rel.GetBody()) 89 lines := strings.Split(body, "\n") 90 last := lines[len(lines)-1] 91 if !strings.HasPrefix(last, "Last updated:") { 92 log.Fatal("Release body is not what I expected. Abort!") 93 } 94 last = fmt.Sprintf("Last updated: %s", time.Now().Format("Mon Jan 2 2006 @ 15:04 MST")) 95 lines[len(lines)-1] = last 96 body = strings.Join(lines, "\n") 97 rel.Body = &body 98 c.Repositories.EditRelease(bg(), owner, repo, rel.GetID(), rel) 99 100 log.Println("DONE") 101 }