gitdiff

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2023 License: MIT Imports: 16 Imported by: 4

Documentation

Overview

Package gitdiff parses and applies patches generated by Git. It supports line-oriented text patches, binary patches, and can also parse standard unified diffs generated by other tools.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apply

func Apply(dst io.Writer, src io.ReaderAt, f *File) error

Apply is a convenience function that creates an Applier for src with default settings and applies the changes in f, writing the result to dst.

func Parse

func Parse(r io.Reader) (<-chan *File, error)

Parse parses a patch with changes to one or more files. Any content before the first file is returned as the second value. If an error occurs while parsing, it returns all files parsed before the error.

func ParsePatchDate

func ParsePatchDate(s string) (time.Time, error)

ParsePatchDate parses a patch date string. It returns the parsed time or an error if s has an unknown format. ParsePatchDate supports the iso, rfc, short, raw, unix, and default formats (with local variants) used by the --date flag in Git.

Types

type Applier

type Applier struct {
	// contains filtered or unexported fields
}

Applier applies changes described in fragments to source data. If changes are described in multiple fragments, those fragments must be applied in order, usually by calling ApplyFile.

By default, Applier operates in "strict" mode, where fragment content and positions must exactly match those of the source.

If an error occurs while applying, methods on Applier return instances of *ApplyError that annotate the wrapped error with additional information when available. If the error is because of a conflict between a fragment and the source, the wrapped error will be a *Conflict.

While an Applier can apply both text and binary fragments, only one fragment type can be used without resetting the Applier. The first fragment applied sets the type for the Applier. Mixing fragment types or mixing fragment-level and file-level applies results in an error.

func NewApplier

func NewApplier(src io.ReaderAt) *Applier

NewApplier creates an Applier that reads data from src. If src is a LineReaderAt, it is used directly to apply text fragments.

func (*Applier) ApplyBinaryFragment

func (a *Applier) ApplyBinaryFragment(dst io.Writer, f *BinaryFragment) error

ApplyBinaryFragment applies the changes in the fragment f and writes the result to dst. At most one binary fragment can be applied before a call to Reset.

func (*Applier) ApplyFile

func (a *Applier) ApplyFile(dst io.Writer, f *File) error

ApplyFile applies the changes in all of the fragments of f and writes the result to dst.

func (*Applier) ApplyTextFragment

func (a *Applier) ApplyTextFragment(dst io.Writer, f *TextFragment) error

ApplyTextFragment applies the changes in the fragment f and writes unwritten data before the start of the fragment and the result to dst. If multiple text fragments apply to the same source, ApplyTextFragment must be called in order of increasing start position. As a result, each fragment can be applied at most once before a call to Reset.

func (*Applier) Flush

func (a *Applier) Flush(dst io.Writer) (err error)

Flush writes any data following the last applied fragment to dst.

func (*Applier) Reset

func (a *Applier) Reset(src io.ReaderAt)

Reset resets the input and internal state of the Applier. If src is nil, the existing source is reused.

type ApplyError

type ApplyError struct {
	// Line is the one-indexed line number in the source data
	Line int64
	// Fragment is the one-indexed fragment number in the file
	Fragment int
	// FragmentLine is the one-indexed line number in the fragment
	FragmentLine int
	// contains filtered or unexported fields
}

ApplyError wraps an error that occurs during patch application with additional location information, if it is available.

func (*ApplyError) Error

func (e *ApplyError) Error() string

func (*ApplyError) Unwrap

func (e *ApplyError) Unwrap() error

Unwrap returns the wrapped error.

type BinaryFragment

type BinaryFragment struct {
	Method BinaryPatchMethod
	Size   int64
	Data   []byte
}

BinaryFragment describes changes to a binary file.

type BinaryPatchMethod

type BinaryPatchMethod int

BinaryPatchMethod is the method used to create and apply the binary patch.

const (
	// BinaryPatchDelta indicates the data uses Git's packfile encoding
	BinaryPatchDelta BinaryPatchMethod = iota
	// BinaryPatchLiteral indicates the data is the exact file content
	BinaryPatchLiteral
)

type Conflict

type Conflict struct {
	// contains filtered or unexported fields
}

Conflict indicates an apply failed due to a conflict between the patch and the source content.

Users can test if an error was caused by a conflict by using errors.Is with an empty Conflict:

    if errors.Is(err, &Conflict{}) {
	       // handle conflict
    }

func (*Conflict) Error

func (c *Conflict) Error() string

func (*Conflict) Is

func (c *Conflict) Is(other error) bool

Is implements error matching for Conflict. Passing an empty instance of Conflict always returns true.

type File

type File struct {
	OldName string
	NewName string

	IsNew    bool
	IsDelete bool
	IsCopy   bool
	IsRename bool

	OldMode os.FileMode
	NewMode os.FileMode

	OldOIDPrefix string
	NewOIDPrefix string
	Score        int

	PatchHeader *PatchHeader

	// TextFragments contains the fragments describing changes to a text file. It
	// may be empty if the file is empty or if only the mode changes.
	TextFragments []*TextFragment

	// IsBinary is true if the file is a binary file. If the patch includes
	// binary data, BinaryFragment will be non-nil and describe the changes to
	// the data. If the patch is reversible, ReverseBinaryFragment will also be
	// non-nil and describe the changes needed to restore the original file
	// after applying the changes in BinaryFragment.
	IsBinary              bool
	BinaryFragment        *BinaryFragment
	ReverseBinaryFragment *BinaryFragment
}

