gitea-plugin/release/gitea.go

107 lines
2.1 KiB
Go
Raw Normal View History

2023-08-24 06:12:27 +00:00
package release
import (
"errors"
"io"
"os"
"path/filepath"
"code.gitea.io/sdk/gitea"
"golang.org/x/sync/errgroup"
sdk "code.icb4dc0.de/buildr/wasi-module-sdk-go"
)
var (
_ sdk.Module = (*GiteaRelease)(nil)
)
type GiteaRelease struct {
API struct {
URL string
Token string
}
Repo struct {
Owner string
Name string
}
Tag string
Target string
Title string
Note string
PreRelease bool
Draft bool
Attachments []string
}
func (GiteaRelease) Category() sdk.Category {
return sdk.CategoryRelease
}
func (GiteaRelease) Type() string {
return "gitea"
}
func (g GiteaRelease) Execute(ctx sdk.ExecutionContext) error {
giteaClient, err := gitea.NewClient(g.API.URL, gitea.SetToken(g.API.Token))
if err != nil {
return err
}
giteaClient.SetContext(ctx)
release, err := g.createRelease(giteaClient)
if err != nil {
return err
}
return g.createReleaseAttachments(ctx, giteaClient, release)
}
func (g GiteaRelease) createRelease(cli releaseCreator) (*gitea.Release, error) {
releaseOpts := gitea.CreateReleaseOption{
TagName: g.Tag,
Target: g.Target,
Title: g.Title,
Note: g.Note,
IsDraft: g.Draft,
IsPrerelease: g.PreRelease,
}
release, _, err := cli.CreateRelease(g.Repo.Owner, g.Repo.Name, releaseOpts)
return release, err
}
func (g GiteaRelease) createReleaseAttachments(ctx sdk.ExecutionContext, cli releaseAttachmentCreator, release *gitea.Release) error {
grp, grpCtx := errgroup.WithContext(ctx)
for _, attachment := range g.Attachments {
attachment := attachment
grp.Go(func() (err error) {
var attachmentReader io.ReadCloser
if filepath.IsAbs(attachment) {
attachmentReader, err = os.Open(attachment)
} else {
attachmentReader, err = os.Open(filepath.Join(ctx.WorkingDir(), attachment))
}
if err != nil {
return err
}
defer func() {
err = errors.Join(err, attachmentReader.Close())
}()
_, fileName := filepath.Split(attachment)
cli.SetContext(grpCtx)
_, _, err = cli.CreateReleaseAttachment(g.Repo.Owner, g.Repo.Name, release.ID, attachmentReader, fileName)
return err
})
}
return grp.Wait()
}