github.com/pkumar631/talisman@v0.3.2/talisman.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"strings"
    10  
    11  	log "github.com/Sirupsen/logrus"
    12  	"github.com/thoughtworks/talisman/git_repo"
    13  )
    14  
    15  var (
    16  	fdebug  bool
    17  	githook string
    18  	showVersion bool
    19  	Version string = "Development Build"
    20  )
    21  
    22  const (
    23  	PrePush   = "pre-push"
    24  	PreCommit = "pre-commit"
    25  )
    26  
    27  func init() {
    28  	log.SetOutput(os.Stderr)
    29  }
    30  
    31  type Options struct {
    32  	debug   bool
    33  	githook string
    34  }
    35  
    36  //Logger is the default log device, set to emit at the Error level by default
    37  func main() {
    38  	flag.BoolVar(&fdebug, "debug", false, "enable debug mode (warning: very verbose)")
    39  	flag.BoolVar(&fdebug, "d", false, "short form of debug (warning: very verbose)")
    40  	flag.BoolVar(&showVersion, "v", false, "show current version of talisman" )
    41  	flag.BoolVar(&showVersion, "version", false, "show current version of talisman")
    42  	flag.StringVar(&githook, "githook", PrePush, "either pre-push or pre-commit")
    43  	flag.Parse()
    44  
    45  	if showVersion {
    46  		fmt.Printf("talisman %s\n", Version)
    47  		os.Exit(0)
    48  	}
    49  
    50  	options := Options{
    51  		debug:   fdebug,
    52  		githook: githook,
    53  	}
    54  
    55  	os.Exit(run(os.Stdin, options))
    56  }
    57  
    58  func run(stdin io.Reader, options Options) (returnCode int) {
    59  	if options.debug {
    60  		log.SetLevel(log.DebugLevel)
    61  	} else {
    62  		log.SetLevel(log.ErrorLevel)
    63  	}
    64  
    65  	if options.githook == "" {
    66  		options.githook = PrePush
    67  	}
    68  
    69  	log.Infof("Running %s hook", options.githook)
    70  
    71  	var additions []git_repo.Addition
    72  	if options.githook == PreCommit {
    73  		preCommitHook := NewPreCommitHook()
    74  		additions = preCommitHook.GetRepoAdditions()
    75  	} else {
    76  		prePushHook := NewPrePushHook(readRefAndSha(stdin))
    77  		additions = prePushHook.GetRepoAdditions()
    78  	}
    79  
    80  	return NewRunner(additions).RunWithoutErrors()
    81  }
    82  
    83  func readRefAndSha(file io.Reader) (string, string, string, string) {
    84  	text, _ := bufio.NewReader(file).ReadString('\n')
    85  	refsAndShas := strings.Split(strings.Trim(string(text), "\n"), " ")
    86  	if len(refsAndShas) < 4 {
    87  		return EmptySha, EmptySha, "", ""
    88  	}
    89  	return refsAndShas[0], refsAndShas[1], refsAndShas[2], refsAndShas[3]
    90  }