github.com/anishathalye/periscope@v0.3.5/internal/periscope/info.go (about)

     1  package periscope
     2  
     3  import (
     4  	"github.com/anishathalye/periscope/internal/herror"
     5  
     6  	"encoding/hex"
     7  	"fmt"
     8  	"path/filepath"
     9  	"text/tabwriter"
    10  )
    11  
    12  type InfoOptions struct {
    13  	Relative bool
    14  }
    15  
    16  func (ps *Periscope) Info(paths []string, options *InfoOptions) herror.Interface {
    17  	var herr herror.Interface
    18  	for i, p := range paths {
    19  		if i > 0 {
    20  			fmt.Fprintf(ps.outStream, "\n")
    21  		}
    22  		err := ps.info1(p, options)
    23  		if err != nil {
    24  			herr = err
    25  		}
    26  		if herr != nil && !herror.IsSilent(herr) {
    27  			return herr
    28  		}
    29  	}
    30  	return herr
    31  }
    32  
    33  func (ps *Periscope) info1(path string, options *InfoOptions) herror.Interface {
    34  	absPath, _, err := ps.checkFile(path, true, false, "show", false, false)
    35  	if err != nil {
    36  		return err
    37  	}
    38  	dupeSet, herr := ps.db.Lookup(absPath)
    39  	if herr != nil {
    40  		return herr
    41  	}
    42  	nCopies := len(dupeSet)
    43  	nDupes := 0
    44  	if nCopies > 1 {
    45  		nDupes = nCopies - 1
    46  	}
    47  	fmt.Fprintf(ps.outStream, "%s\n", path)
    48  	w := tabwriter.NewWriter(ps.outStream, 0, 0, 0, ' ', tabwriter.DiscardEmptyColumns|tabwriter.AlignRight)
    49  	if len(dupeSet) > 0 {
    50  		info := dupeSet[0]
    51  		if info.ShortHash != nil {
    52  			fmt.Fprintf(w, "  short hash:\v %s\n", hex.EncodeToString(info.ShortHash))
    53  		}
    54  		if info.FullHash != nil {
    55  			fmt.Fprintf(w, "  full hash:\v %s\n", hex.EncodeToString(info.FullHash))
    56  		}
    57  	}
    58  	if nDupes > 0 {
    59  		fmt.Fprintf(w, "  duplicates:\v %d\n", nDupes)
    60  	}
    61  	w.Flush()
    62  	if nDupes > 0 {
    63  		dirPath := filepath.Dir(absPath)
    64  		for _, info := range dupeSet {
    65  			if info.Path != absPath {
    66  				showPath := info.Path
    67  				if options.Relative {
    68  					showPath = relPath(dirPath, info.Path)
    69  				}
    70  				fmt.Fprintf(ps.outStream, "    %s\n", showPath)
    71  			}
    72  		}
    73  	}
    74  	return nil
    75  }