github.com/hhsnopek/up@v0.1.1/internal/util/util.go (about)

     1  // Package util haters gonna hate.
     2  package util
     3  
     4  import (
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  	"os"
    10  
    11  	"github.com/apex/up/internal/colors"
    12  	"github.com/pascaldekloe/name"
    13  	"github.com/pkg/errors"
    14  	"github.com/tj/go-progress"
    15  )
    16  
    17  // Fields retained when clearing.
    18  var keepFields = map[string]bool{
    19  	"X-Powered-By": true,
    20  }
    21  
    22  // ClearHeader removes all header fields.
    23  func ClearHeader(h http.Header) {
    24  	for k := range h {
    25  		if keepFields[k] {
    26  			continue
    27  		}
    28  
    29  		h.Del(k)
    30  	}
    31  }
    32  
    33  // ManagedByUp appends "Managed by Up".
    34  func ManagedByUp(s string) string {
    35  	if s == "" {
    36  		return "Managed by Up."
    37  	}
    38  
    39  	return s + " (Managed by Up)."
    40  }
    41  
    42  // Exists returns true if the file exists.
    43  func Exists(path string) bool {
    44  	_, err := os.Stat(path)
    45  	return err == nil
    46  }
    47  
    48  // ReadFileJSON reads json from the given path.
    49  func ReadFileJSON(path string, v interface{}) error {
    50  	b, err := ioutil.ReadFile(path)
    51  	if err != nil {
    52  		return errors.Wrap(err, "reading")
    53  	}
    54  
    55  	if err := json.Unmarshal(b, &v); err != nil {
    56  		return errors.Wrap(err, "unmarshaling")
    57  	}
    58  
    59  	return nil
    60  }
    61  
    62  // Camelcase string with optional args.
    63  func Camelcase(s string, v ...interface{}) string {
    64  	return name.CamelCase(fmt.Sprintf(s, v...), true)
    65  }
    66  
    67  // NewProgressInt with the given total.
    68  func NewProgressInt(total int) *progress.Bar {
    69  	b := progress.NewInt(total)
    70  	b.Template(`{{.Bar}} {{.Percent | printf "%0.0f"}}% {{.Text}}`)
    71  	b.Width = 35
    72  	b.StartDelimiter = colors.Gray("|")
    73  	b.EndDelimiter = colors.Gray("|")
    74  	b.Filled = colors.Purple("█")
    75  	b.Empty = colors.Gray("░")
    76  	return b
    77  }
    78  
    79  // Pad helper.
    80  func Pad() func() {
    81  	println()
    82  	return func() {
    83  		println()
    84  	}
    85  }
    86  
    87  // Fatal error.
    88  func Fatal(err error) {
    89  	fmt.Fprintf(os.Stderr, "\n  %s %s\n\n", colors.Red("Error:"), err)
    90  	os.Exit(1)
    91  }
    92  
    93  // IsJSON returns true if the msg looks like json.
    94  func IsJSON(s string) bool {
    95  	return len(s) > 1 && s[0] == '{' && s[len(s)-1] == '}'
    96  }