navid/veinsforge / 7e2b5acc78090b2b76a5dca0e0f8c9645baf3c2e4a649e84f02371471b9e9ccd / internal/vn/browse.go

browse.go

← internal/vn · 12882 bytes · raw · download

package vn

import (
	"context"
	"errors"
	"fmt"
	"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) initBrowseLocked(ctx context.Context, path, central string) error {
	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
		return err
	}
	if !r.RepoExists(path) {
		if _, err := os.Stat(path); err == nil {
			if err := os.RemoveAll(path); err != nil {
				return err
			}
		}
		args := []string{"clone", "file://" + filepath.Clean(central), path}
		if r.KeyName != "" {
			args = append(args, "-key:"+r.KeyName)
		}
		if _, err := r.runOK(ctx, filepath.Dir(path), nil, args...); err != nil {
			return err
		}
		_ = os.Chmod(path, 0o700)
	}
	return r.ensureRemoteConfig(path, central)
}

func (r *Runner) fetchBrowseLocked(ctx context.Context, path, central string) (string, error) {
	_, errOut, err := r.runLong(ctx, path, nil, "fetch", "origin")
	if err != nil {
		return string(errOut), err
	}
	if err := r.syncBrowseBookmarksLocked(ctx, path, central); err != nil {
		return err.Error(), err
	}
	return "", nil
}

// syncBrowseBookmarksLocked advances the cache's bookmarks to the served
// repository's current targets. `vn fetch` only updates remote refs, so a
// read-only cache would otherwise serve the revision it was cloned at forever.
func (r *Runner) syncBrowseBookmarksLocked(ctx context.Context, path, central string) error {
	centralOut, err := r.runOK(ctx, central, nil, "bmk", "ls", "-no-col-titles")
	if err != nil {
		if isNoOperationState(err) {
			return nil
		}
		return fmt.Errorf("list served bookmarks: %w", err)
	}
	served := ParseBranches(string(centralOut))
	if len(served) == 0 {
		return nil
	}
	localOut, err := r.runOK(ctx, path, nil, "bmk", "ls", "-no-col-titles")
	if err != nil {
		if isNoOperationState(err) {
			return nil
		}
		return fmt.Errorf("list cached bookmarks: %w", err)
	}
	localHashes := make(map[string]string)
	for _, b := range ParseBranches(string(localOut)) {
		localHashes[b.Name] = b.Hash
	}
	for _, b := range served {
		if localHashes[b.Name] == b.Hash {
			continue
		}
		if _, err := r.runOK(ctx, path, nil, "bmk", "set", b.Name, "origin/"+b.Name); err != nil {
			return fmt.Errorf("update cached bookmark %s: %w", b.Name, err)
		}
	}
	return nil
}

func isNoOperationState(err error) bool {
	return strings.Contains(strings.ToLower(err.Error()), "no operation state")
}

func (r *Runner) rebuildBrowseLocked(ctx context.Context, repoID int64, path, central string) error {
	if err := os.RemoveAll(path); err != nil {
		return err
	}
	if err := r.initBrowseLocked(ctx, path, central); err != nil {
		return err
	}
	r.mu.Lock()
	delete(r.currentRev, repoID)
	delete(r.fetchHead, repoID)
	r.mu.Unlock()
	return nil
}

func (r *Runner) ensureBrowseLocked(ctx context.Context, repoID int64, central string) (string, error) {
	path := r.BrowsePath(repoID)
	if err := r.initBrowseLocked(ctx, 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
	}
	errOut, err := r.fetchBrowseLocked(ctx, path, central)
	if err != nil {
		if r.Logger != nil {
			r.Logger.Printf("vn fetch for repo %d failed: %v: %s", repoID, err, truncate(errOut, 1024))
		}
		// A cache left behind by an interrupted fetch or with stale remote
		// configuration cannot recover by retrying alone. Rebuild it once.
		if rebuildErr := r.rebuildBrowseLocked(ctx, repoID, path, central); rebuildErr != nil {
			if r.Logger != nil {
				r.Logger.Printf("rebuild browse cache for repo %d failed: %v", repoID, rebuildErr)
			}
		} else {
			errOut, err = r.fetchBrowseLocked(ctx, path, central)
			if err != nil && r.Logger != nil {
				r.Logger.Printf("vn fetch for rebuilt repo %d failed: %v: %s", repoID, err, truncate(errOut, 1024))
			}
		}
	}
	r.mu.Lock()
	r.fetchAt[repoID] = time.Now()
	if err == nil {
		r.fetchHead[repoID] = head
	} else {
		delete(r.fetchHead, repoID)
	}
	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 strings.Contains(strings.ToLower(string(out)), "no bookmarks") {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return ParseBranches(string(out)), nil
}

func (r *Runner) Tags(ctx context.Context, repoID int64, central string) ([]Tag, 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, "tag", "ls", "-no-col-titles")
	if strings.Contains(strings.ToLower(string(out)), "no tags") {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return ParseTags(string(out)), nil
}

func (r *Runner) LatestTag(ctx context.Context, repoID int64, central string) (string, error) {
	lock := r.repoLock(central)
	lock.Lock()
	defer lock.Unlock()
	path, err := r.ensureBrowseLocked(ctx, repoID, central)
	if err != nil {
		return "", err
	}
	if currentHead(central) == "" {
		return "", nil
	}
	out, err := r.runOK(ctx, path, nil, "tag", "latest")
	if err != nil {
		if strings.Contains(strings.ToLower(err.Error()), "no tags") {
			return "", nil
		}
		return "", err
	}
	return strings.TrimSpace(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
}