util

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2020 License: MIT Imports: 22 Imported by: 0

README

Util

Utility and core functions used by the updater.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckDigest

func CheckDigest(digest string, path string, typ DigestType) error

CheckDigest returns no error if digest matches file

func Close

func Close(f io.Closer)

Close closes a file and ignores the error. This satisfies lint checks when using with defer and you don't care if there is an error, so instead of:

defer func() { _ = f.Close() }()
defer Close(f)

func CombineErrors

func CombineErrors(errs ...error) error

CombineErrors returns a single error for multiple errors, or nil if none

func ComputeEtag

func ComputeEtag(path string) (string, error)

ComputeEtag returns etag for a file at path

func CopyFile

func CopyFile(sourcePath string, destinationPath string) error

CopyFile copies a file safely. It will create parent directories for destinationPath if they don't exist. It will overwrite an existing destinationPath.

func Digest256

func Digest256(r io.Reader) (string, error)

Digest256 returns a SHA256 digest.

func Digest512

func Digest512(r io.Reader) (string, error)

Digest512 returns a SHA256 digest.

func DigestForFileAtPath

func DigestForFileAtPath(path string, typ DigestType) (string, error)

DigestForFileAtPath returns a SHA256 digest for file at specified path

func DiscardAndCloseBody

func DiscardAndCloseBody(resp *http.Response) error

DiscardAndCloseBody reads as much as possible from the body of the given response, and then closes it.

This is because, in order to free up the current connection for re-use, a response body must be read from before being closed; see http://stackoverflow.com/a/17953506 .

Instead of doing:

res, _ := ...
defer res.Body.Close()

do

res, _ := ...
defer DiscardAndCloseBody(res)

instead.

func DiscardAndCloseBodyIgnoreError

func DiscardAndCloseBodyIgnoreError(resp *http.Response)

DiscardAndCloseBodyIgnoreError calls DiscardAndCloseBody. This satisfies lint checks when using with defer and you don't care if there is an error, so instead of:

defer func() { _ = DiscardAndCloseBody(resp) }()
defer DiscardAndCloseBodyIgnoreError(resp)

func DownloadURL

func DownloadURL(urlString string, destinationPath string, options DownloadURLOptions) error

DownloadURL downloads a URL to a path.

func EnvBool

func EnvBool(envVar string, defaultValue bool) bool

EnvBool returns a bool from an environment variable or default if invalid or not specified

func EnvDuration

func EnvDuration(envVar string, defaultValue time.Duration) time.Duration

EnvDuration returns a duration from an environment variable or default if invalid or not specified

func FileExists

func FileExists(path string) (bool, error)

FileExists returns whether the given file or directory exists or not

func FileModTime

func FileModTime(path string) (time.Time, error)

FileModTime returns modification time for file. If file doesn't exist returns error.

func HTTPClient

func HTTPClient(timeout time.Duration) *http.Client

HTTPClient returns http.Client with timeout.

func IsDirReal

func IsDirReal(path string) (bool, error)

IsDirReal returns true if directory exists and is a real directory (not a symlink). If it returns false, an error will be set explaining why.

func JoinPredicate

func JoinPredicate(arr []string, delimeter string, f func(s string) bool) string

JoinPredicate joins strings with predicate

func MakeDirs

func MakeDirs(dir string, mode os.FileMode) error

MakeDirs ensures directory exists for path

func MakeParentDirs

func MakeParentDirs(path string, mode os.FileMode) error

MakeParentDirs ensures parent directory exist for path

func MakeTempDir

func MakeTempDir(prefix string, mode os.FileMode) (string, error)

MakeTempDir creates a unique temp directory.

For example:

MakeTempDir("Test.", 0700)

func MoveFile

func MoveFile(sourcePath string, destinationPath string, tmpDir string) error

MoveFile moves a file safely. It will create parent directories for destinationPath if they don't exist. If the destination already exists and you specify a tmpDir, it will move it there, otherwise it will be removed.

func PathFromURL

func PathFromURL(u *url.URL) string

PathFromURL returns path for file URL scheme For example,

file:///usr/local/go/bin => /usr/local/go/bin
file:///C:/Go/bin => C:\Go\bin

func RandBytes

func RandBytes(length int) ([]byte, error)

RandBytes returns random bytes of length

func RandomID

func RandomID(prefix string) (string, error)

RandomID returns random ID (base32) string with prefix, using 256 bits as recommended by tptacek: https://gist.github.com/tqbf/be58d2d39690c3b366ad

func ReadFile

func ReadFile(path string) ([]byte, error)

ReadFile returns data for file at path

func RemoveFileAtPath

func RemoveFileAtPath(path string)

RemoveFileAtPath removes a file at path (and any children) ignoring any error. We do nothing if path == "". This satisfies lint checks when using with defer and you don't care if there is an error, so instead of:

defer func() { _ = os.Remove(path) }()
defer RemoveFileAtPath(path)

func SaveHTTPResponse

func SaveHTTPResponse(resp *http.Response, savePath string, mode os.FileMode) error

