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

     1  package main
     2  
     3  import (
     4  	"os"
     5  
     6  	log "github.com/Sirupsen/logrus"
     7  	"github.com/thoughtworks/talisman/git_repo"
     8  )
     9  
    10  const (
    11  	//EmptySha represents the state of a brand new ref
    12  	EmptySha string = "0000000000000000000000000000000000000000"
    13  	//ShaId of the empty tree in Git
    14  	EmptyTreeSha string = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
    15  )
    16  
    17  type PrePushHook struct {
    18  	localRef, localCommit, remoteRef, remoteCommit string
    19  }
    20  
    21  func NewPrePushHook(localRef, localCommit, remoteRef, remoteCommit string) *PrePushHook {
    22  	return &PrePushHook{localRef, localCommit, remoteRef, remoteCommit}
    23  }
    24  
    25  //If the outgoing ref does not exist on the remote, all commits on the local ref will be checked
    26  //If the outgoing ref already exists, all additions in the range between "localSha" and "remoteSha" will be validated
    27  func (p *PrePushHook) GetRepoAdditions() []git_repo.Addition {
    28  	if p.runningOnDeletedRef() {
    29  		log.WithFields(log.Fields{
    30  			"localRef":     p.localRef,
    31  			"localCommit":  p.localCommit,
    32  			"remoteRef":    p.remoteRef,
    33  			"remoteCommit": p.remoteCommit,
    34  		}).Info("Running on a deleted ref. Nothing to verify as outgoing changes are all deletions.")
    35  
    36  		return []git_repo.Addition{}
    37  	}
    38  
    39  	if p.runningOnNewRef() {
    40  		log.WithFields(log.Fields{
    41  			"localRef":     p.localRef,
    42  			"localCommit":  p.localCommit,
    43  			"remoteRef":    p.remoteRef,
    44  			"remoteCommit": p.remoteCommit,
    45  		}).Info("Running on a new ref. All changes in the ref will be verified.")
    46  
    47  		return p.getRepoAdditionsFrom(EmptyTreeSha, p.localCommit)
    48  	}
    49  
    50  	log.WithFields(log.Fields{
    51  		"localRef":     p.localRef,
    52  		"localCommit":  p.localCommit,
    53  		"remoteRef":    p.remoteRef,
    54  		"remoteCommit": p.remoteCommit,
    55  	}).Info("Running on an existing ref. All changes in the commit range will be verified.")
    56  
    57  	return p.getRepoAdditions()
    58  }
    59  
    60  func (p *PrePushHook) runningOnDeletedRef() bool {
    61  	return p.localCommit == EmptySha
    62  }
    63  
    64  func (p *PrePushHook) runningOnNewRef() bool {
    65  	return p.remoteCommit == EmptySha
    66  }
    67  
    68  func (p *PrePushHook) getRepoAdditions() []git_repo.Addition {
    69  	return p.getRepoAdditionsFrom(p.remoteCommit, p.localCommit)
    70  }
    71  
    72  func (p *PrePushHook) getRepoAdditionsFrom(oldCommit, newCommit string) []git_repo.Addition {
    73  	wd, _ := os.Getwd()
    74  	repo := git_repo.RepoLocatedAt(wd)
    75  	return repo.AdditionsWithinRange(oldCommit, newCommit)
    76  }