repos.go

316 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
package internal

import (
	"fmt"
	"log"
	"path/filepath"
	"regexp"
	"strings"

	"congo.gg/dev/models"
)

var nonSlugChars = regexp.MustCompile(`[^a-z0-9-]+`)

// RepoSlug converts a name to a URL-safe slug for use as a model ID.
func RepoSlug(name string) string {
	s := strings.ToLower(strings.TrimSpace(name))
	s = nonSlugChars.ReplaceAllString(s, "-")
	s = strings.Trim(s, "-")
	if s == "" {
		return "repo"
	}
	return s
}

var reposDir = "/home/coder/repos"

// CloneRepository clones a git repo into the code-server container.
func CloneRepository(repoURL, name string) error {
	if name == "" {
		name = parseRepoName(repoURL)
	}
	if name == "" {
		return fmt.Errorf("repository name cannot be empty")
	}

	existing, _ := models.Repositories.First("WHERE Name = ?", name)
	if existing != nil {
		return fmt.Errorf("a repository named '%s' already exists", name)
	}

	CoderExec("mkdir -p " + reposDir)
	targetDir := filepath.Join(reposDir, name)

	exists, _ := CoderExec(fmt.Sprintf("test -d %s && echo exists", targetDir))
	if strings.TrimSpace(exists) == "exists" {
		return fmt.Errorf("directory %s already exists", name)
	}

	output, err := CoderExec(fmt.Sprintf("git clone %s %s 2>&1", repoURL, targetDir))
	if err != nil {
		if strings.Contains(output, "Permission denied") || strings.Contains(output, "Could not read from remote") {
			return fmt.Errorf("authentication failed — add your SSH key to the git provider")
		}
		if strings.Contains(output, "does not exist") || strings.Contains(output, "not found") {
			return fmt.Errorf("repository not found — check the URL")
		}
		if strings.Contains(output, "Could not resolve") || strings.Contains(output, "unable to access") {
			return fmt.Errorf("network error — check connection and try again")
		}
		return fmt.Errorf("clone failed")
	}

	branch := "main"
	if branchOut, err := CoderExec(fmt.Sprintf("git -C %s rev-parse --abbrev-ref HEAD", targetDir)); err == nil {
		branch = strings.TrimSpace(branchOut)
	}

	repo := &models.Repository{
		Name:   name,
		URL:    repoURL,
		Path:   targetDir,
		Branch: branch,
		Status: "cloned",
	}
	repo.ID = RepoSlug(name)
	if _, err := models.Repositories.Insert(repo); err != nil {
		return fmt.Errorf("failed to save repository: %w", err)
	}

	go models.Activities.Insert(&models.Activity{
		Action: "clone",
		Detail: fmt.Sprintf("Cloned %s", name),
	})
	return nil
}

// PullRepository fetches latest changes.
func PullRepository(repoName string) error {
	repo, err := models.Repositories.First("WHERE Name = ?", repoName)
	if err != nil {
		return fmt.Errorf("repository '%s' not found", repoName)
	}

	exists, _ := CoderExec(fmt.Sprintf("test -d %s && echo exists", repo.Path))
	if strings.TrimSpace(exists) != "exists" {
		log.Printf("repo directory missing, re-cloning: %s", repoName)
		CoderExec("mkdir -p " + reposDir)
		if _, err := CoderExec(fmt.Sprintf("git clone %s %s 2>&1", repo.URL, repo.Path)); err != nil {
			return fmt.Errorf("directory missing and re-clone failed")
		}
		go models.Activities.Insert(&models.Activity{
			Action: "pull",
			Detail: fmt.Sprintf("Re-cloned missing repository %s", repoName),
		})
		return nil
	}

	output, err := CoderExec(fmt.Sprintf("cd %s && git pull 2>&1", repo.Path))
	if err != nil {
		if strings.Contains(output, "Permission denied") {
			return fmt.Errorf("authentication failed — check your SSH key")
		}
		if strings.Contains(output, "merge conflict") || strings.Contains(output, "Merge conflict") {
			return fmt.Errorf("merge conflicts — resolve manually in VS Code")
		}
		if strings.Contains(output, "uncommitted changes") || strings.Contains(output, "Your local changes") {
			return fmt.Errorf("uncommitted changes — commit or stash first")
		}
		return fmt.Errorf("pull failed")
	}

	if branchOut, err := CoderExec(fmt.Sprintf("git -C %s rev-parse --abbrev-ref HEAD", repo.Path)); err == nil {
		repo.Branch = strings.TrimSpace(branchOut)
		models.Repositories.Update(repo)
	}

	go models.Activities.Insert(&models.Activity{
		Action: "pull",
		Detail: fmt.Sprintf("Synced %s", repoName),
	})
	return nil
}

// DeleteRepository removes a repo from the filesystem and database.
func DeleteRepository(name string) error {
	repo, err := models.Repositories.First("WHERE Name = ?", name)
	if err != nil {
		return fmt.Errorf("repository not found: %s", name)
	}

	if _, err := CoderExec(fmt.Sprintf("rm -rf %s", repo.Path)); err != nil {
		return fmt.Errorf("failed to delete files: %w", err)
	}

	if err := models.Repositories.Delete(repo); err != nil {
		return fmt.Errorf("failed to delete record: %w", err)
	}

	go models.Activities.Insert(&models.Activity{
		Action: "delete",
		Detail: fmt.Sprintf("Deleted %s", name),
	})
	return nil
}