SaveHTTPResponse saves an http.Response to path

func SetLogger

func SetLogger(l Logger)

SetLogger sets logger for the package.

func TempPath

func TempPath(tempDir string, prefix string) string

TempPath returns a temporary unique file path. If for some reason we can't obtain random data, we still return a valid path, which may not be as unique. If tempDir is "", then os.TempDir() is used.

func TimeFromMillis

func TimeFromMillis(m TimeMs) time.Time

TimeFromMillis returns time.Time from milliseconds since epoch.

func Touch

func Touch(path string) error

Touch a file, updating its modification time

func URLExists

func URLExists(urlString string, timeout time.Duration) (bool, error)

URLExists returns error if URL doesn't exist

func URLStringForPath

func URLStringForPath(path string) string

URLStringForPath returns an URL as string with file scheme for path. For example,

/usr/local/go/bin => file:///usr/local/go/bin
C:\Go\bin => file:///C:/Go/bin

func URLValueForBool

func URLValueForBool(b bool) string

URLValueForBool returns "1" for true, otherwise "0"

func Unzip

func Unzip(sourcePath, destinationPath string) error

Unzip unpacks a zip file to a destination. This unpacks files using the current user and time (it doesn't preserve). This code was modified from https://stackoverflow.com/questions/20357223/easy-way-to-unzip-file-with-golang/20357902

func UnzipOver

func UnzipOver(sourcePath string, path string, destinationPath string, check func(sourcePath, destinationPath string) error, tmpDir string) error

UnzipOver safely unzips a file and copies it contents to a destination path. If destination path exists, it will be removed first. The filename must have a ".zip" extension. You can specify a check function, which will run before moving the unzipped directory into place. If you specify a tmpDir and destination path exists, it will be moved there instead of being removed.

To unzip Keybase-1.2.3.zip and move the contents Keybase.app to /Applications/Keybase.app

UnzipOver("/tmp/Keybase-1.2.3.zip", "Keybase.app", "/Applications/Keybase.app", check, "")

func UnzipPath

func UnzipPath(sourcePath string) (string, error)

UnzipPath unzips and returns path to unzipped directory

func WriteTempFile

func WriteTempFile(prefix string, data []byte, mode os.FileMode) (string, error)

WriteTempFile creates a unique temp file with data.

For example:

WriteTempFile("Test.", byte[]("test data"), 0600)

Types

type ContextLogger

type ContextLogger interface {
	Debugf(ctx context.Context, format string, args ...interface{})
	Infof(ctx context.Context, format string, args ...interface{})
	Warningf(ctx context.Context, format string, args ...interface{})
	Errorf(ctx context.Context, format string, args ...interface{})
}

ContextLogger interface used in this package with request context.

func NewContextLogger

func NewContextLogger(lev LogLevel) ContextLogger

NewContextLogger ...

type DigestType

type DigestType string

DigestType is type of digest.

const (
	// SHA256 is sha256 digest type
	SHA256 DigestType = "sha256"
	// SHA512 is sha512 digest type
	SHA512 DigestType = "sha512"
)

type DownloadURLOptions

type DownloadURLOptions struct {
	Digest     string
	SkipDigest bool
	DigestType DigestType
	UseETag    bool
	Timeout    time.Duration
}

DownloadURLOptions are options for DownloadURL.

type File

type File struct {
	// contains filtered or unexported fields
}

File uses a safer file API

func NewFile

func NewFile(name string, data []byte, perm os.FileMode) File

NewFile returns a File

func (File) GetFilename

func (f File) GetFilename() string

GetFilename returns the file name for SafeWriter

func (File) Save

func (f File) Save() error

Save file

func (File) WriteTo

func (f File) WriteTo(w io.Writer) (int64, error)

WriteTo is for SafeWriter

type LogLevel

type LogLevel int

LogLevel ...

const (
	// DebugLevel ...
	DebugLevel LogLevel = 3
	// InfoLevel ...
	InfoLevel LogLevel = 2
	// WarnLevel ...
	WarnLevel LogLevel = 1
	// ErrLevel ...
	ErrLevel LogLevel = 0
)

func (LogLevel) String

func (l LogLevel) String() string

type Logger

type Logger interface {
	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Warningf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
}

Logger interface used in this package.

func NewLogger

func NewLogger(lev LogLevel) Logger

NewLogger ...

type SafeWriter

type SafeWriter interface {
	GetFilename() string
	WriteTo(io.Writer) (int64, error)
}

SafeWriter defines a writer that is safer (atomic)

type TimeMs

type TimeMs int64

TimeMs is time as number of milliseconds from epoch.

func TimePtrToMillis

func TimePtrToMillis(t *time.Time) TimeMs

TimePtrToMillis returns milliseconds since epoch from time.Time. If t is nil or t.IsZero() we return 0.

func TimeToMillis

func TimeToMillis(t time.Time) TimeMs

TimeToMillis returns milliseconds since epoch from time.Time. If t.IsZero() we return 0.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL