github.com/psexton/git-lfs@v2.1.1-0.20170517224304-289a18b2bc53+incompatible/test/cmd/lfstest-testutils.go (about)

     1  // +build testtools
     2  
     3  package main
     4  
     5  import (
     6  	"encoding/json"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"os"
    10  	"path/filepath"
    11  
    12  	"github.com/git-lfs/git-lfs/test"
    13  )
    14  
    15  type TestUtilRepoCallback struct{}
    16  
    17  func (*TestUtilRepoCallback) Fatalf(format string, args ...interface{}) {
    18  	fmt.Fprintf(os.Stderr, format, args...)
    19  	os.Exit(4)
    20  }
    21  func (*TestUtilRepoCallback) Errorf(format string, args ...interface{}) {
    22  	fmt.Fprintf(os.Stderr, format, args...)
    23  }
    24  
    25  func main() {
    26  
    27  	commandMap := map[string]func(*test.Repo){
    28  		"addcommits": AddCommits,
    29  	}
    30  	if len(os.Args) < 2 {
    31  		fmt.Fprintf(os.Stderr, "Command required (e.g. addcommits)\n")
    32  		os.Exit(2)
    33  	}
    34  
    35  	f, ok := commandMap[os.Args[1]]
    36  	if !ok {
    37  		fmt.Fprintf(os.Stderr, "Unknown command: %v\n", os.Args[1])
    38  		os.Exit(2)
    39  	}
    40  	// Construct test repo context (note: no Cleanup() call since managed outside)
    41  	// also assume we're in the same folder
    42  	wd, err := os.Getwd()
    43  	if err != nil {
    44  		fmt.Fprintf(os.Stderr, "Problem getting working dir: %v\n", err)
    45  		os.Exit(2)
    46  	}
    47  	// Make sure we're directly inside directory which contains .git
    48  	// don't want to accidentally end up committing to some other parent git
    49  	_, err = os.Stat(filepath.Join(wd, ".git"))
    50  	if err != nil {
    51  		fmt.Fprintf(os.Stderr, "You're in the wrong directory, should be in root of a test repo: %v\n", err)
    52  		os.Exit(2)
    53  	}
    54  
    55  	repo := test.WrapRepo(&TestUtilRepoCallback{}, wd)
    56  	f(repo)
    57  }
    58  
    59  func AddCommits(repo *test.Repo) {
    60  	// Read stdin as JSON []*test.CommitInput
    61  	in, err := ioutil.ReadAll(os.Stdin)
    62  	if err != nil {
    63  		fmt.Fprintf(os.Stderr, "addcommits: Unable to read input data: %v\n", err)
    64  		os.Exit(3)
    65  	}
    66  	inputs := make([]*test.CommitInput, 0)
    67  	err = json.Unmarshal(in, &inputs)
    68  	if err != nil {
    69  		fmt.Fprintf(os.Stderr, "addcommits: Unable to unmarshal JSON: %v\n%v\n", string(in), err)
    70  		os.Exit(3)
    71  	}
    72  	outputs := repo.AddCommits(inputs)
    73  
    74  	by, err := json.Marshal(outputs)
    75  	if err != nil {
    76  		fmt.Fprintf(os.Stderr, "addcommits: Unable to marshal output JSON: %v\n", err)
    77  		os.Exit(3)
    78  	}
    79  	// Write response to stdout
    80  	_, err = os.Stdout.Write(by)
    81  	if err != nil {
    82  		fmt.Fprintf(os.Stderr, "addcommits: Error writing JSON to stdout: %v\n", err)
    83  		os.Exit(3)
    84  	}
    85  	os.Stdout.WriteString("\n")
    86  
    87  }