File describes changes to a single file. It can be either a text file or a binary file.

type Line

type Line struct {
	Op   LineOp
	Line string
}

Line is a line in a text fragment.

func (Line) New

func (fl Line) New() bool

New returns true if the line appears in the new content of the fragment.

func (Line) NoEOL

func (fl Line) NoEOL() bool

NoEOL returns true if the line is missing a trailing newline character.

func (Line) Old

func (fl Line) Old() bool

Old returns true if the line appears in the old content of the fragment.

func (Line) String

func (fl Line) String() string

type LineOp

type LineOp int

LineOp describes the type of a text fragment line: context, added, or removed.

const (
	// OpContext indicates a context line
	OpContext LineOp = iota
	// OpDelete indicates a deleted line
	OpDelete
	// OpAdd indicates an added line
	OpAdd
)

func (LineOp) String

func (op LineOp) String() string

type LineReaderAt

type LineReaderAt interface {
	ReadLinesAt(lines [][]byte, offset int64) (n int, err error)
}

LineReaderAt is the interface that wraps the ReadLinesAt method.

ReadLinesAt reads len(lines) into lines starting at line offset. It returns the number of lines read (0 <= n <= len(lines)) and any error encountered. Line numbers are zero-indexed.

If n < len(lines), ReadLinesAt returns a non-nil error explaining why more lines were not returned.

Lines read by ReadLinesAt include the newline character. The last line does not have a final newline character if the input ends without one.

type PatchHeader

type PatchHeader struct {
	// The SHA of the commit the patch was generated from. Empty if the SHA is
	// not included in the header.
	SHA string

	// The author details of the patch. If these details are not included in
	// the header, Author is nil and AuthorDate is the zero time.
	Author     *PatchIdentity
	AuthorDate time.Time

	// The committer details of the patch. If these details are not included in
	// the header, Committer is nil and CommitterDate is the zero time.
	Committer     *PatchIdentity
	CommitterDate time.Time

	// The title and body of the commit message describing the changes in the
	// patch. Empty if no message is included in the header.
	Title string
	Body  string

	// If the preamble looks like an email, ParsePatchHeader will
	// remove prefixes such as `Re: ` and `[PATCH v3 5/17]` from the
	// Title and place them here.
	SubjectPrefix string

	// If the preamble looks like an email, and it contains a `---`
	// line, that line will be removed and everything after it will be
	// placed in BodyAppendix.
	BodyAppendix string
}

PatchHeader is a parsed version of the preamble content that appears before the first diff in a patch. It includes metadata about the patch, such as the author and a subject.

func ParsePatchHeader

func ParsePatchHeader(s string) (*PatchHeader, error)

ParsePatchHeader parses a preamble string as returned by Parse into a PatchHeader. Due to the variety of header formats, some fields of the parsed PatchHeader may be unset after parsing.

Supported formats are the short, medium, full, fuller, and email pretty formats used by git diff, git log, and git show and the UNIX mailbox format used by git format-patch.

If ParsePatchHeader detects that it is handling an email, it will remove extra content at the beginning of the title line, such as `[PATCH]` or `Re:` in the same way that `git mailinfo` does. SubjectPrefix will be set to the value of this removed string. (`git mailinfo` is the core part of `git am` that pulls information out of an individual mail.)

Additionally, if ParsePatchHeader detects that it's handling an email, it will remove a `---` line and put anything after it into BodyAppendix.

Those wishing the effect of a plain `git am` should use `PatchHeader.Title + "\n" + PatchHeader.Body` (or `PatchHeader.Message()`). Those wishing to retain the subject prefix and appendix material should use `PatchHeader.SubjectPrefix + PatchHeader.Title + "\n" + PatchHeader.Body + "\n" + PatchHeader.BodyAppendix`.

func (*PatchHeader) Message

func (h *PatchHeader) Message() string

Message returns the commit message for the header. The message consists of the title and the body separated by an empty line.

type PatchIdentity

type PatchIdentity struct {
	Name  string
	Email string
}

PatchIdentity identifies a person who authored or committed a patch.

func ParsePatchIdentity

func ParsePatchIdentity(s string) (PatchIdentity, error)

ParsePatchIdentity parses a patch identity string. A valid string contains a name followed by an email address in angle brackets. ParsePatchIdentity does not require that the email address is valid or properly formatted. The name must not contain a left angle bracket, '<', and the email address must not contain a right angle bracket, '>'.

func (PatchIdentity) String

func (i PatchIdentity) String() string

type TextFragment

type TextFragment struct {
	Comment string

	OldPosition int64
	OldLines    int64

	NewPosition int64
	NewLines    int64

	LinesAdded   int64
	LinesDeleted int64

	LeadingContext  int64
	TrailingContext int64

	Lines []Line
}

TextFragment describes changed lines starting at a specific line in a text file.

func (*TextFragment) Header

func (f *TextFragment) Header() string

Header returns the canonical header of this fragment.

func (*TextFragment) Raw added in v0.7.1

func (f *TextFragment) Raw(op LineOp) string

func (*TextFragment) Validate

func (f *TextFragment) Validate() error

Validate checks that the fragment is self-consistent and appliable. Validate returns an error if and only if the fragment is invalid.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL