explorer.go

378 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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
package controllers

import (
	"encoding/json"
	"fmt"
	"io/fs"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"

	"congo.gg/dev/internal"
	"congo.gg/dev/models"
	"congo.gg/pkg/application"
)

func Explorer() (string, *ExplorerController) {
	return "explorer", &ExplorerController{}
}

type ExplorerController struct {
	application.BaseController

	// Per-request state (set in Handle via value receiver copy)
	repo    *models.Repository
	entries []FileEntry
	file    *SourceFile
	reqPath string
	repoDir string // translated local path
}

type FileEntry struct {
	Name  string
	IsDir bool
	Path  string
	Size  string
}

type SourceFile struct {
	Name     string
	Path     string
	Content  string
	Lines    int
	LineNums []int
	Lang     string
}

// InfraData holds parsed infra.json for template display.
type InfraData struct {
	Platforms map[string]any   `json:"platforms"`
	Servers   map[string]any   `json:"servers"`
	Services  map[string]any   `json:"services"`
	Instances map[string][]any `json:"instances"`
	Raw       string           // pretty-printed JSON
}

func (c *ExplorerController) Setup(app *application.App) {
	c.BaseController.Setup(app)
	http.Handle("GET /repos/{id}", app.Serve("project.html", RequireAuth()))
	http.Handle("GET /repos/{id}/files", app.Serve("explorer.html", RequireAuth()))
	http.Handle("GET /repos/{id}/files/{path...}", app.Serve("explorer.html", RequireAuth()))
}

func (c ExplorerController) Handle(r *http.Request) application.Controller {
	c.Request = r

	repoID := r.PathValue("id")
	if repoID == "" {
		return &c
	}

	repo, err := models.Repositories.Get(repoID)
	if err != nil {
		return &c
	}
	c.repo = repo

	p := r.PathValue("path")
	if p == "" {
		p = "."
	}
	c.reqPath = p

	// Translate coder container path to dev container path
	c.repoDir = internal.LocalRepoPath(repo.Path)
	if c.repoDir == "" {
		return &c
	}

	dirFS := os.DirFS(c.repoDir)
	info, err := fs.Stat(dirFS, p)
	if err != nil {
		return &c
	}

	if info.IsDir() {
		c.entries = readDir(dirFS, p)
	} else {
		c.file = readFile(dirFS, p)
	}

	return &c
}

// Template methods

func (c *ExplorerController) Repo() *models.Repository {
	return c.repo
}

func (c *ExplorerController) Path() string {
	if c.reqPath == "." {
		return ""
	}
	return c.reqPath
}

func (c *ExplorerController) Breadcrumbs() []FileEntry {
	if c.repo == nil {
		return nil
	}
	crumbs := []FileEntry{{Name: c.repo.Name, Path: ""}}
	if c.reqPath == "." {
		return crumbs
	}
	parts := strings.Split(c.reqPath, "/")
	for i, part := range parts {
		p := strings.Join(parts[:i+1], "/")
		crumbs = append(crumbs, FileEntry{Name: part, Path: p})
	}
	return crumbs
}

func (c *ExplorerController) Entries() []FileEntry {
	return c.entries
}

func (c *ExplorerController) File() *SourceFile {
	return c.file
}

func (c *ExplorerController) IsFile() bool {
	return c.file != nil
}

func (c *ExplorerController) NotFound() bool {
	return c.repo != nil && c.reqPath != "." && c.file == nil && c.entries == nil
}

// HasInfra returns true if the repo has an infra.json file.
func (c *ExplorerController) HasInfra() bool {
	if c.repoDir == "" {
		return false
	}
	_, err := os.Stat(filepath.Join(c.repoDir, "infra.json"))
	return err == nil
}

// Infra reads and parses infra.json from the repo.
func (c *ExplorerController) Infra() *InfraData {
	if c.repoDir == "" {
		return nil
	}
	data, err := os.ReadFile(filepath.Join(c.repoDir, "infra.json"))
	if err != nil {
		return nil
	}

	var infra InfraData
	if err := json.Unmarshal(data, &infra); err != nil {
		return nil
	}

	pretty, _ := json.MarshalIndent(json.RawMessage(data), "", "  ")
	infra.Raw = string(pretty)

	return &infra
}

// LinkedServices returns services deployed from this repo.
func (c *ExplorerController) LinkedServices() []*models.Service {
	if c.repo == nil {
		return nil
	}
	svcs, _ := models.Services.Search("WHERE RepoID = ? ORDER BY CreatedAt DESC", c.repo.ID)
	// Update live status
	for _, s := range svcs {
		if internal.IsContainerRunning("svc-" + s.Slug) {
			s.Status = "running"
		} else if s.Status == "running" {
			s.Status = "stopped"
		}
	}
	return svcs
}

