cadoles-profile/mage/gitea/option.go

116 lines
2.3 KiB
Go
Raw Normal View History

2019-05-24 19:29:22 +02:00
package gitea
import (
"bufio"
"fmt"
"os"
"strings"
"syscall"
"time"
"code.gitea.io/gitea/modules/structs"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh/terminal"
)
type Options struct {
structs.CreateReleaseOption
Attachments []string
Token string
Username string
Password string
BaseURL string
}
type OptionFunc func(*Options)
func WithAttachments(attachments ...string) OptionFunc {
return func(opts *Options) {
opts.Attachments = attachments
}
}
func WithBaseURL(baseURL string) OptionFunc {
return func(opts *Options) {
opts.BaseURL = baseURL
}
}
func WithInteractivePassword() OptionFunc {
return func(opts *Options) {
fmt.Print("Enter Password: ")
password, err := terminal.ReadPassword(syscall.Stdin)
if err != nil {
panic(errors.Wrap(err, "error while asking password"))
}
opts.Password = strings.TrimSpace(string(password))
}
}
func WithInteractiveUsername() OptionFunc {
return func(opts *Options) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Username: ")
username, err := reader.ReadString('\n')
if err != nil {
panic(errors.Wrap(err, "error while asking username"))
}
opts.Username = strings.TrimSpace(username)
}
}
func WithEnvUsername() OptionFunc {
return func(opts *Options) {
opts.Username = os.Getenv("GITEA_USERNAME")
}
}
func WithEnvPassword() OptionFunc {
return func(opts *Options) {
opts.Password = os.Getenv("GITEA_PASSWORD")
}
}
func WithAutoUsername() OptionFunc {
envUsername := WithEnvUsername()
interactiveUsername := WithInteractiveUsername()
return func(opts *Options) {
envUsername(opts)
if opts.Username != "" {
return
}
interactiveUsername(opts)
}
}
func WithAutoPassword() OptionFunc {
envPassword := WithEnvPassword()
interactivePassword := WithInteractivePassword()
return func(opts *Options) {
envPassword(opts)
if opts.Password != "" {
return
}
interactivePassword(opts)
}
}
func DefaultTagName() string {
now := time.Now()
return fmt.Sprintf("r%s", now.Format("20060102150405"))
}
func defaultOptions() *Options {
return &Options{
CreateReleaseOption: structs.CreateReleaseOption{
IsDraft: false,
IsPrerelease: true,
Note: "test",
Target: "master",
Title: "test",
TagName: "test",
},
Attachments: make([]string, 0),
}
}