package git import ( "bytes" "context" "errors" "fmt" "io" "strings" ) const resolvedUnitsBytesMax = 16 * 1024 * 1024 // SelectionOutputExtentError reports that resolving one requested range // produced more commit metadata than Thresh can retain. type SelectionOutputExtentError struct { cause CommandOutputExtentError } // Error implements error. func (extentError SelectionOutputExtentError) Error() string { return "git: selected range contains too much commit metadata" } // Unwrap retains the command-output extent that caused selection to stop. func (extentError SelectionOutputExtentError) Unwrap() error { return extentError.cause } // SelectionOutputBytes returns the range metadata observed before aborting. func (extentError SelectionOutputExtentError) SelectionOutputBytes() int { return extentError.cause.CommandOutputBytes() } // SelectionOutputLimitBytes returns the fixed range-metadata bound. func (extentError SelectionOutputExtentError) SelectionOutputLimitBytes() int { return extentError.cause.CommandOutputLimitBytes() } // ResolvedUnit identifies one exact, single-parent Git comparison unit. type ResolvedUnit struct { CommitID string BaseCommit string HeadCommit string Description string } // ResolveUnits resolves one commit or directional range into an oldest-first // linear sequence. Merge commits and ambiguous histories are rejected. func (repository Repository) ResolveUnits(ctx context.Context, selection string) ([]ResolvedUnit, error) { if ctx == nil { return nil, errors.New("git: context is required") } if err := repository.validate(); err != nil { return nil, err } if selection == "" || strings.TrimSpace(selection) != selection || strings.ContainsRune(selection, 0) { return nil, errors.New("git: revision selection is invalid") } left, right, rangeKind, err := parseRevisionSelection(selection) if err != nil { return nil, err } if rangeKind == 0 { head, resolveErr := repository.resolveCommit(ctx, selection) if resolveErr != nil { return nil, resolveErr } return repository.resolveSingleUnit(ctx, head) } leftCommit, err := repository.resolveCommit(ctx, left) if err != nil { return nil, fmt.Errorf("git: resolving left range endpoint: %w", err) } rightCommit, err := repository.resolveCommit(ctx, right) if err != nil { return nil, fmt.Errorf("git: resolving right range endpoint: %w", err) } base := leftCommit if rangeKind == 3 { base, err = repository.uniqueMergeBase(ctx, leftCommit, rightCommit) if err != nil { return nil, err } } else if err := repository.requireAncestor(ctx, leftCommit, rightCommit); err != nil { return nil, err } return repository.resolveLinearRange(ctx, base, rightCommit) } func parseRevisionSelection(selection string) (string, string, uint8, error) { if strings.Count(selection, "...") > 1 { return "", "", 0, errors.New("git: selection contains multiple triple-dot ranges") } if left, right, found := strings.Cut(selection, "..."); found { if left == "" || right == "" || strings.Contains(left, "..") || strings.Contains(right, "..") { return "", "", 0, errors.New("git: triple-dot range requires two revisions") } return left, right, 3, nil } if strings.Count(selection, "..") > 1 { return "", "", 0, errors.New("git: selection contains multiple double-dot ranges") } if left, right, found := strings.Cut(selection, ".."); found { if left == "" || right == "" { return "", "", 0, errors.New("git: double-dot range requires two revisions") } return left, right, 2, nil } return selection, "", 0, nil } func (repository Repository) resolveCommit(ctx context.Context, revision string) (string, error) { if err := repository.rejectAmbiguousShortRef(ctx, revision); err != nil { return "", err } output, err := repository.run( ctx, 256, "rev-parse", "--verify", "--end-of-options", revision+"^{commit}", ) if err != nil { return "", fmt.Errorf("git: revision %q does not resolve to one commit: %w", revision, err) } commit := strings.TrimSuffix(string(output), "\n") if !validObjectID(commit) || bytes.Count(output, []byte{'\n'}) != 1 { return "", errors.New("git: resolved commit output is malformed") } return commit, nil } func (repository Repository) rejectAmbiguousShortRef(ctx context.Context, revision string) error { if strings.HasPrefix(revision, "refs/") || strings.ContainsAny(revision, "~^:") || strings.Contains(revision, "@{") { return nil } branch := repository.refExists(ctx, "refs/heads/"+revision) tag := repository.refExists(ctx, "refs/tags/"+revision) if branch && tag { return fmt.Errorf( "git: revision %q matches both a branch and tag; use the full ref name", revision, ) } return nil } func (repository Repository) refExists(ctx context.Context, reference string) bool { command := []string{"show-ref", "--verify", "--quiet", reference} return repository.write(ctx, nil, nil, io.Discard, command...) == nil } func (repository Repository) resolveSingleUnit(ctx context.Context, head string) ([]ResolvedUnit, error) { output, err := repository.run(ctx, 512, "rev-list", "--parents", "-n", "1", head) if err != nil { return nil, fmt.Errorf("git: resolving commit parent: %w", err) } fields := strings.Fields(string(output)) if len(fields) > 2 { return nil, fmt.Errorf("git: selected commit %s is a merge with %d parents", head, len(fields)-1) } if len(fields) == 0 || fields[0] != head { return nil, errors.New("git: selected commit parent output is malformed") } base := "" if len(fields) == 2 { base = fields[1] } else { base, err = repository.emptyTreeID(ctx) if err != nil { return nil, err } } description, err := repository.commitDescription(ctx, head) if err != nil { return nil, err } return []ResolvedUnit{{CommitID: head, BaseCommit: base, HeadCommit: head, Description: description}}, nil } func (repository Repository) resolveLinearRange( ctx context.Context, base string, head string, ) ([]ResolvedUnit, error) { output, err := repository.run( ctx, resolvedUnitsBytesMax, "rev-list", "--reverse", "--topo-order", "--parents", head, "^"+base, ) if err != nil { if extentError, ok := errors.AsType[CommandOutputExtentError](err); ok { return nil, SelectionOutputExtentError{cause: extentError} } return nil, fmt.Errorf("git: resolving linear range: %w", err) } lines := bytes.Split(bytes.TrimSuffix(output, []byte{'\n'}), []byte{'\n'}) if len(lines) == 1 && len(lines[0]) == 0 { return nil, fmt.Errorf("%w: selected range contains no commits", ErrNoChanges) } units := make([]ResolvedUnit, 0, len(lines)) previous := base for index, line := range lines { commit, parent, parseErr := parseLinearRangeCommit(line, index, previous) if parseErr != nil { return nil, parseErr } description, descriptionErr := repository.commitDescription(ctx, commit) if descriptionErr != nil { return nil, descriptionErr } units = append(units, ResolvedUnit{ CommitID: commit, BaseCommit: parent, HeadCommit: commit, Description: description, }) previous = commit } if previous != head { return nil, errors.New("git: selected range does not terminate at its right endpoint") } return units, nil } func parseLinearRangeCommit(line []byte, index int, previous string) (string, string, error) { fields := strings.Fields(string(line)) if len(fields) > 2 && validObjectID(fields[0]) { return "", "", fmt.Errorf("git: selected range includes merge commit %s", fields[0]) } if len(fields) != 2 || !validObjectID(fields[0]) || !validObjectID(fields[1]) { return "", "", fmt.Errorf("git: range unit %d is malformed", index+1) } if fields[1] != previous { return "", "", fmt.Errorf("git: selected range is nonlinear at commit %s", fields[0]) } return fields[0], fields[1], nil } func (repository Repository) requireAncestor(ctx context.Context, base, head string) error { err := repository.write(ctx, nil, nil, io.Discard, "merge-base", "--is-ancestor", base, head) if err != nil { if ctxErr := ctx.Err(); ctxErr != nil { return ctxErr } return errors.New("git: double-dot left endpoint is not an ancestor of the right endpoint; use triple-dot") } return nil } func (repository Repository) uniqueMergeBase(ctx context.Context, left, right string) (string, error) { output, err := repository.run(ctx, 512, "merge-base", "--all", left, right) if err != nil { return "", fmt.Errorf("git: finding merge base: %w", err) } fields := strings.Fields(string(output)) if len(fields) != 1 || !validObjectID(fields[0]) { return "", errors.New("git: triple-dot range requires exactly one merge base") } return fields[0], nil } func (repository Repository) emptyTreeID(ctx context.Context) (string, error) { output := newBoundedBuffer(256) if err := repository.write( ctx, nil, bytes.NewReader(nil), &output, "hash-object", "-t", "tree", "--stdin", ); err != nil { return "", fmt.Errorf("git: deriving empty tree: %w", err) } objectID := strings.TrimSuffix(output.buffer.String(), "\n") if !validObjectID(objectID) { return "", errors.New("git: empty tree identity is malformed") } return objectID, nil } func (repository Repository) commitDescription(ctx context.Context, commit string) (string, error) { output, err := repository.run(ctx, 1024*1024, "show", "-s", "--format=%s%x00", commit) if err != nil { return "", fmt.Errorf("git: reading commit description: %w", err) } if len(output) < 2 || output[len(output)-2] != 0 || output[len(output)-1] != '\n' || bytes.Count(output, []byte{0}) != 1 { return "", errors.New("git: commit description output is malformed") } return string(output[:len(output)-2]), nil } func validObjectID(value string) bool { if len(value) != 40 && len(value) != 64 { return false } for _, character := range []byte(value) { if (character < '0' || character > '9') && (character < 'a' || character > 'f') { return false } } return true }