github.com/jchengjr77/canaveral@v1.0.1-0.20200715160102-ea9245d1a2fb/lib/errcheck.go (about)

     1  package lib
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  )
     8  
     9  // Check takes in an error and verifies if it is nil.
    10  // If the error is not nil, it will terminate the program.
    11  // * tested
    12  func Check(e error) {
    13  	if e != nil {
    14  		panic(e)
    15  	}
    16  }
    17  
    18  // FileExists checks if a file exists and is not a directory before we
    19  // try using it to prevent further errors.
    20  // * tested
    21  func FileExists(filename string) bool {
    22  	info, err := os.Stat(filename)
    23  	if os.IsNotExist(err) {
    24  		return false
    25  	}
    26  	return !info.IsDir()
    27  }
    28  
    29  // DirExists checks if a dir exists and is not a file before we
    30  // try using it to prevent further errors.
    31  // * tested
    32  func DirExists(dirname string) bool {
    33  	info, err := os.Stat(dirname)
    34  	if os.IsNotExist(err) {
    35  		return false
    36  	}
    37  	return info.IsDir()
    38  }
    39  
    40  // CreateFile creates a file with the name filename
    41  // ? untested (low priority)
    42  func CreateFile(filename string) error {
    43  	f, err := os.Create(filename)
    44  	defer f.Close()
    45  	return err
    46  }
    47  
    48  // CheckToolExists uses the 'which' command to find a specific tool.
    49  // It then parses the output of the command, and checks if
    50  // 'which' found the toolname in the path or not.
    51  // * tested
    52  func CheckToolExists(toolName string) bool {
    53  	if toolName == "" {
    54  		fmt.Println("Cannot pass in a blank toolname")
    55  		return false
    56  	}
    57  	if toolName[0] == '-' {
    58  		fmt.Println("Cannot pass in an option as a toolname")
    59  		return false
    60  	}
    61  	cmd := exec.Command("which", toolName)
    62  	_, err := cmd.Output()
    63  	// When 'which' cannot find the tool, it exits with status 1 (error)
    64  	if err != nil {
    65  		fmt.Println(err.Error())
    66  		fmt.Printf("PROBLEM: %s not found in path\n", toolName)
    67  		return false
    68  	}
    69  	fmt.Printf("%s found in path\n", toolName)
    70  	return true
    71  }