navid/veinsforge / 0a20713c8f274f2128a18dc74c8c8081cd2a258a4e2ef2e997c8f14141626229 / internal/vn/browse.go

browse.go

← internal/vn · 8937 bytes · raw · download

package vn

import (
	"context"
	"errors"
	"io"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"
)

var ErrTooLarge = errors.New("file is too large to display")

type FileData struct {
	Data       []byte
	Size       int64
	IsSymlink  bool
	LinkTarget string
	ModTime    time.Time
}

func (r *Runner) EnsureBrowse(ctx context.Context, repoID int64, central string) (string, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	return r.ensureBrowseLocked(ctx, repoID, central)
}

func (r *Runner) ensureBrowseLocked(ctx context.Context, repoID int64, central string) (string, error) {
	path := r.BrowsePath(repoID)
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		return "", err
	}
	if !r.RepoExists(path) {
		if _, err := r.runOK(ctx, filepath.Dir(path), nil, "init", path); err != nil {
			return "", err
		}
		_ = os.Chmod(path, 0o700)
	}
	if err := r.ensureRemoteConfig(path, central); err != nil {
		return "", err
	}
	head := currentHead(central)
	if head == "" {
		return path, nil
	}
	r.mu.Lock()
	last := r.fetchAt[repoID]
	seen := r.fetchHead[repoID]
	r.mu.Unlock()
	if head == seen && time.Since(last) < 30*time.Second {
		return path, nil
	}
	if _, errOut, err := r.runLong(ctx, path, nil, "fetch", "origin"); err != nil {
		if r.Logger != nil {
			r.Logger.Printf("vn fetch for repo %d failed: %v: %s", repoID, err, truncate(string(errOut), 1024))
		}
		// Back off for a short while instead of re-running a failing fetch on
		// every page request.
	}
	r.mu.Lock()
	r.fetchAt[repoID] = time.Now()
	r.fetchHead[repoID] = head
	r.mu.Unlock()
	return path, nil
}

func (r *Runner) ensureRemoteConfig(repoPath, central string) error {
	cfgPath := filepath.Join(repoPath, ".veins", "config")
	data, _ := os.ReadFile(cfgPath)
	var kept []string
	for _, line := range strings.Split(string(data), "\n") {
		trimmed := strings.TrimSpace(line)
		if strings.HasPrefix(trimmed, "remote.origin.url =") ||
			strings.HasPrefix(trimmed, "remote.origin.key =") ||
			strings.HasPrefix(trimmed, "promisor =") {
			continue
		}
		kept = append(kept, line)
	}
	body := strings.TrimRight(strings.Join(kept, "\n"), "\n")
	if body != "" {
		body += "\n"
	}
	body += "remote.origin.url = file://" + filepath.Clean(central) + "\n"
	body += "remote.origin.key = " + r.KeyName + "\n"
	body += "promisor = origin\n"
	tmp := cfgPath + ".tmp"
	if err := os.WriteFile(tmp, []byte(body), 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, cfgPath)
}

func currentHead(central string) string {
	entries, err := os.ReadDir(filepath.Join(central, ".veins", "op-heads"))
	if err != nil || len(entries) == 0 {
		return ""
	}
	names := make([]string, 0, len(entries))
	for _, e := range entries {
		names = append(names, e.Name())
	}
	sort.Strings(names)
	return strings.Join(names, ",")
}

func (r *Runner) Invalidate(repoID int64) {
	r.mu.Lock()
	delete(r.fetchAt, repoID)
	delete(r.currentRev, repoID)
	r.mu.Unlock()
}

func (r *Runner) Resolve(ctx context.Context, repoID int64, central, rev string) (string, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return "", err
	}
	return r.resolveLocked(ctx, path, rev)
}

func (r *Runner) resolveLocked(ctx context.Context, browsePath, rev string) (string, error) {
	out, err := r.runOK(ctx, browsePath, nil, "hash", "-rev", rev)
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}

func (r *Runner) CommitHash(ctx context.Context, repoID int64, central, rev string) (string, error) {
	return r.Resolve(ctx, repoID, central, rev)
}

func (r *Runner) Branches(ctx context.Context, repoID int64, central string) ([]Branch, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return nil, err
	}
	if currentHead(central) == "" {
		return nil, nil
	}
	out, _, err := r.run(ctx, path, nil, "bmk", "ls", "-no-col-titles")
	if err != nil {
		if strings.Contains(strings.ToLower(string(out)), "no bookmarks") {
			return nil, nil
		}
		return nil, err
	}
	return ParseBranches(string(out)), nil
}

