actions/checkout-go/main.go

97 lines
2.1 KiB
Go
Raw Normal View History

2024-12-30 12:40:05 +00:00
package main
import (
"fmt"
2025-04-07 12:05:46 +00:00
"log"
2024-12-30 12:40:05 +00:00
"os"
2025-04-07 12:05:46 +00:00
"os/exec"
"strings"
2024-12-30 12:40:05 +00:00
)
type Config struct {
2025-04-09 13:41:31 +00:00
Repository string
Ref string
Token string
Path string
ServerURL string
CheckoutType CheckoutType
2025-04-09 13:53:44 +00:00
FetchDepth string
2024-12-30 12:40:05 +00:00
}
2025-04-09 13:41:31 +00:00
type CheckoutType string
const (
HttpsType = "https"
SshType = "ssh"
)
2024-12-30 12:40:05 +00:00
func getConfig() Config {
2025-04-09 13:53:44 +00:00
fetchDepth := os.Getenv("INPUT_FETCHDEPTH")
if fetchDepth == "" || fetchDepth == "0" {
fetchDepth = "1"
}
2024-12-30 12:40:05 +00:00
return Config{
2025-04-09 13:41:31 +00:00
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")),
2025-04-09 13:53:44 +00:00
FetchDepth: fetchDepth,
2024-12-30 12:40:05 +00:00
}
}
func main() {
cfg := getConfig()
2025-04-07 12:05:46 +00:00
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")
}
2025-04-09 13:41:31 +00:00
cloneURL := cfg.CheckoutType.GenerateCloneURL(cfg)
2025-04-07 12:05:46 +00:00
fmt.Println("Cloning", cloneURL, "into", cfg.Path)
2025-04-09 13:53:44 +00:00
run("git", "clone", fmt.Sprintf("--depth=%s", cfg.FetchDepth), cloneURL, cfg.Path)
2025-04-07 12:05:46 +00:00
if cfg.Ref != "" {
fmt.Println("Checking out", cfg.Ref)
2025-04-09 13:53:44 +00:00
run("git", "-C", cfg.Path, "fetch", fmt.Sprintf("--depth=%s", cfg.FetchDepth), "origin", cfg.Ref)
2025-04-07 12:05:46 +00:00
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)
}
2024-12-30 12:40:05 +00:00
}
2025-04-09 13:41:31 +00:00
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 ""
}
}