buildr/modules/helpers/github/get_release_info.go

80 lines
1.9 KiB
Go
Raw Permalink Normal View History

2023-03-15 17:56:38 +00:00
package github
import (
"context"
"net/http"
2023-03-15 17:56:38 +00:00
"time"
gh "github.com/google/go-github/v53/github"
"code.icb4dc0.de/buildr/buildr/modules/state"
2023-03-15 17:56:38 +00:00
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
const DefaultAPITimeout = 30 * time.Second
func GetLatestReleaseTag(ctx context.Context, cache state.Cache) function.Function {
2023-03-15 17:56:38 +00:00
return function.New(&function.Spec{
Description: "Get tag of latest release of Github project",
Params: []function.Parameter{
{
Name: "owner",
Description: "Owner of the repository",
Type: cty.String,
},
{
Name: "repo",
Description: "Name of the repository",
Type: cty.String,
},
},
VarParam: &function.Parameter{
Name: "token",
Description: "GitHub API token",
Type: cty.String,
},
2023-03-15 17:56:38 +00:00
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
owner := args[0].AsString()
repo := args[1].AsString()
cacheKey := state.KeyOfStrings("latest_github_release", owner, repo)
if cache != nil {
val, _, err := cache.Get(ctx, cacheKey)
if err == nil && len(val) > 0 {
return cty.StringVal(string(val)), nil
}
}
var cli *gh.Client
if len(args) >= 3 && args[2].AsString() != "" && args[2].AsString() != "<mocked>" {
cli = gh.NewTokenClient(ctx, args[2].AsString())
} else {
cli = gh.NewClient(http.DefaultClient)
}
2023-03-15 17:56:38 +00:00
if cli == nil {
return cty.StringVal("<mocked>"), nil
2023-03-15 17:56:38 +00:00
}
2023-06-22 16:06:56 +00:00
opCtx, cancel := context.WithTimeout(ctx, DefaultAPITimeout)
2023-03-15 17:56:38 +00:00
defer cancel()
2023-06-22 16:06:56 +00:00
release, _, err := cli.Repositories.GetLatestRelease(opCtx, owner, repo)
2023-03-15 17:56:38 +00:00
if err != nil {
return cty.Value{}, err
}
if cache != nil {
2023-06-22 16:06:56 +00:00
_ = cache.Set(opCtx, cacheKey, []byte(release.GetTagName()))
}
2023-03-15 17:56:38 +00:00
return cty.StringVal(release.GetTagName()), nil
},
})
}