github.com/Mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/tests/gm/git.go (about) 1 /* 2 Copyright 2017 Mirantis 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package gm 18 19 import ( 20 "fmt" 21 "io/ioutil" 22 "os" 23 "os/exec" 24 "path/filepath" 25 26 "github.com/golang/glog" 27 ) 28 29 // GitDiff does 'git diff' on the specified file, first changing 30 // to its directory. It returns the diff and error, if any 31 func GitDiff(path string) (string, error) { 32 absPath, err := filepath.Abs(path) 33 if err != nil { 34 return "", fmt.Errorf("can't get abs path for %q: %v", path, err) 35 } 36 origWd, err := os.Getwd() 37 if err != nil { 38 return "", fmt.Errorf("can't get current directory: %v", err) 39 } 40 defer func() { 41 if err := os.Chdir(origWd); err != nil { 42 glog.Warningf("Can't chdir back to the old work dir: %v", err) 43 } 44 }() 45 fileDir := filepath.Dir(absPath) 46 if err := os.Chdir(fileDir); err != nil { 47 return "", fmt.Errorf("can't chdir to %q: %v", fileDir, err) 48 } 49 basePath := filepath.Base(absPath) 50 51 // https://stackoverflow.com/questions/2405305/how-to-tell-if-a-file-is-git-tracked-by-shell-exit-code 52 out, err := exec.Command("git", "ls-files", "--error-unmatch", "--", basePath).CombinedOutput() 53 if err != nil { 54 if _, ok := err.(*exec.ExitError); ok { 55 content, err := ioutil.ReadFile(absPath) 56 if err != nil { 57 return "", fmt.Errorf("error reading file %q: %v", absPath, err) 58 } 59 return "<NEW FILE>\n" + string(content), nil 60 } 61 return "", err 62 } 63 64 out, err = exec.Command("git", "diff", "--", basePath).CombinedOutput() 65 if err != nil { 66 return "", fmt.Errorf("git diff failed on %q: %v", basePath, err) 67 } 68 return string(out), nil 69 }