util

package
v0.0.0-...-37fe1c2 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2024 License: BSD-3-Clause, MIT Imports: 17 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, log Log) 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, log Log) 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 Digest

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

Digest returns a SHA256 digest

func DigestForFileAtPath

func DigestForFileAtPath(path string) (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 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, log Log) error

MakeDirs ensures directory exists for path

func MakeParentDirs

func MakeParentDirs(path string, mode os.FileMode, log Log) 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, log Log) 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, log Log) error

SaveHTTPResponse saves an http.Response to path

func Semver

func Semver(version string) string

Semver outputs the semver in Major.Minor.Patch form for readability.

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 Touch

func Touch(path string) error

Touch a file, updating its modification time

func URLExists

func URLExists(urlString string, timeout time.Duration, log Log) (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, log Log) 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, log Log) 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, "", log)

func UnzipPath

func UnzipPath(sourcePath string, log Log) (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 DownloadURLOptions

type DownloadURLOptions struct {
	Digest        string
	RequireDigest bool
	UseETag       bool
	Timeout       time.Duration
	Log           Log
}

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(log Log) error

Save file

func (File) WriteTo

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

WriteTo is for SafeWriter

type Log

type Log interface {
	Debugf(s string, args ...interface{})
	Infof(s string, args ...interface{})
	Warningf(s string, args ...interface{})
	Errorf(s string, args ...interface{})
}

Log is the logging interface for the util package

type SafeWriter

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

SafeWriter defines a writer that is safer (atomic)

Jump to

Keyboard shortcuts

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