github.com/driusan/dgit@v0.0.0-20221118233547-f39f0c15edbb/git/diff.go (about)

     1  package git
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"strconv"
     8  )
     9  
    10  // Describes the options that may be specified on the command line for
    11  // "git diff".
    12  type DiffOptions struct {
    13  	DiffCommonOptions
    14  
    15  	Staged bool
    16  
    17  	NoIndex bool
    18  }
    19  
    20  // DiffFiles implements the git diff-files command.
    21  // It compares the file system to the index.
    22  func Diff(c *Client, opt DiffOptions, paths []File) ([]HashDiff, error) {
    23  	if opt.NoIndex {
    24  		if len(paths) != 2 {
    25  			return nil, fmt.Errorf("Must provide 2 paths for git diff --no-index")
    26  		}
    27  
    28  		// Just invoke the system diff command, we can't return a HashDiff
    29  		// since we're not working things that are tracked by the repo.
    30  		// we just directly invoke diff if --no-index is specified.
    31  		diffcmd := exec.Command(posixDiff, "-U", strconv.Itoa(opt.NumContextLines), paths[0].String(), paths[1].String())
    32  		diffcmd.Stderr = os.Stderr
    33  		diffcmd.Stdout = os.Stdout
    34  
    35  		if err := diffcmd.Run(); err != nil {
    36  			return nil, err
    37  		}
    38  		return nil, nil
    39  	}
    40  	if err := refreshIndex(c); err != nil {
    41  		return nil, err
    42  	}
    43  	if opt.Staged {
    44  		head, err := c.GetHeadCommit()
    45  		if err != nil {
    46  			return nil, err
    47  		}
    48  		index, _ := c.GitDir.ReadIndex()
    49  		return DiffIndex(c,
    50  			DiffIndexOptions{
    51  				DiffCommonOptions: opt.DiffCommonOptions,
    52  				Cached:            true,
    53  			},
    54  			index,
    55  			head,
    56  			paths)
    57  	}
    58  	return DiffFiles(c,
    59  		DiffFilesOptions{
    60  			DiffCommonOptions: opt.DiffCommonOptions,
    61  		},
    62  		paths)
    63  }