explorer.go

489 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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
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
	linkedSvcs   []internal.LocalService
	linkedLoaded bool
}

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 {
	Provider     string
	Region       string
	ServerGroups []InfraServerGroup
	ServiceList  []InfraServiceInfo
	Raw          string
}

type InfraServerGroup struct {
	Name      string
	Size      string
	Instances []InfraInstanceInfo
}

type InfraInstanceInfo struct {
	Name   string
	IP     string
	Region string
	Role   string
}

type InfraServiceInfo struct {
	Name   string
	Image  string
	Source string
	Ports  string
}

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

// SetRequest binds the request and loads the repository, path, and directory or
// file being browsed. It runs once per request (the framework memoizes the
// spawned controller), so the load is not repeated across template references.
func (c *ExplorerController) SetRequest(r *http.Request) {
	c.Request = r

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

	repo, err := models.Repositories.Get(repoID)
	if err != nil {
		return
	}
	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
	}

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

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

// 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 into typed display structures.
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 raw map[string]any
	if err := json.Unmarshal(data, &raw); err != nil {
		return nil
	}

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

	// Extract provider/region from "platforms" (map) or "platform" (single)
	if platforms, ok := raw["platforms"].(map[string]any); ok {
		for _, p := range platforms {
			if pm, ok := p.(map[string]any); ok {
				infra.Provider = jsonString(pm, "provider")
				infra.Region = jsonString(pm, "region")
				break
			}
		}
	} else if platform, ok := raw["platform"].(map[string]any); ok {
		infra.Provider = jsonString(platform, "provider")
		infra.Region = jsonString(platform, "region")
	}

	// Server type sizes for lookup
	serverSizes := map[string]string{}
	if servers, ok := raw["servers"].(map[string]any); ok {
		for name, s := range servers {
			if sm, ok := s.(map[string]any); ok {
				serverSizes[name] = jsonString(sm, "size")
			}
		}
	}

	// Build server groups from instances
	if instances, ok := raw["instances"].(map[string]any); ok {
		for groupName, insts := range instances {
			group := InfraServerGroup{
				Name: groupName,
				Size: serverSizes[groupName],
			}
			if instSlice, ok := insts.([]any); ok {
				for _, inst := range instSlice {
					if im, ok := inst.(map[string]any); ok {
						group.Instances = append(group.Instances, InfraInstanceInfo{
							Name:   jsonString(im, "name"),
							IP:     jsonString(im, "ip"),
							Region: jsonString(im, "region"),
							Role:   jsonString(im, "role"),
						})
					}
				}
			}
			infra.ServerGroups = append(infra.ServerGroups, group)
		}
		sort.Slice(infra.ServerGroups, func(i, j int) bool {
			return infra.ServerGroups[i].Name < infra.ServerGroups[j].Name
		})
	}

	// Build service list
	if services, ok := raw["services"].(map[string]any); ok {
		for name, s := range services {
			if sm, ok := s.(map[string]any); ok {
				svc := InfraServiceInfo{
					Name:   name,
					Image:  jsonString(sm, "image"),
					Source: jsonString(sm, "source"),
				}
				if ports, ok := sm["ports"].([]any); ok {
					var ps []string
					for _, p := range ports {
						if pm, ok := p.(map[string]any); ok {
							if host, ok := pm["host"].(float64); ok {
								ps = append(ps, fmt.Sprintf(":%d", int(host)))
							}
						}
					}
					svc.Ports = strings.Join(ps, " ")
				}
				infra.ServiceList = append(infra.ServiceList, svc)
			}
		}
		sort.Slice(infra.ServiceList, func(i, j int) bool {
			return infra.ServiceList[i].Name < infra.ServiceList[j].Name
		})
	}

	return infra
}

func jsonString(m map[string]any, key string) string {
	if v, ok := m[key].(string); ok {
		return v
	}
	return ""
}

// LinkedServices returns services from this project's infra.json (cached per request).
func (c *ExplorerController) LinkedServices() []internal.LocalService {
	if c.repo == nil {
		return nil
	}
	if !c.linkedLoaded {
		c.linkedSvcs = internal.ProjectServices(c.repo.Name, c.repo.ID)
		c.linkedLoaded = true
	}
	return c.linkedSvcs
}

// LinkedRunningCount returns the number of running services from this project.
func (c *ExplorerController) LinkedRunningCount() int {
	count := 0
	for _, svc := range c.LinkedServices() {
		if svc.Status == "running" {
			count++
		}
	}
	return count
}

// 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 names []any
	for _, s := range svcs {
		names = append(names, s.ContainerName)
	}
	placeholders := strings.Repeat("?,", len(names))
	placeholders = placeholders[:len(placeholders)-1]
	domains, _ := models.Domains.Search("WHERE ContainerName IN ("+placeholders+") ORDER BY Host", names...)
	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 _, group := range infra.ServerGroups {
		count += len(group.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"
}