github.com/BenLubar/git-last-modified@v0.1.1-0.20210215221858-9b8031919630/modtime.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  func getModTime(path string) (time.Time, error) {
    14  	pretty := "--pretty=format:%aI"
    15  	if *flagCommit {
    16  		pretty = "--pretty=format:%cI"
    17  	}
    18  
    19  	/* #nosec G204 */
    20  	cmd := exec.Command("git", "log", "-n", "1", pretty, "--", path)
    21  	cmd.Stderr = os.Stderr
    22  
    23  	b, err := cmd.Output()
    24  	if err != nil {
    25  		return time.Time{}, errors.Wrapf(err, "get last-modified time for file %q", path)
    26  	}
    27  
    28  	s := strings.TrimSpace(string(b))
    29  	if s == "" {
    30  		return time.Time{}, nil
    31  	}
    32  
    33  	t, err := time.Parse(time.RFC3339, s)
    34  	return t, errors.Wrapf(err, "cannot parse time %q for file %q", s, path)
    35  }
    36  
    37  func setModTime(path string) error {
    38  	t, err := getModTime(path)
    39  	if err != nil {
    40  		return err
    41  	}
    42  
    43  	if t.IsZero() {
    44  		if *flagVerbose {
    45  			fmt.Printf("%s: never committed in Git\n", path)
    46  		}
    47  
    48  		if !*flagQuiet {
    49  			return errors.Errorf("file not found in Git history: %q", path)
    50  		}
    51  
    52  		// Never committed in Git. Leave it alone.
    53  		return nil
    54  	}
    55  
    56  	if *flagVerbose {
    57  		fmt.Printf("%s: last modified %v\n", path, t)
    58  	}
    59  
    60  	if *flagDryRun {
    61  		return nil
    62  	}
    63  
    64  	return errors.Wrapf(os.Chtimes(path, t, t), "cannot change time for file %q", path)
    65  }