source.go

214 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
package controllers

import (
	"fmt"
	"io/fs"
	"net/http"
	"path"
	"sort"
	"strings"

	"congo.gg/pkg/application"
)

// Source creates the source browser controller.
// sourceFS should embed the full Congo source tree.
func Source(sourceFS fs.FS) (string, *SourceController) {
	return "source", &SourceController{sourceFS: sourceFS}
}

type SourceController struct {
	application.BaseController
	sourceFS fs.FS

	// Per-request state (set in Handle via value receiver copy).
	entries []DirEntry
	file    *SourceFile
	reqPath string
}

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

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

func (c *SourceController) Setup(app *application.App) {
	c.BaseController.Setup(app)
	http.Handle("GET /source", app.Serve("source.html", nil))
	http.Handle("GET /source/{path...}", app.Serve("source.html", nil))
}

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

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

	info, err := fs.Stat(c.sourceFS, p)
	if err != nil {
		return &c
	}

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

	return &c
}

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

func (c *SourceController) Breadcrumbs() []DirEntry {
	crumbs := []DirEntry{{Name: "congo", 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, DirEntry{Name: part, Path: p})
	}
	return crumbs
}

func (c *SourceController) Entries() []DirEntry {
	return c.entries
}

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

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

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

func (c *SourceController) readDir(dirPath string) []DirEntry {
	entries, err := fs.ReadDir(c.sourceFS, dirPath)
	if err != nil {
		return nil
	}

	var dirs, files []DirEntry
	for _, e := range entries {
		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 = formatSize(info.Size())
			}
		}
		entry := DirEntry{
			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 formatSize(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 extToLang(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 ".css":
		return "css"
	case ".json":
		return "json"
	case ".md":
		return "markdown"
	case ".sh", ".bash":
		return "bash"
	case ".yaml", ".yml":
		return "yaml"
	}
	// Extensionless files
	switch name {
	case "Makefile":
		return "makefile"
	case "Dockerfile":
		return "dockerfile"
	}
	return "plaintext"
}

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

	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:     extToLang(path.Base(filePath), path.Ext(filePath)),
	}
}