github.com/kcmerrill/alfred@v0.0.0-20180727171036-06445dcb5e3d/pkg/alfred/utils.go (about)

     1  package alfred
     2  
     3  import (
     4  	"os"
     5  	"os/exec"
     6  	"strings"
     7  )
     8  
     9  func evaluate(command, dir string) string {
    10  	results, ok := execute(command, dir)
    11  	if ok {
    12  		return strings.TrimSpace(results)
    13  	}
    14  	return command
    15  }
    16  
    17  func testCommand(command, dir string) bool {
    18  	_, ok := execute(command, dir)
    19  	return ok
    20  }
    21  
    22  func execute(command, dir string) (string, bool) {
    23  	cmd := exec.Command("bash", "-c", command)
    24  	cmd.Dir = dir
    25  	cmdOutput, error := cmd.CombinedOutput()
    26  	if error != nil {
    27  		return error.Error(), false
    28  	}
    29  	return string(cmdOutput), true
    30  }
    31  
    32  func emptyContext() *Context {
    33  	return InitialContext([]string{})
    34  }
    35  
    36  func emptyTaskList() map[string]Task {
    37  	etl := make(map[string]Task)
    38  	return etl
    39  }
    40  
    41  func padLeft(word string, size int, padding string) string {
    42  	return pad(word, size, padding) + word
    43  }
    44  
    45  func padRight(word string, size int, padding string) string {
    46  	return word + pad(word, size, padding)
    47  }
    48  
    49  func pad(word string, size int, padding string) string {
    50  	padded := ""
    51  	if len(word) >= size {
    52  		return padded
    53  	}
    54  
    55  	for l := 0; l < size-len(word); l++ {
    56  		padded += padding
    57  	}
    58  
    59  	return padded
    60  }
    61  
    62  func mkdir(dir string, context *Context) (string, bool) {
    63  	d := evaluate(context.relativePath(translate(dir, context)), ".")
    64  
    65  	if _, err := os.Stat(d); err == nil {
    66  		// woot!
    67  		return d, true
    68  	}
    69  
    70  	// ok, we have some work to do
    71  	if err := os.MkdirAll(d, 0755); err != nil {
    72  		// problem making directory
    73  		os.Exit(42)
    74  		return "./", false
    75  	}
    76  	return d, true
    77  }
    78  
    79  func curDir() string {
    80  	dir, err := os.Getwd()
    81  	if err == nil {
    82  		return dir
    83  	}
    84  	return "./"
    85  }