github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/cmd/uptodate/uptodate.go (about)

     1  // Copyright 2018 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  // uptodate efficiently computes whether an output file is up-to-date with
    12  // regard to its input files.
    13  package main
    14  
    15  import (
    16  	"fmt"
    17  	"io/ioutil"
    18  	"log"
    19  	"os"
    20  
    21  	"github.com/MichaelTJones/walk"
    22  	"github.com/spf13/pflag"
    23  )
    24  
    25  var debug = pflag.BoolP("debug", "d", false, "debug mode")
    26  
    27  func die(err error) {
    28  	fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
    29  	os.Exit(2)
    30  }
    31  
    32  func main() {
    33  	pflag.Usage = func() {
    34  		fmt.Fprintf(os.Stderr, "usage: %s [-d] OUTPUT INPUT...\n", os.Args[0])
    35  	}
    36  	pflag.Parse()
    37  	if pflag.NArg() < 2 {
    38  		pflag.Usage()
    39  		os.Exit(1)
    40  	}
    41  	if !*debug {
    42  		log.SetOutput(ioutil.Discard)
    43  	}
    44  	output, inputs := pflag.Arg(0), pflag.Args()[1:]
    45  
    46  	fi, err := os.Stat(output)
    47  	if os.IsNotExist(err) {
    48  		log.Printf("output %q is missing", output)
    49  		os.Exit(1)
    50  	} else if err != nil {
    51  		die(err)
    52  	}
    53  	outputModTime := fi.ModTime()
    54  
    55  	for _, input := range inputs {
    56  		err = walk.Walk(input, func(path string, fi os.FileInfo, err error) error {
    57  			if err != nil {
    58  				return err
    59  			}
    60  			if fi.IsDir() {
    61  				return nil
    62  			}
    63  			if !fi.ModTime().Before(outputModTime) {
    64  				log.Printf("input %q (mtime %s) not older than output %q (mtime %s)",
    65  					path, fi.ModTime(), output, outputModTime)
    66  				os.Exit(1)
    67  			}
    68  			return nil
    69  		})
    70  		if err != nil {
    71  			die(err)
    72  		}
    73  	}
    74  	log.Printf("all inputs older than output %q (mtime %s)\n", output, outputModTime)
    75  	os.Exit(0)
    76  }