|
| 1 | +package internal |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "gitte/config" |
| 7 | + "gitte/executor" |
| 8 | + "os" |
| 9 | + "regexp" |
| 10 | +) |
| 11 | + |
| 12 | +func GitOps(ctx context.Context, cwd string, gitteConfig config.GitteConfig) error { |
| 13 | + for _, pc := range gitteConfig.Projects { |
| 14 | + if err := gitopsProject(ctx, cwd, pc); err != nil { |
| 15 | + return err |
| 16 | + } |
| 17 | + } |
| 18 | + return nil |
| 19 | +} |
| 20 | + |
| 21 | +func gitopsProject(ctx context.Context, cwd string, pc config.ProjectConfig) error { |
| 22 | + relativeDirectory, err := getProjectDirFromRemote(pc) |
| 23 | + if err != nil { |
| 24 | + return err |
| 25 | + } |
| 26 | + |
| 27 | + projectPath := fmt.Sprintf("%s/%s", cwd, relativeDirectory) // TODO join prettier |
| 28 | + |
| 29 | + // Check if directory exists |
| 30 | + if _, err := os.Stat(projectPath); os.IsNotExist(err) { |
| 31 | + // Directory does not exist, clone the repository |
| 32 | + fmt.Println("Cloning repository:", pc.Remote, "into", projectPath) |
| 33 | + return clone(ctx, cwd, pc) |
| 34 | + } |
| 35 | + return nil // TODO pull and update |
| 36 | +} |
| 37 | + |
| 38 | +func clone(ctx context.Context, cwd string, pc config.ProjectConfig) error { |
| 39 | + relativeDirectory, err := getProjectDirFromRemote(pc) |
| 40 | + if err != nil { |
| 41 | + return err |
| 42 | + } |
| 43 | + |
| 44 | + res, err := executor.ExecuteSyncInDir(cwd, "git", "clone", pc.Remote, relativeDirectory) |
| 45 | + if err != nil { |
| 46 | + return fmt.Errorf("failed to execute git clone command: %w", err) |
| 47 | + } |
| 48 | + |
| 49 | + if res.ExitCode != 0 { |
| 50 | + // If res.Stderr contains "Permission denied" return a specific error |
| 51 | + if regexp.MustCompile(`(?i)permission denied`).Match(res.Stderr) { |
| 52 | + return fmt.Errorf("permission denied when trying to clone repository '%s'. Please check your SSH keys and access rights", pc.Remote) |
| 53 | + } |
| 54 | + return fmt.Errorf("git clone command failed with exit code %d: \n%s", res.ExitCode, string(res.Stderr)) |
| 55 | + } |
| 56 | + |
| 57 | + return nil |
| 58 | +} |
| 59 | + |
| 60 | +func getProjectDirFromRemote(pc config.ProjectConfig) (string, error) { |
| 61 | + // const match = remote.match(/git@.*?:.*?\.git/); |
| 62 | + |
| 63 | + regex := regexp.MustCompile(`git@.*?:(.*)?\.git`) |
| 64 | + match := regex.FindStringSubmatch(pc.Remote) |
| 65 | + |
| 66 | + firstMatch := "" |
| 67 | + if len(match) > 1 { |
| 68 | + firstMatch = match[1] |
| 69 | + } |
| 70 | + |
| 71 | + if firstMatch == "" { |
| 72 | + return "", fmt.Errorf("'%' is not a valid git ssh url. Use git@gitlab.com:example/cego.git syntax", pc.Remote) |
| 73 | + } |
| 74 | + |
| 75 | + return firstMatch, nil |
| 76 | +} |
0 commit comments