package gitea import ( "fmt" "os" "path/filepath" "code.gitea.io/gitea/modules/structs" "code.gitea.io/sdk/gitea" "github.com/magefile/mage/mg" "github.com/pkg/errors" ) const ( AccessTokenName = "mage-gitea" ) func Release(user, repo string, opts ...OptionFunc) error { options := defaultOptions() for _, o := range opts { o(options) } client := gitea.NewClient(options.BaseURL, options.Token) if options.Token == "" { accessToken, err := retrieveAccessToken(client, options.Username, options.Password) if err != nil { return errors.Wrap(err, "error while retrieving gitea access token") } client = gitea.NewClient(options.BaseURL, accessToken.Token) } if mg.Verbose() { fmt.Printf("Creating release '%s' for repo '%s/%s'\n", options.Title, user, repo) } release, err := client.CreateRelease( user, repo, options.CreateReleaseOption, ) if err != nil { return errors.Wrap(err, "error while creating gitea release") } for _, filePath := range options.Attachments { file, err := os.Open(filePath) if err != nil { return errors.Wrapf(err, "error while opening file '%s'", filePath) } fileName := filepath.Base(filePath) if mg.Verbose() { fmt.Printf("Uploading attachment '%s'\n", fileName) } _, err = client.CreateReleaseAttachment(user, repo, release.ID, file, fileName) if err != nil { return errors.Wrapf(err, "error while creating attachment with file '%s'", filePath) } if err := file.Close(); err != nil { return errors.Wrapf(err, "error while closing file '%s'", filePath) } } return nil } func retrieveAccessToken(client *gitea.Client, username, password string) (*gitea.AccessToken, error) { tokens, err := client.ListAccessTokens(username, password) if err != nil { return nil, err } for _, at := range tokens { if at.Name == AccessTokenName { return at, nil } } accessToken, err := client.CreateAccessToken(username, password, structs.CreateAccessTokenOption{ Name: AccessTokenName, }) if err != nil { return nil, err } return accessToken, nil }