// Copyright 2020 the Drone Authors. All rights reserved. // Use of this source code is governed by the Blue Oak Model License // that can be found in the LICENSE file. package plugin import ( "encoding/base64" "encoding/json" "fmt" "io" "log" "net/http" "os" "strings" "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing/transport/client" githttp "github.com/go-git/go-git/v5/plumbing/transport/http" ) type GetLatestGitTagOption func(repo *git.Repository) error type BasicAuthTransport struct { Username string Password string RoundTriper http.RoundTripper } func (bat BasicAuthTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { creds := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", bat.Username, bat.Password))) req.Header.Set("Authorization", fmt.Sprintf("Basic %s", creds)) return bat.RoundTriper.RoundTrip(req) } func SetBasicAuth(username, password string) func(repo *git.Repository) error { return func(repo *git.Repository) error { log.Println("Configuring basic auth for https") customClient := &http.Client{ Transport: BasicAuthTransport{username, password, http.DefaultTransport}, } // Override http(s) default protocol to use our custom client client.InstallProtocol("https", githttp.NewClient(customClient)) return nil } } func FetchTags() func(repo *git.Repository) error { return func(repo *git.Repository) error { log.Println("Fetching latest git tags") err := repo.Fetch(&git.FetchOptions{Tags: git.AllTags}) if err == git.NoErrAlreadyUpToDate { return nil } return err } } func getLatestGitTag(options ...GetLatestGitTagOption) (tag string, err error) { r, err := git.PlainOpen(".") if err != nil { return "", fmt.Errorf("error opening git repo at %s: %w", ".", err) } for _, opt := range options { err := opt(r) if err != nil { return "", err } } tagRefs, err := r.Tags() if err != nil { return "", fmt.Errorf("error getting git tag refs %w", err) } ref, err := tagRefs.Next() if err == io.EOF { return tag, fmt.Errorf("couldn't find any git tags %w", err) } if err != nil { return tag, fmt.Errorf("error iterating tags %w", err) } parts := strings.Split(string(ref.Name()), "/") tag = strings.Join(parts[2:], "/") return } func writeCard(path, schema string, card interface{}) { data, _ := json.Marshal(map[string]interface{}{ "schema": schema, "data": card, }) switch { case path == "/dev/stdout": writeCardTo(os.Stdout, data) case path == "/dev/stderr": writeCardTo(os.Stderr, data) case path != "": os.WriteFile(path, data, 0644) } } func writeCardTo(out io.Writer, data []byte) { encoded := base64.StdEncoding.EncodeToString(data) io.WriteString(out, "\u001B]1338;") io.WriteString(out, encoded) io.WriteString(out, "\u001B]0m") io.WriteString(out, "\n") }