github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/configfile_unix.go (about)

     1  // +build darwin freebsd linux netbsd openbsd
     2  
     3  package main
     4  
     5  import (
     6  	"bytes"
     7  	"errors"
     8  	"log"
     9  	"os"
    10  	"os/exec"
    11  	"path/filepath"
    12  	"strings"
    13  )
    14  
    15  func configFile() (string, error) {
    16  	dir, err := configDir()
    17  	if err != nil {
    18  		return "", err
    19  	}
    20  
    21  	return filepath.Join(dir, ".packerconfig"), nil
    22  }
    23  
    24  func configDir() (string, error) {
    25  	// First prefer the HOME environmental variable
    26  	if home := os.Getenv("HOME"); home != "" {
    27  		log.Printf("Detected home directory from env var: %s", home)
    28  		return home, nil
    29  	}
    30  
    31  	// If that fails, try the shell
    32  	var stdout bytes.Buffer
    33  	cmd := exec.Command("sh", "-c", "eval echo ~$USER")
    34  	cmd.Stdout = &stdout
    35  	if err := cmd.Run(); err != nil {
    36  		return "", err
    37  	}
    38  
    39  	result := strings.TrimSpace(stdout.String())
    40  	if result == "" {
    41  		return "", errors.New("blank output")
    42  	}
    43  
    44  	return result, nil
    45  }