Files
pipelines/internal/server/chat_tools_diff.go
T

317 lines
11 KiB
Go

package server
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"unicode"
"git.a-wan.net/alan/pipelines/internal/chattools"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// The show_diff bounds. A larger diff is shown partially, never cut silently:
// files past the count are omitted (and counted), and a patch over the per-file
// or total size keeps its entry with a no-patch reason.
const (
showDiffMaxFiles = 300
showDiffMaxFileBytes = 256 << 10
showDiffMaxBytes = 1 << 20
showDiffTimeout = 30 * time.Second
// The empty tree is the base of a repository without commits.
gitEmptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
)
type showDiffRequest struct {
Path string
Base string
Head string
Paths []string
CommittedOnly bool
Title string
}
// showDiffMaxPaths bounds the paths argument.
const showDiffMaxPaths = 50
// showDiffPathspecs turns the model's paths into Git pathspecs confined to the
// repository: each must be relative, without a .. component, option prefix,
// pathspec magic or control character. A path with glob characters matches as
// a glob (":(glob)"), any other literally.
func showDiffPathspecs(paths []string) ([]string, []string, error) {
if len(paths) > showDiffMaxPaths {
return nil, nil, fmt.Errorf("paths has %d entries; the limit is %d", len(paths), showDiffMaxPaths)
}
var specs, kept []string
for _, raw := range paths {
path := strings.TrimSpace(raw)
if path == "" {
continue
}
if len(path) > 500 || strings.HasPrefix(path, "-") || strings.HasPrefix(path, ":") || filepath.IsAbs(path) || strings.HasPrefix(path, "~") {
return nil, nil, fmt.Errorf("paths entry %q must be a path inside the repository, relative to its top", raw)
}
for _, r := range path {
if unicode.IsControl(r) {
return nil, nil, fmt.Errorf("paths entry %q contains a control character", raw)
}
}
for _, part := range strings.Split(filepath.ToSlash(path), "/") {
if part == ".." {
return nil, nil, fmt.Errorf("paths entry %q leaves the repository", raw)
}
}
path = strings.TrimSuffix(filepath.ToSlash(filepath.Clean(path)), "/")
if path == "." {
continue
}
kept = append(kept, path)
if strings.ContainsAny(path, "*?[") {
specs = append(specs, ":(glob)"+path)
} else {
specs = append(specs, ":(literal)"+path)
}
}
return specs, kept, nil
}
// runShowDiff compares a repository inside the operator's home and records
// the per-file patches as one diff item.
func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in showDiffRequest) (*protocol.ChatShownItem, chattools.Result) {
fail := func(err error) (*protocol.ChatShownItem, chattools.Result) {
return nil, chattools.Result{Text: "Nothing was shown: " + err.Error(), IsError: true}
}
base := strings.TrimSpace(in.Base)
if in.CommittedOnly && base == "" {
return fail(errors.New("committed_only needs a base to compare against"))
}
if base != "" && !validGitRevision(base) {
return fail(fmt.Errorf("base %q is not a branch, tag or commit name", base))
}
headName := strings.TrimSpace(in.Head)
if headName != "" && !validGitRevision(headName) {
return fail(fmt.Errorf("head %q is not a branch, tag or commit name", headName))
}
if headName != "" && in.CommittedOnly {
return fail(errors.New("committed_only does not apply with head, which is always committed"))
}
pathspecs, paths, err := showDiffPathspecs(in.Paths)
if err != nil {
return fail(err)
}
directory, err := s.resolveDiffDirectory(ctx, sessionID, in.Path)
if err != nil {
return fail(err)
}
ctx, cancel := context.WithTimeout(ctx, showDiffTimeout)
defer cancel()
git := gitRunner{ctx: ctx, directory: directory}
top, err := git.output("rev-parse", "--show-toplevel")
if err != nil {
return fail(fmt.Errorf("%s is not inside a Git repository", directory))
}
git.directory = strings.TrimSpace(top)
body := protocol.ChatShownDiffBody{Repo: git.directory, Base: base, CommittedOnly: in.CommittedOnly}
head, headErr := git.output("rev-parse", "--verify", "--quiet", "HEAD^{commit}")
head = strings.TrimSpace(head)
if branch, err := git.output("symbolic-ref", "--quiet", "--short", "HEAD"); err == nil {
body.Head = strings.TrimSpace(branch)
} else if head != "" {
body.Head = shortCommit(head)
}
current := head
if headName != "" {
target, err := git.output("rev-parse", "--verify", "--quiet", "--end-of-options", headName+"^{commit}")
if err != nil {
return fail(fmt.Errorf("head %q is not a commit in %s", headName, git.directory))
}
head, headErr = strings.TrimSpace(target), nil
body.Head, body.HeadRevision = headName, headName
}
body.Paths = paths
var compare string
switch {
case headName != "" && base == "":
if current == "" {
return fail(errors.New("this repository has no HEAD commit to compare " + headName + " with; pass base"))
}
compare = current
case base != "":
if headErr != nil || head == "" {
return fail(errors.New("this repository has no commits yet, so there is nothing to compare with " + base))
}
target, err := git.output("rev-parse", "--verify", "--quiet", "--end-of-options", base+"^{commit}")
if err != nil {
return fail(fmt.Errorf("base %q is not a commit in %s", base, git.directory))
}
mergeBase, err := git.output("merge-base", strings.TrimSpace(target), head)
if err != nil {
return fail(fmt.Errorf("%s and HEAD share no history", base))
}
compare = strings.TrimSpace(mergeBase)
case headErr == nil && head != "":
compare = head
default:
compare = gitEmptyTree
}
if compare != gitEmptyTree {
body.BaseCommit = shortCommit(compare)
}
revisions := []string{compare}
worktree := !in.CommittedOnly && headName == ""
if !worktree {
revisions = append(revisions, head)
}
changes, err := collectGitDiff(git, revisions, worktree, pathspecs)
if err != nil {
return fail(err)
}
body.Changes = changes
diffBytes := 0
for _, file := range changes.Files {
added, removed := patchLineCounts(file.Patch)
body.Additions += added
body.Deletions += removed
diffBytes += len(file.Patch)
}
body.Files = len(changes.Files) + changes.Omitted
item := protocol.ChatShownItem{Kind: protocol.ChatShownDiff, Title: in.Title, Diff: &body, DiffBytes: diffBytes}
return &item, chattools.Result{Text: showDiffSummary(body)}
}
func showDiffSummary(body protocol.ChatShownDiffBody) string {
against := "HEAD"
switch {
case body.HeadRevision != "" && body.Base != "":
against = fmt.Sprintf("%s (merge base %s), showing %s", body.Base, body.BaseCommit, body.HeadRevision)
case body.HeadRevision != "":
against = fmt.Sprintf("HEAD (%s), showing %s", body.BaseCommit, body.HeadRevision)
case body.Base != "" && body.CommittedOnly:
against = fmt.Sprintf("%s (merge base %s), committed changes only", body.Base, body.BaseCommit)
case body.Base != "":
against = fmt.Sprintf("%s (merge base %s), including uncommitted work", body.Base, body.BaseCommit)
case body.BaseCommit == "":
against = "an empty repository"
}
if len(body.Paths) > 0 {
against += ", limited to " + strings.Join(body.Paths, ", ")
}
if body.Files == 0 {
return fmt.Sprintf("Shown in the operator's Pipelines chat: no changes in %s against %s.", body.Repo, against)
}
text := fmt.Sprintf("Shown in the operator's Pipelines chat: %d changed %s (+%d -%d) in %s against %s.",
body.Files, plural(body.Files, "file", "files"), body.Additions, body.Deletions, body.Repo, against)
if body.Changes != nil && body.Changes.Status != "complete" {
text += " The diff is partial: " + body.Changes.Diagnostic
}
return text
}
func plural(n int, one, many string) string {
if n == 1 {
return one
}
return many
}
// resolveDiffDirectory applies the home containment of show_file to a
// directory, defaulting to the chat's working directory.
func (s *chatToolService) resolveDiffDirectory(ctx context.Context, sessionID, requested string) (string, error) {
requested = strings.TrimSpace(requested)
home, err := s.home()
if err != nil {
return "", err
}
realHome, err := filepath.EvalSymlinks(filepath.Clean(home))
if err != nil {
return "", errors.New("the operator's home directory is not available")
}
if requested == "" || (!filepath.IsAbs(requested) && !strings.HasPrefix(requested, "~")) {
directory := s.chatSessionDirectory(ctx, sessionID)
if directory == "" {
return "", errors.New("this chat has no recorded working directory; pass the repository's absolute path")
}
requested = filepath.Join(directory, requested)
}
target, err := expandHomePath(filepath.Clean(home), requested)
if err != nil {
return "", err
}
_, realTarget, err := resolveInsideHome(realHome, target)
if err != nil {
if strings.Contains(err.Error(), "outside the home directory") {
return "", errors.New(requested + " is outside the operator's home directory; only repositories inside home can be shown")
}
return "", err
}
info, err := os.Stat(realTarget)
if err != nil {
return "", describePathError(requested, err)
}
if !info.IsDir() {
return "", errors.New(requested + " is not a directory; pass the repository directory")
}
return realTarget, nil
}
// validGitRevision accepts a plain revision name: no option prefix, range,
// whitespace or control character, so it can only name one commit.
func validGitRevision(name string) bool {
if name == "" || len(name) > 200 || strings.HasPrefix(name, "-") || strings.Contains(name, "..") {
return false
}
for _, r := range name {
if unicode.IsSpace(r) || unicode.IsControl(r) {
return false
}
}
return true
}
// gitRunner runs git in one directory with the operator's environment and no
// pager, external diff, text conversion or path quoting.
type gitRunner struct {
ctx context.Context
directory string
}
func (g gitRunner) command(args ...string) *exec.Cmd {
full := append([]string{"-c", "core.quotepath=false", "-c", "core.fsmonitor=false", "-C", g.directory}, args...)
cmd := exec.CommandContext(g.ctx, "git", full...)
cmd.Env = append(workenv.CommandEnv(g.ctx, g.directory), "GIT_PAGER=cat", "GIT_OPTIONAL_LOCKS=0", "LC_ALL=C")
return cmd
}
func (g gitRunner) output(args ...string) (string, error) {
var stdout, stderr bytes.Buffer
cmd := g.command(args...)
cmd.Stdout, cmd.Stderr = &stdout, &stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("git %s: %v: %s", args[0], err, strings.TrimSpace(stderr.String()))
}
return stdout.String(), nil
}
// patch returns one file's patch. A `diff --no-index` exits 1 when the files
// differ, which is its success.
func (g gitRunner) patch(noIndex bool, args ...string) (string, error) {
var stdout, stderr bytes.Buffer
cmd := g.command(args...)
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
var exit *exec.ExitError
if err != nil && !(noIndex && errors.As(err, &exit) && exit.ExitCode() == 1) {
return "", fmt.Errorf("git diff: %v: %s", err, strings.TrimSpace(stderr.String()))
}
return stdout.String(), nil
}