util.go 1.52 KB
Newer Older
Juan Batiz-Benet's avatar
key  
Juan Batiz-Benet committed
1
package util
Juan Batiz-Benet's avatar
util  
Juan Batiz-Benet committed
2 3 4

import (
	"fmt"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
5
	mh "github.com/jbenet/go-multihash"
Juan Batiz-Benet's avatar
util  
Juan Batiz-Benet committed
6
	"os"
7 8
	"os/user"
	"strings"
Juan Batiz-Benet's avatar
util  
Juan Batiz-Benet committed
9 10
)

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
11
// Debug is a global flag for debugging.
Juan Batiz-Benet's avatar
util  
Juan Batiz-Benet committed
12 13
var Debug bool

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
14 15 16 17
// ErrNotImplemented signifies a function has not been implemented yet.
var ErrNotImplemented = fmt.Errorf("Error: not implemented yet.")

// Key is a string representation of multihash for use with maps.
Juan Batiz-Benet's avatar
key  
Juan Batiz-Benet committed
18 19
type Key string

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
20
// Hash is the global IPFS hash function. uses multihash SHA2_256, 256 bits
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21 22 23 24
func Hash(data []byte) (mh.Multihash, error) {
	return mh.Sum(data, mh.SHA2_256, -1)
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
25
// TildeExpansion expands a filename, which may begin with a tilde.
26 27 28 29 30 31 32 33 34 35 36 37 38
func TildeExpansion(filename string) (string, error) {
	if strings.HasPrefix(filename, "~/") {
		usr, err := user.Current()
		if err != nil {
			return "", err
		}

		dir := usr.HomeDir + "/"
		filename = strings.Replace(filename, "~/", dir, 1)
	}
	return filename, nil
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
39
// PErr is a shorthand printing function to output to Stderr.
Juan Batiz-Benet's avatar
util  
Juan Batiz-Benet committed
40 41 42 43
func PErr(format string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, format, a...)
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
44
// POut is a shorthand printing function to output to Stdout.
Juan Batiz-Benet's avatar
util  
Juan Batiz-Benet committed
45 46 47 48
func POut(format string, a ...interface{}) {
	fmt.Fprintf(os.Stdout, format, a...)
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
49 50
// DErr is a shorthand debug printing function to output to Stderr.
// Will only print if Debug is true.
Juan Batiz-Benet's avatar
util  
Juan Batiz-Benet committed
51 52 53 54 55 56
func DErr(format string, a ...interface{}) {
	if Debug {
		PErr(format, a...)
	}
}

Juan Batiz-Benet's avatar
go lint  
Juan Batiz-Benet committed
57 58
// DOut is a shorthand debug printing function to output to Stdout.
// Will only print if Debug is true.
Juan Batiz-Benet's avatar
util  
Juan Batiz-Benet committed
59 60 61 62 63
func DOut(format string, a ...interface{}) {
	if Debug {
		POut(format, a...)
	}
}