1
0
Fork 0
mirror of https://github.com/Luzifer/badge-gen.git synced 2024-11-08 13:20:02 +00:00
badge-gen/service_travis.go

88 lines
2.1 KiB
Go
Raw Normal View History

2016-06-28 19:04:13 +00:00
package main
import (
"encoding/json"
"net/http"
"strings"
2016-06-29 13:13:26 +00:00
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
2016-06-28 19:04:13 +00:00
)
const travisCacheDuration = 5 * time.Minute
2016-06-28 19:04:13 +00:00
func init() {
2016-06-28 21:56:22 +00:00
registerServiceHandler("travis", travisServiceHandler{})
}
type travisServiceHandler struct{}
func (travisServiceHandler) GetDocumentation() serviceHandlerDocumentationList {
return serviceHandlerDocumentationList{{
2016-06-28 21:56:22 +00:00
ServiceName: "Travis-CI",
DemoPath: "/travis/Luzifer/password",
Arguments: []string{"<user>", "<repo>", "[branch]"},
}}
2016-06-28 21:56:22 +00:00
}
2016-06-28 19:04:13 +00:00
func (travisServiceHandler) IsEnabled() bool { return true }
func (travisServiceHandler) Handle(ctx context.Context, params []string) (title, text, color string, err error) {
if len(params) < 2 { //nolint:gomnd
err = errors.New("you need to provide user and repo")
return title, text, color, err
2016-06-28 21:56:22 +00:00
}
if len(params) < 3 { //nolint:gomnd
2016-06-28 21:56:22 +00:00
params = append(params, "master")
}
path := strings.Join([]string{"repos", params[0], params[1], "branches", params[2]}, "/")
2016-06-29 13:13:26 +00:00
var state string
state, err = cacheStore.Get("travis", path)
2016-06-28 21:56:22 +00:00
if err != nil {
2016-06-29 13:13:26 +00:00
var resp *http.Response
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.travis-ci.org/"+path, nil)
resp, err = http.DefaultClient.Do(req)
2016-06-29 13:13:26 +00:00
if err != nil {
return title, text, color, errors.Wrap(err, "executing request")
2016-06-29 13:13:26 +00:00
}
defer func() {
if err := resp.Body.Close(); err != nil {
logrus.WithError(err).Error("closing request body (leaked fd)")
}
}()
2016-06-28 21:56:22 +00:00
2016-06-29 13:13:26 +00:00
r := struct {
File string `json:"file"`
Branch struct {
State string `json:"state"`
} `json:"branch"`
}{}
2016-06-28 21:56:22 +00:00
2016-06-29 13:13:26 +00:00
if err = json.NewDecoder(resp.Body).Decode(&r); err != nil {
return title, text, color, errors.Wrap(err, "decoding JSON response")
2016-06-29 13:13:26 +00:00
}
state = r.Branch.State
logErr(cacheStore.Set("travis", path, state, travisCacheDuration), "writing Travis status to cache")
2016-06-28 21:56:22 +00:00
}
title = "travis"
2016-06-29 13:13:26 +00:00
text = state
2016-06-28 21:56:22 +00:00
if text == "" {
text = "unknown"
}
color = map[string]string{
"unknown": "9f9f9f",
"passed": "4c1",
"failed": "e05d44",
"canceled": "9f9f9f",
}[text]
return title, text, color, nil
2016-06-28 19:04:13 +00:00
}