package main import ( "fmt" "log" "os" "os/exec" "strings" ) type Config struct { Repository string Ref string Token string Path string ServerURL string CheckoutType CheckoutType FetchDepth string } type CheckoutType string const ( HttpsType = "https" SshType = "ssh" ) func getConfig() Config { fetchDepth := os.Getenv("INPUT_FETCHDEPTH") if fetchDepth == "" || fetchDepth == "0" { fetchDepth = "1" } return Config{ Repository: os.Getenv("INPUT_REPOSITORY"), Ref: os.Getenv("INPUT_REF"), Token: os.Getenv("INPUT_TOKEN"), Path: os.Getenv("INPUT_PATH"), ServerURL: os.Getenv("INPUT_SERVERURL"), CheckoutType: CheckoutType(os.Getenv("INPUT_CHECKOUTTYPE")), FetchDepth: fetchDepth, } } func main() { cfg := getConfig() if cfg.Repository == "" { log.Fatal("field repository is required") } if cfg.Token == "" { log.Fatal("field token is required") } fmt.Println(cfg.Token) if cfg.ServerURL == "" { log.Fatal("field serverURL is required") } cloneURL := cfg.CheckoutType.GenerateCloneURL(cfg) fmt.Println("Cloning", cloneURL, "into", cfg.Path) run("git", "clone", fmt.Sprintf("--depth=%s", cfg.FetchDepth), cloneURL, cfg.Path) if cfg.Ref != "" { fmt.Println("Checking out", cfg.Ref) run("git", "-C", cfg.Path, "fetch", fmt.Sprintf("--depth=%s", cfg.FetchDepth), "origin", cfg.Ref) run("git", "-C", cfg.Path, "checkout", "FETCH_HEAD") } } func run(name string, args ...string) { cmd := exec.Command(name, args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatalf("Command failed: %s %s Error: %v", name, strings.Join(args, " "), err) } } func (t CheckoutType) GenerateCloneURL(cfg Config) string { switch t { case HttpsType: return fmt.Sprintf("https://x-access-token:%s@%s/%s.git", cfg.Token, strings.TrimPrefix(cfg.ServerURL, "https://"), cfg.Repository, ) case SshType: return fmt.Sprintf("git@%s:%s.git", strings.TrimPrefix(cfg.ServerURL, "git@"), cfg.Repository, ) default: log.Fatalf("Unknown checkout type: %s", t) return "" } }