utils.go 3.6 KB
Newer Older
1 2
package common

3 4
import (
	"encoding/json"
5 6 7
	"fmt"
	"io"
	"net/http"
8
	"net/url"
9
	"os"
A
Avi Aryan 已提交
10 11
	"os/exec"
	"runtime"
12
	"strings"
13 14

	"github.com/appbaseio/abc/log"
15 16
)

17 18 19 20 21 22 23 24 25
// GetKeyForValue returns key for the given value
func GetKeyForValue(data map[string]string, val string) string {
	for k, v := range data {
		if v == val {
			return k
		}
	}
	return ""
}
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

// JSONNumberToString converts a json.Number to string, properly
// i.e. no decimal points for a integer
// json.Number is required instead of normal types in map[..].. based decoding
func JSONNumberToString(number json.Number) string {
	str := number.String()
	if strings.HasSuffix(str, ".0") {
		return str[0 : len(str)-2]
	}
	return str
}

// JSONNumberToInt ...
func JSONNumberToInt(number json.Number) int64 {
	f, err := number.Float64()
	if err != nil {
		log.Errorln(err)
		return 0
	}
	return int64(f)
}

// StringInSlice checks if string is in list or not
func StringInSlice(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}
57 58 59

// ColonPad pads spaces after colon
func ColonPad(text string, length int) string {
A
Avi Aryan 已提交
60 61 62 63 64
	// remove brackets in names, they are long
	bracket := strings.Index(text, "(")
	if bracket > -1 {
		text = text[:bracket]
	}
65 66 67 68 69 70 71
	textLen := len(text)
	text += ":"
	for i := 0; i < (length - textLen - 1); i++ {
		text += " "
	}
	return text
}
A
Avi Aryan 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

// OpenURL opens the specified URL in the default browser of the user.
// https://stackoverflow.com/a/39324149/2295672
func OpenURL(url string) error {
	var cmd string
	var args []string

	switch runtime.GOOS {
	case "windows":
		cmd = "cmd"
		args = []string{"/c", "start"}
	case "darwin":
		cmd = "open"
	default: // "linux", "freebsd", "openbsd", "netbsd"
		cmd = "xdg-open"
	}
	args = append(args, url)
	return exec.Command(cmd, args...).Start()
}
A
Avi Aryan 已提交
91 92 93 94 95

// SizeInKB shows size in KB
func SizeInKB(size int) int {
	return size / 1024 // original size in bytes
}
96 97 98

// IsFileValid check if the file is valid
func IsFileValid(file string) error {
99 100 101 102 103 104

	if _, err := url.ParseRequestURI(file); err == nil { //do not check remote file validity here
		log.Infoln("Importing data from remote file", file)
		return nil
	}

105 106 107 108 109
	if _, err := os.Stat(file); os.IsNotExist(err) {
		return err
	}
	return nil
}
A
Avi Aryan 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

// RemoveDuplicates removes duplicate values in a slice
// https://groups.google.com/forum/#!topic/golang-nuts/-pqkICuokio
func RemoveDuplicates(xs *[]string) {
	found := make(map[string]bool)
	j := 0
	for i, x := range *xs {
		if !found[x] {
			found[x] = true
			(*xs)[j] = (*xs)[i]
			j++
		}
	}
	*xs = (*xs)[:j]
}
125 126 127 128 129 130 131 132

// Max function
func Max(a, b int) int {
	if a >= b {
		return a
	}
	return b
}
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178

// DefaultDownloadDirectory to download remote files
var DefaultDownloadDirectory = "./temp"

//DownloadFile create a local copy of the remote json file
func DownloadFile(filepath string, url string) error {
	log.Infoln("Downloading the file from remote URL:", url)
	_, err := os.Stat(DefaultDownloadDirectory) //check if  directory exist
	if os.IsNotExist(err) {

		err = os.Mkdir(DefaultDownloadDirectory, 0755) //if not create, directory
		if err != nil {
			return err
		}
	}
	if err != nil {
		return err
	}

	resp, err := http.Get(url)
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	out, err := os.Create(filepath)
	if err != nil {
		return err
	}

	defer out.Close()

	_, err = io.Copy(out, resp.Body)
	return err
}

// RemoveFile delete remote file
func RemoveFile(fileName string) error {
	log.Infoln("Deleting the temporary file:", fileName)
	if err := os.Remove(fileName); err != nil {
		log.Debugf(fmt.Sprintf("Unable to delete temporary file: %s", fileName), err)
		return err
	}
	log.Infoln("file successfully deleted at path:", fileName)
	return nil
}