github.com/knoebber/dotfile@v1.0.6/cli/diff.go (about)

     1  package cli
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/hexops/gotextdiff"
     6  	"github.com/knoebber/dotfile/dotfile"
     7  	"gopkg.in/alecthomas/kingpin.v2"
     8  )
     9  
    10  // TODO commitHash should match on first 7 characters as well.
    11  // Same for checkout
    12  type diffCommand struct {
    13  	alias      string
    14  	commitHash string
    15  }
    16  
    17  func (d *diffCommand) run(*kingpin.ParseContext) error {
    18  	s, err := loadFile(d.alias)
    19  	if err != nil {
    20  		return err
    21  	}
    22  
    23  	if d.commitHash == "" {
    24  		d.commitHash = s.FileData.Revision
    25  	}
    26  
    27  	to := d.commitHash
    28  	if to == "" {
    29  		to = "*"
    30  	}
    31  	fmt.Printf("\033[1mdiff %s %s\033[0m\n", s.FileData.Path, to)
    32  
    33  	unified, err := dotfile.Diff(s, d.commitHash, "")
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	for _, hunk := range unified.Hunks {
    39  		if len(unified.Hunks) > 1 {
    40  			fmt.Println("\033[1m==HUNK==\033[0m")
    41  		}
    42  		for _, line := range hunk.Lines {
    43  			text := line.Content
    44  
    45  			switch line.Kind {
    46  			case gotextdiff.Insert:
    47  				fmt.Print("\x1b[32m")
    48  				fmt.Print(text)
    49  				fmt.Print("\x1b[0m")
    50  			case gotextdiff.Delete:
    51  				fmt.Print("\x1b[31m")
    52  				fmt.Print(text)
    53  				fmt.Print("\x1b[0m")
    54  			case gotextdiff.Equal:
    55  				fmt.Print(text)
    56  			}
    57  		}
    58  	}
    59  
    60  	return nil
    61  }
    62  
    63  func addDiffSubCommandToApplication(app *kingpin.Application) {
    64  	dc := new(diffCommand)
    65  	c := app.Command("diff", "check changes to tracked file").Action(dc.run)
    66  	c.Arg("alias", "file to check changes in").
    67  		HintAction(flags.defaultAliasList).
    68  		Required().
    69  		StringVar(&dc.alias)
    70  	c.Arg("commit-hash",
    71  		"the revision to diff against; default current").
    72  		StringVar(&dc.commitHash)
    73  
    74  }