func (r *Runner) Log(ctx context.Context, repoID int64, central, rev string, max int) ([]Commit, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return nil, err
	}
	args := []string{"log", "-no-col-titles"}
	if rev != "" {
		args = append(args, "-rev", rev)
	}
	out, err := r.runOK(ctx, path, nil, args...)
	if err != nil {
		return nil, err
	}
	return ParseLog(string(out), max), nil
}

func (r *Runner) Show(ctx context.Context, repoID int64, central, rev string) (*CommitDetail, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return nil, err
	}
	out, err := r.runOK(ctx, path, nil, "show", rev)
	if err != nil {
		return nil, err
	}
	d := ParseShow(string(out))
	return &d, nil
}

func (r *Runner) Diff(ctx context.Context, repoID int64, central, from, to string) (string, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return "", err
	}
	out, _, err := r.run(ctx, path, nil, "diff", from, to)
	if err != nil {
		return "", err
	}
	return string(out), nil
}

func (r *Runner) ListFiles(ctx context.Context, repoID int64, central, rev string) ([]string, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return nil, err
	}
	out, err := r.runOK(ctx, path, nil, "ls", "-plain", rev)
	if err != nil {
		return nil, err
	}
	var files []string
	for _, line := range strings.Split(string(out), "\n") {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		files = append(files, line)
	}
	return files, nil
}

func (r *Runner) ReadFile(ctx context.Context, repoID int64, central, rev, rel string, max int64) (*FileData, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return nil, err
	}
	if err := r.checkoutLocked(ctx, repoID, path, rev); err != nil {
		return nil, err
	}
	return safeRead(path, rel, max)
}

func (r *Runner) checkoutLocked(ctx context.Context, repoID int64, path, rev string) error {
	hash, err := r.resolveLocked(ctx, path, rev)
	if err != nil {
		return err
	}
	r.mu.Lock()
	checkedOut := r.currentRev[repoID]
	r.mu.Unlock()
	if checkedOut == hash {
		return nil
	}
	if _, err := r.runOK(ctx, path, nil, "co", hash); err != nil {
		return err
	}
	r.mu.Lock()
	r.currentRev[repoID] = hash
	r.mu.Unlock()
	return nil
}

// FileSizes returns the on-disk size of each tracked file at rev. The caller
// supplies the tracked paths so the tree only has to be listed once.
func (r *Runner) FileSizes(ctx context.Context, repoID int64, central, rev string, files []string) (map[string]int64, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return nil, err
	}
	if err := r.checkoutLocked(ctx, repoID, path, rev); err != nil {
		return nil, err
	}
	sizes := make(map[string]int64, len(files))
	for _, rel := range files {
		info, err := os.Lstat(filepath.Join(path, filepath.FromSlash(rel)))
		if err != nil || !info.Mode().IsRegular() {
			continue
		}
		sizes[rel] = info.Size()
	}
	return sizes, nil
}

func safeRead(root, rel string, max int64) (*FileData, error) {
	rel = filepath.FromSlash(rel)
	clean := filepath.Clean(rel)
	if clean == "." || filepath.IsAbs(clean) || clean == ".." ||
		strings.HasPrefix(clean, ".."+string(filepath.Separator)) ||
		clean == ".veins" || strings.HasPrefix(clean, ".veins"+string(filepath.Separator)) {
		return nil, errors.New("invalid path")
	}
	full := filepath.Join(root, clean)
	if !pathWithin(root, full) {
		return nil, errors.New("invalid path")
	}
	info, err := os.Lstat(full)
	if err != nil {
		return nil, err
	}
	if info.IsDir() {
		return nil, errors.New("path is a directory")
	}
	if info.Mode()&os.ModeSymlink != 0 {
		target, err := os.Readlink(full)
		if err != nil {
			return nil, err
		}
		return &FileData{Data: []byte(target), Size: int64(len(target)), IsSymlink: true, LinkTarget: target, ModTime: info.ModTime()}, nil
	}
	if !info.Mode().IsRegular() {
		return nil, errors.New("not a regular file")
	}
	if info.Size() > max {
		return nil, ErrTooLarge
	}
	f, err := os.Open(full)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	data, err := io.ReadAll(io.LimitReader(f, max+1))
	if err != nil {
		return nil, err
	}
	if int64(len(data)) > max {
		return nil, ErrTooLarge
	}
	return &FileData{Data: data, Size: info.Size(), ModTime: info.ModTime()}, nil
}