// LinkedRoutes returns domains associated with services from this repo.
func (c *ExplorerController) LinkedRoutes() []*models.Domain {
	svcs := c.LinkedServices()
	if len(svcs) == 0 {
		return nil
	}
	var ids []string
	for _, s := range svcs {
		ids = append(ids, s.ID)
	}
	placeholders := strings.Repeat("?,", len(ids))
	placeholders = placeholders[:len(placeholders)-1]
	args := make([]any, len(ids))
	for i, id := range ids {
		args[i] = id
	}
	domains, _ := models.Domains.Search("WHERE ServiceID IN ("+placeholders+") ORDER BY Host", args...)
	return domains
}

// InstanceCount returns the total number of instances from infra.json.
func (c *ExplorerController) InstanceCount() int {
	infra := c.Infra()
	if infra == nil {
		return 0
	}
	count := 0
	for _, instances := range infra.Instances {
		count += len(instances)
	}
	return count
}

// Helpers

func readDir(fsys fs.FS, dirPath string) []FileEntry {
	entries, err := fs.ReadDir(fsys, dirPath)
	if err != nil {
		return nil
	}

	var dirs, files []FileEntry
	for _, e := range entries {
		// Skip hidden files and common uninteresting dirs
		if strings.HasPrefix(e.Name(), ".") && e.Name() != ".gitignore" && e.Name() != ".env.example" {
			continue
		}
		if e.IsDir() && (e.Name() == "node_modules" || e.Name() == "vendor" || e.Name() == ".git") {
			continue
		}

		var href string
		if dirPath == "." {
			href = e.Name()
		} else {
			href = dirPath + "/" + e.Name()
		}
		var size string
		if !e.IsDir() {
			if info, err := e.Info(); err == nil {
				size = formatFileSize(info.Size())
			}
		}
		entry := FileEntry{
			Name:  e.Name(),
			IsDir: e.IsDir(),
			Path:  href,
			Size:  size,
		}
		if e.IsDir() {
			dirs = append(dirs, entry)
		} else {
			files = append(files, entry)
		}
	}

	sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name < dirs[j].Name })
	sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name })

	return append(dirs, files...)
}

func readFile(fsys fs.FS, filePath string) *SourceFile {
	content, err := fs.ReadFile(fsys, filePath)
	if err != nil {
		return nil
	}

	// Skip binary files (check for null bytes in first 512 bytes)
	check := content
	if len(check) > 512 {
		check = check[:512]
	}
	for _, b := range check {
		if b == 0 {
			return &SourceFile{
				Name:    path.Base(filePath),
				Path:    filePath,
				Content: "(binary file)",
				Lines:   0,
				Lang:    "plaintext",
			}
		}
	}

	// Cap file size at 500KB for display
	if len(content) > 500*1024 {
		content = append(content[:500*1024], []byte("\n\n... (truncated)")...)
	}

	lines := strings.Count(string(content), "\n")
	if len(content) > 0 && content[len(content)-1] != '\n' {
		lines++
	}
	nums := make([]int, lines)
	for i := range nums {
		nums[i] = i + 1
	}

	return &SourceFile{
		Name:     path.Base(filePath),
		Path:     filePath,
		Content:  string(content),
		Lines:    lines,
		LineNums: nums,
		Lang:     detectLang(path.Base(filePath), filepath.Ext(filePath)),
	}
}

func formatFileSize(bytes int64) string {
	if bytes < 1024 {
		return fmt.Sprintf("%d B", bytes)
	}
	kb := float64(bytes) / 1024
	if kb < 1024 {
		return fmt.Sprintf("%.1f KB", kb)
	}
	mb := kb / 1024
	return fmt.Sprintf("%.1f MB", mb)
}

func detectLang(name, ext string) string {
	switch ext {
	case ".go", ".mod", ".sum":
		return "go"
	case ".html", ".htm", ".tmpl":
		return "xml"
	case ".js", ".jsx", ".mjs":
		return "javascript"
	case ".ts", ".tsx":
		return "typescript"
	case ".css":
		return "css"
	case ".json":
		return "json"
	case ".md":
		return "markdown"
	case ".sh", ".bash":
		return "bash"
	case ".yaml", ".yml":
		return "yaml"
	case ".sql":
		return "sql"
	case ".py":
		return "python"
	case ".rb":
		return "ruby"
	case ".rs":
		return "rust"
	case ".toml":
		return "ini"
	}
	switch name {
	case "Makefile", "Justfile":
		return "makefile"
	case "Dockerfile":
		return "dockerfile"
	}
	return "plaintext"
}