bitbucket.org/ai69/amoy@v0.2.3/shell.go (about)

     1  package amoy
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"log"
     8  	"os"
     9  	"reflect"
    10  	"runtime"
    11  	"strings"
    12  )
    13  
    14  // ChangeDir changes the current working directory.
    15  func ChangeDir(path string) {
    16  	if err := os.Chdir(path); err != nil {
    17  		log.Fatalf("fail to change dir: %v", err)
    18  	}
    19  }
    20  
    21  // CurrentFunctionName returns name of current function.
    22  func CurrentFunctionName() string {
    23  	pc, _, _, _ := runtime.Caller(1)
    24  	return runtime.FuncForPC(pc).Name()
    25  }
    26  
    27  // FunctionName returns name of the given function.
    28  func FunctionName(f interface{}) string {
    29  	return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
    30  }
    31  
    32  // ShortFunctionName returns short name of the given function.
    33  func ShortFunctionName(f interface{}) string {
    34  	name := FunctionName(f)
    35  	if p := strings.LastIndex(name, "."); p >= 0 && len(name) > p {
    36  		return name[p+1:]
    37  	}
    38  	return name
    39  }
    40  
    41  // GetEnvVar returns the value of the given environment variable or the fallback.
    42  func GetEnvVar(key, fallback string) string {
    43  	if value, ok := os.LookupEnv(key); ok {
    44  		return value
    45  	}
    46  	return fallback
    47  }
    48  
    49  // IsInterfaceNil returns true if the given interface is nil.
    50  func IsInterfaceNil(i interface{}) bool {
    51  	if i == nil {
    52  		return true
    53  	}
    54  	defer func() { recover() }()
    55  	switch reflect.TypeOf(i).Kind() {
    56  	case reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan, reflect.Func:
    57  		return reflect.ValueOf(i).IsNil()
    58  	}
    59  	return false
    60  }
    61  
    62  var (
    63  	// ErrNoPipeData is returned when no data was read from the stdin pipe.
    64  	ErrNoPipeData = errors.New("amoy: no pipe data")
    65  )
    66  
    67  // ReadStdinPipe reads stdin data via pipe and returns the data.
    68  func ReadStdinPipe() ([]byte, error) {
    69  	fi, err := os.Stdin.Stat()
    70  	if err != nil {
    71  		return nil, fmt.Errorf(`amoy: %w`, err)
    72  	}
    73  	if fi.Mode()&os.ModeNamedPipe != 0 {
    74  		b, err := ioutil.ReadAll(os.Stdin)
    75  		if err != nil {
    76  			return b, fmt.Errorf(`amoy: %w`, err)
    77  		}
    78  		return b, nil
    79  	}
    80  	return nil, ErrNoPipeData
    81  }