// InitRepository creates a new empty git repo.
func InitRepository(name string) error {
	if name == "" {
		return fmt.Errorf("repository name is required")
	}

	existing, _ := models.Repositories.First("WHERE Name = ?", name)
	if existing != nil {
		return fmt.Errorf("a repository named '%s' already exists", name)
	}

	CoderExec("mkdir -p " + reposDir)
	targetDir := filepath.Join(reposDir, name)

	exists, _ := CoderExec(fmt.Sprintf("test -d %s && echo exists", targetDir))
	if strings.TrimSpace(exists) == "exists" {
		return fmt.Errorf("directory %s already exists", name)
	}

	if out, err := CoderExec(fmt.Sprintf("git init %s 2>&1", targetDir)); err != nil {
		return fmt.Errorf("git init failed: %s", strings.TrimSpace(out))
	}

	branch := "main"
	if branchOut, err := CoderExec(fmt.Sprintf("git -C %s rev-parse --abbrev-ref HEAD", targetDir)); err == nil {
		branch = strings.TrimSpace(branchOut)
	}

	repo := &models.Repository{
		Name:   name,
		Path:   targetDir,
		Branch: branch,
		Status: "cloned",
	}
	repo.ID = RepoSlug(name)
	if _, err := models.Repositories.Insert(repo); err != nil {
		return fmt.Errorf("failed to save repository: %w", err)
	}

	go models.Activities.Insert(&models.Activity{
		Action: "init",
		Detail: fmt.Sprintf("Initialized %s", name),
	})
	return nil
}

// SyncFromFilesystem scans repos directory and syncs DB state.
func SyncFromFilesystem() {
	if !IsCoderRunning() {
		return
	}

	output, err := CoderExec("ls -1 " + reposDir + " 2>/dev/null")
	if err != nil {
		return
	}

	found := make(map[string]bool)
	for _, name := range strings.Split(strings.TrimSpace(output), "\n") {
		name = strings.TrimSpace(name)
		if name == "" {
			continue
		}

		isGit, _ := CoderExec(fmt.Sprintf("test -d %s/%s/.git && echo yes", reposDir, name))
		if strings.TrimSpace(isGit) != "yes" {
			continue
		}

		found[name] = true

		existing, _ := models.Repositories.First("WHERE Name = ?", name)
		if existing != nil {
			existing.StatusDetail = gitStatusSummary(name)
			if branchOut, err := CoderExec(fmt.Sprintf("git -C %s/%s rev-parse --abbrev-ref HEAD", reposDir, name)); err == nil {
				existing.Branch = strings.TrimSpace(branchOut)
			}
			models.Repositories.Update(existing)
			continue
		}

		targetDir := filepath.Join(reposDir, name)
		branch := "main"
		if branchOut, err := CoderExec(fmt.Sprintf("git -C %s rev-parse --abbrev-ref HEAD", targetDir)); err == nil {
			branch = strings.TrimSpace(branchOut)
		}

		repoURL := ""
		if urlOut, err := CoderExec(fmt.Sprintf("git -C %s remote get-url origin 2>/dev/null", targetDir)); err == nil {
			repoURL = strings.TrimSpace(urlOut)
		}

		repo := &models.Repository{
			Name:         name,
			URL:          repoURL,
			Path:         targetDir,
			Branch:       branch,
			Status:       "discovered",
			StatusDetail: gitStatusSummary(name),
		}
		repo.ID = RepoSlug(name)
		models.Repositories.Insert(repo)
		log.Printf("discovered repo: %s", name)
	}

	allRepos, _ := models.Repositories.All()
	for _, repo := range allRepos {
		if !found[repo.Name] {
			repo.Status = "missing"
			repo.StatusDetail = "directory not found"
			models.Repositories.Update(repo)
		}
	}
}

func gitStatusSummary(name string) string {
	output, err := CoderExec(fmt.Sprintf("git -C %s/%s status --porcelain 2>/dev/null | wc -l", reposDir, name))
	if err != nil {
		return ""
	}
	count := strings.TrimSpace(output)
	if count == "0" {
		return "clean"
	}
	return count + " files changed"
}

// LocalRepoPath translates a code-server repo path (/home/coder/repos/<name>)
// to the dev container's local path (DATA_DIR/repos/<name>).
// Docker operations (build, etc.) need paths accessible from this container.
func LocalRepoPath(coderPath string) string {
	name := filepath.Base(coderPath)
	return filepath.Join(hostReposDir(), name)
}

func parseRepoName(u string) string {
	if u == "" {
		return ""
	}
	u = strings.TrimSpace(u)
	u = strings.TrimSuffix(u, "/")
	u = strings.TrimSuffix(u, ".git")

	if strings.HasPrefix(u, "git@") {
		parts := strings.Split(u, ":")
		if len(parts) > 1 {
			segments := strings.Split(parts[1], "/")
			if len(segments) > 0 && segments[len(segments)-1] != "" {
				return segments[len(segments)-1]
			}
		}
		return ""
	}

	parts := strings.Split(u, "/")
	if len(parts) > 0 && parts[len(parts)-1] != "" {
		return parts[len(parts)-1]
	}
	return ""
}