util

package
v0.0.0-...-9e9b4ff Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2018 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// GitCommit is the git commit hash associated with this build.
	GitCommit = ""

	// MajorVersion is the semver major version.
	MajorVersion = "1"

	// MinorVersion is the semver minor version.
	MinorVersion = "0"

	// PatchVersion is the semver patch version. (use 0 for dev, build process
	// will inject a build number)
	PatchVersion = "0"

	// Compiled is the unix timestamp when this binary got compiled.
	Compiled = ""
)
View Source
var (
	// ErrEmptyTarball is returned when the tarball has no files in it
	ErrEmptyTarball = errors.New("empty tarball")
)

Functions

func CompiledAt

func CompiledAt() time.Time

CompiledAt converts the Unix time Compiled to a time.Time using UTC timezone.

func ContainsString

func ContainsString(items []string, target string) bool

ContainsString checks if the array items contains the string target. TODO(bvdberg): write units tests

func ConvertUnit

func ConvertUnit(size int64) (int64, string)

ConvertUnit takes the number of bytes and converts this to the largest unit possible, where the result is still > 1. Uses default golang int rounding.

func Exists

func Exists(path string) (bool, error)

exists is like python's os.path.exists and too many lines in Go

func ExpandHomePath

func ExpandHomePath(p string, home string) string

ExpandHomePath will expand ~/ in p to home.

func FormatMessage

func FormatMessage(color string, useColors bool, messages ...string) string

FormatMessage handles one or two messages. If more messages are used, those are ignore. If no messages are used, than it will return an empty string. 1 message : --> message[0] 2 messages: --> message[0]: message[1] color will be applied to the first message, varColor will be used for the second message. If useColors is false, than color will be ignored.

func FullVersion

func FullVersion() string

FullVersion returns the semver version and the git version if available.

func Get

func Get(url, authToken string) (*http.Response, error)

Get tries to make a GET request to url. It will retry, upto 3 times, when the response is http statuscode 5xx.

func InstalledWithHomebrew

func InstalledWithHomebrew() bool

InstalledWithHomebrew tries to determine if the cli was installed with homebrew

func MaxInt

func MaxInt(input ...int) int

MaxInt finds the biggest int in input and return that value. If no input is given, it will return 0.

func MinInt

func MinInt(input ...int) int

MinInt finds the smallest int in input and return that value. If no input is given, it will return 0.

func QueryString

func QueryString(opts interface{}) map[string]interface{}

QueryString converts a struct to a map. It looks for items with a qs tag. This code was taken from the fsouza/go-dockerclient, and then slightly modified. See: https://github.com/fsouza/go-dockerclient/blob/5fa67ac8b52afe9430a490391a639085e9357e1e/client.go#L535

func SortByModDate

func SortByModDate(dirs []os.FileInfo)

SortByModDate sorts the files or folders descending by modification date

func SplitSpaceOrComma

func SplitSpaceOrComma(str string) []string

func SqaushErrors

func SqaushErrors(errors []error) error

SqaushErrors takes multiple error objects and returns a single error which will enumerate all Error() from the wrapped error objects. If errors contains no error objects, then it will return nil.

func TarPath

func TarPath(writer io.Writer, root string) error

TarPath makes a tarfile out of a directory The contents of the "root" directory will be placed at the top level in the tarfile. Directory names are not written to the tarfile.

func TarPathWithRoot

func TarPathWithRoot(writer io.Writer, root string, tarRoot string) error

TarPathWithRoot makes a tarfile from the files under "root". A directory named "tarRoot" will be created at the top level in the tarball, with the files under "root" placed under it. Directory names are written to the tarfile (including empty directories). Symbolic links are ignored (walk doesn't follow symbolic links anyway).

func Untar

func Untar(dst string, r io.Reader) error

Untar takes a destination path and a reader; a tar reader loops over the tarfile creating the file structure at 'dst' along the way, and writing any files

func UntarOne

func UntarOne(name string, dst io.Writer, src io.ReadCloser) error

UntarOne writes the contents up a single file to dst

func Untargzip

func Untargzip(path string, r io.Reader) error

Untargzip tries to untar-gzip stuff to a path

func Version

func Version() string

Version returns a semver compatible version for this build.

Types

type Archive

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

Archive holds the tarball stream and provides methods to manipulate it

func NewArchive

func NewArchive(stream io.Reader, closer func()) *Archive

NewArchive constructor If the reader needs to be closed after use then closer must be set to a func which will close the reader

func (*Archive) Close

func (a *Archive) Close()

Close the archive

func (*Archive) Multi

func (a *Archive) Multi(source, target string, maxSize int64) (errs chan error)

Multi file extraction with max size and empty check

func (*Archive) Single

func (a *Archive) Single(source, target string, maxSize int64) (errs chan error)

Single file extraction with max size and empty check

func (*Archive) SingleBytes

func (a *Archive) SingleBytes(source string, dst *bytes.Buffer) chan error

SingleBytes gives you the bytes of a single file, with empty check

func (*Archive) Stream

func (a *Archive) Stream(processors ...ArchiveProcessor) error

Stream is the low-level interface to the archive stream processor

func (*Archive) Tee

func (a *Archive) Tee(w io.Writer)

Tee the tar stream to your own writer

type ArchiveBytes

type ArchiveBytes struct {
	*bytes.Buffer
}

ArchiveBytes is expected to be used with an ArchiveSingle filter so that it only gets one file, if not the buffer will be pretty silly

func (*ArchiveBytes) Process

func (p *ArchiveBytes) Process(hdr *tar.Header, r io.Reader) (*tar.Header, io.Reader, error)

Process writes the bytes for a file to ourselves (a bytes.Buffer)

type ArchiveCheckEmpty

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

ArchiveCheckEmpty is an ArchiveProcessor to check whether a stream is empty

func (*ArchiveCheckEmpty) IsEmpty

func (p *ArchiveCheckEmpty) IsEmpty() bool

IsEmpty will represent whether the tarball was empty after processing

func (*ArchiveCheckEmpty) Process

func (p *ArchiveCheckEmpty) Process(hdr *tar.Header, r io.Reader) (*tar.Header, io.Reader, error)

Process impl

type ArchiveExtract

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

ArchiveExtract everything to a tempdir, methods for Rename and Cleanup

func NewArchiveExtract

func NewArchiveExtract(tempDir string) *ArchiveExtract

NewArchiveExtract creates a new ArchiveExtract. tempDir is directory to perform work. Leave empty string to use default

func (*ArchiveExtract) Clean

func (p *ArchiveExtract) Clean()

Clean should be called to clean up the workingDir

func (*ArchiveExtract) Process

func (p *ArchiveExtract) Process(hdr *tar.Header, r io.Reader) (*tar.Header, io.Reader, error)

Process impl

func (*ArchiveExtract) Rename

func (p *ArchiveExtract) Rename(source, target string) error

Rename one of the extracted paths to the target path

type ArchiveMaxSize

type ArchiveMaxSize struct {
	MaxSize int64 // in bytes
	// contains filtered or unexported fields
}

ArchiveMaxSize throws an error and stop stream if MaxSize reached

func (*ArchiveMaxSize) Process

func (p *ArchiveMaxSize) Process(hdr *tar.Header, r io.Reader) (*tar.Header, io.Reader, error)

Process impl

type ArchiveProcessor

type ArchiveProcessor interface {
	Process(*tar.Header, io.Reader) (*tar.Header, io.Reader, error)
}

ArchiveProcessor is a stream processor for the archive tarballs

type ArchiveSingle

type ArchiveSingle struct {
	Name string
}

ArchiveSingle filters all but a single item out of the string

func (*ArchiveSingle) Process

func (p *ArchiveSingle) Process(hdr *tar.Header, r io.Reader) (*tar.Header, io.Reader, error)

Process impl

type ByModifiedTime

type ByModifiedTime []os.FileInfo

ByModifiedTime is used for sorting files/folders by mod time

func (ByModifiedTime) Len

func (s ByModifiedTime) Len() int

Len returns the length of items in the slice

func (ByModifiedTime) Less

func (s ByModifiedTime) Less(i, j int) bool

Less returns true if the first value shoudl appear first in the sorted results

func (ByModifiedTime) Swap

func (s ByModifiedTime) Swap(i, j int)

Swap swaps two items when sorting

type CLISettings

type CLISettings struct {
	CheapSettings *CheapSettings
	// contains filtered or unexported fields
}

CLISettings is a wrapper on a cli.Context with a special "target" set in place of "Args().First()"

func NewCLISettings

func NewCLISettings(ctx *cli.Context) *CLISettings

func (*CLISettings) Bool

func (s *CLISettings) Bool(name string, def ...interface{}) (rv bool, ok bool)

func (*CLISettings) BoolT

func (s *CLISettings) BoolT(name string, def ...interface{}) (rv bool, ok bool)

func (*CLISettings) Duration

func (s *CLISettings) Duration(name string, def ...interface{}) (rv time.Duration, ok bool)

func (*CLISettings) Float64

func (s *CLISettings) Float64(name string, def ...interface{}) (rv float64, ok bool)

func (*CLISettings) GlobalBool

func (s *CLISettings) GlobalBool(name string, def ...interface{}) (rv bool, ok bool)

func (*CLISettings) GlobalDuration

func (s *CLISettings) GlobalDuration(name string, def ...interface{}) (rv time.Duration, ok bool)

func (*CLISettings) GlobalInt

func (s *CLISettings) GlobalInt(name string, def ...interface{}) (rv int, ok bool)

func (*CLISettings) GlobalIntSlice

func (s *CLISettings) GlobalIntSlice(name string, def ...interface{}) (rv []int, ok bool)

func (*CLISettings) GlobalString

func (s *CLISettings) GlobalString(name string, def ...interface{}) (rv string, ok bool)

func (*CLISettings) GlobalStringSlice

func (s *CLISettings) GlobalStringSlice(name string, def ...interface{}) (rv []string, ok bool)

func (*CLISettings) Int

func (s *CLISettings) Int(name string, def ...interface{}) (rv int, ok bool)

func (*CLISettings) IntSlice

func (s *CLISettings) IntSlice(name string, def ...interface{}) (rv []int, ok bool)

func (*CLISettings) String

func (s *CLISettings) String(name string, def ...interface{}) (rv string, ok bool)

func (*CLISettings) StringSlice

func (s *CLISettings) StringSlice(name string, def ...interface{}) (rv []string, ok bool)

type CheapSettings

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

CheapSettings based on a map, returns val, ok

func NewCheapSettings

func NewCheapSettings(data map[string]interface{}) *CheapSettings

func (*CheapSettings) Bool

func (s *CheapSettings) Bool(name string, def ...interface{}) (rv bool, ok bool)

func (*CheapSettings) BoolT

func (s *CheapSettings) BoolT(name string, def ...interface{}) (rv bool, ok bool)

BoolT is true by default

func (*CheapSettings) Duration

func (s *CheapSettings) Duration(name string, def ...interface{}) (rv time.Duration, ok bool)

func (*CheapSettings) Float64

func (s *CheapSettings) Float64(name string, def ...interface{}) (rv float64, ok bool)

func (*CheapSettings) GlobalBool

func (s *CheapSettings) GlobalBool(name string, def ...interface{}) (rv bool, ok bool)

func (*CheapSettings) GlobalDuration

func (s *CheapSettings) GlobalDuration(name string, def ...interface{}) (rv time.Duration, ok bool)

func (*CheapSettings) GlobalInt

func (s *CheapSettings) GlobalInt(name string, def ...interface{}) (rv int, ok bool)

All the Global versions to do the same thing as the non-global

func (*CheapSettings) GlobalIntSlice

func (s *CheapSettings) GlobalIntSlice(name string, def ...interface{}) (rv []int, ok bool)

func (*CheapSettings) GlobalString

func (s *CheapSettings) GlobalString(name string, def ...interface{}) (rv string, ok bool)

func (*CheapSettings) GlobalStringSlice

func (s *CheapSettings) GlobalStringSlice(name string, def ...interface{}) (rv []string, ok bool)

func (*CheapSettings) Int

func (s *CheapSettings) Int(name string, def ...interface{}) (rv int, ok bool)

func (*CheapSettings) IntSlice

func (s *CheapSettings) IntSlice(name string, def ...interface{}) (rv []int, ok bool)

func (*CheapSettings) String

func (s *CheapSettings) String(name string, def ...interface{}) (rv string, ok bool)

func (*CheapSettings) StringSlice

func (s *CheapSettings) StringSlice(name string, def ...interface{}) (rv []string, ok bool)

type Counter

type Counter struct {
	Current int
	// contains filtered or unexported fields
}

Counter is a simple struct

func (*Counter) Increment

func (c *Counter) Increment() int

Increment will return current and than increment c.Current.

type CounterReader

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

CounterReader is a io.Reader which wraps a other io.Reader and stores the bytes reader from it.

func NewCounterReader

func NewCounterReader(r io.Reader) *CounterReader

NewCounterReader creates a new CounterReader.

func (*CounterReader) Count

func (c *CounterReader) Count() int64

Count returns the bytes read from r.

func (*CounterReader) Read

func (c *CounterReader) Read(p []byte) (int, error)

Read proxy's the request to r, and stores the bytes read as reported by r.

type Debouncer

type Debouncer struct {
	C <-chan time.Time
	// contains filtered or unexported fields
}

Debouncer silences repeated triggers for settlePeriod and sends the current time on first trigger to C C is the public read only channel, c is the private r/w chan

func NewDebouncer

func NewDebouncer(d time.Duration) *Debouncer

NewDebouncer constructor

func (*Debouncer) Trigger

func (d *Debouncer) Trigger()

Trigger tells us we should do the thing we're waiting on

type Environment

type Environment struct {
	Hidden *Environment
	Map    map[string]string
	Order  []string
}

Environment represents a shell environment and is implemented as something like an OrderedMap

func NewEnvironment

func NewEnvironment(env ...string) *Environment

NewEnvironment fills up an Environment from a []string Usually called like: env := NewEnvironment(os.Environ())

func (*Environment) Add

func (e *Environment) Add(key, value string)

Add an individual record.

func (*Environment) AddIfMissing

func (e *Environment) AddIfMissing(key, value string)

Add an individual record.

func (*Environment) Export

func (e *Environment) Export() []string

Export the environment as shell commands for use with Session.Send*

func (*Environment) Get

func (e *Environment) Get(key string) string

Get an individual record.

func (*Environment) GetHiddenPassthru

func (e *Environment) GetHiddenPassthru() (env *Environment)

Collect the hidden passthru variables

func (*Environment) GetInclHidden

func (e *Environment) GetInclHidden(key string) string

GetInclHidden gets an individual record either from this environment or the hidden environment.

func (*Environment) GetMirror

func (e *Environment) GetMirror() [][]string

func (*Environment) GetPassthru

func (e *Environment) GetPassthru() (env *Environment)

Collect passthru variables from the project

func (*Environment) Interpolate

func (e *Environment) Interpolate(s string) string

Interpolate is a naive interpolator that attempts to replace variables identified by $VAR with the value of the VAR pipeline environment variable NOTE(termie): This will check the hidden env, too.

func (*Environment) LoadFile

func (e *Environment) LoadFile(f string) error

LoadFile imports key,val pairs from the provided file path. File entries should be 1 per line in the form key=value. Blank lines and lines begining with # are ignored.

func (*Environment) Ordered

func (e *Environment) Ordered() [][]string

Ordered returns a [][]string of the items in the env. Used only for debugging

func (*Environment) PassThruProxyConfig

func (e *Environment) PassThruProxyConfig()

Add proxy configuration as public

func (*Environment) Update

func (e *Environment) Update(a [][]string)

Update adds new elements to the Environment data structure.

type Finisher

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

Finisher is a helper class for running something either right away or at `defer` time.

func NewFinisher

func NewFinisher(callback func(interface{})) *Finisher

NewFinisher returns a new Finisher with a callback.

func (*Finisher) Finish

func (f *Finisher) Finish(result interface{})

Finish executes the callback if it hasn't been run yet.

type Formatter

type Formatter struct {
	ShowColors bool
}

Formatter formats the messages, and optionally disabling colors. See FormatMessage for the structure of messages.

func (*Formatter) Fail

func (f *Formatter) Fail(messages ...string) string

Fail uses failColor (red) as color.

func (*Formatter) Info

func (f *Formatter) Info(messages ...string) string

Info uses no color.

func (*Formatter) Success

func (f *Formatter) Success(messages ...string) string

Success uses successColor (green) as color.

type LogEntry

type LogEntry struct {
	*logrus.Entry
}

LogEntry wraps logrus

func (*LogEntry) WithField

func (e *LogEntry) WithField(key string, value interface{}) *LogEntry

WithField wraps logrus

func (*LogEntry) WithFields

func (e *LogEntry) WithFields(fields LogFields) *LogEntry

WithFields wraps logrus

type LogFields

type LogFields logrus.Fields

LogFields is just exported form logrus

type Logger

type Logger struct {
	*logrus.Logger
}

Logger is a wrapper for logrus so that we don't have to keep referring to its types everywhere and can add helpers

func NewLogger

func NewLogger() *Logger

NewLogger constructor

func NewRawLogger

func NewRawLogger() *Logger

NewRawLogger constructor

func RootLogger

func RootLogger() *Logger

func (*Logger) SetLevel

func (l *Logger) SetLevel(level string)

SetLevel to set using strings

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) *LogEntry

WithField wraps logrus

func (*Logger) WithFields

func (l *Logger) WithFields(fields LogFields) *LogEntry

WithFields wraps logrus

type Settings

type Settings interface {
	Int(string, ...interface{}) (int, bool)
	Duration(string, ...interface{}) (time.Duration, bool)
	Float64(string, ...interface{}) (float64, bool)
	Bool(string, ...interface{}) (bool, bool)
	BoolT(string, ...interface{}) (bool, bool)
	String(string, ...interface{}) (string, bool)
	StringSlice(string, ...interface{}) ([]string, bool)
	IntSlice(string, ...interface{}) ([]int, bool)

	GlobalInt(string, ...interface{}) (int, bool)
	GlobalDuration(string, ...interface{}) (time.Duration, bool)
	// NOTE(termie): for some reason not in cli.Context
	// GlobalFloat64(string, ...interface{}) (float64, bool)
	GlobalBool(string, ...interface{}) (bool, bool)
	// NOTE(termie): for some reason not in cli.Context
	// GlobalBoolT(string, ...interface{}) (bool, bool)
	GlobalString(string, ...interface{}) (string, bool)
	GlobalStringSlice(string, ...interface{}) ([]string, bool)
	GlobalIntSlice(string, ...interface{}) ([]int, bool)
}

Settings mathces the cli.Context interface so we can make a cheap re-implementation for testing purposes.

type SignalHandler

type SignalHandler struct {
	ID string
	F  func() bool
}

SignalHandler is a little struct to hold our signal handling functions and an identifier so we can remove it from the list.

type SignalMonkey

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

SignalMonkey is a LIFO, cascading, singleton for dispatching signal handlers

func GlobalSigint

func GlobalSigint() *SignalMonkey

GlobalSigint returns the sigint registry

func GlobalSigterm

func GlobalSigterm() *SignalMonkey

GlobalSigterm returns the sigterm registry

func NewSignalMonkey

func NewSignalMonkey() *SignalMonkey

NewSignalMonkey constructor

func (*SignalMonkey) Add

func (s *SignalMonkey) Add(fn *SignalHandler)

Add a handler to our array

func (*SignalMonkey) Dispatch

func (s *SignalMonkey) Dispatch()

Dispatch calls the handlers LIFO, removing them from the list as it does if any returns false, it stops processing further handlers.

func (*SignalMonkey) Register

func (s *SignalMonkey) Register(sig os.Signal)

Register ourselves to get notifications on a signal

func (*SignalMonkey) Remove

func (s *SignalMonkey) Remove(fn *SignalHandler)

Remove a handler from our array

type Stepper

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

Stepper lets use step and sync goroutines

func NewStepper

func NewStepper() *Stepper

NewStepper constructor

func (*Stepper) Step

func (s *Stepper) Step(delay ...int)

Step through a waiting goroutine with optional delay

func (*Stepper) Wait

func (s *Stepper) Wait()

Wait until Step has been called

type TerseFormatter

type TerseFormatter struct {
	// Set to true to bypass checking for a TTY before outputting colors.
	ForceColors   bool
	DisableColors bool
	// Set to true to disable timestamp logging (useful when the output
	// is redirected to a logging system already adding a timestamp)
	DisableTimestamp bool
}

TerseFormatter gives us very basic output

func (*TerseFormatter) Format

func (f *TerseFormatter) Format(entry *logrus.Entry) ([]byte, error)

Format tersely

type TestLogFormatter

type TestLogFormatter struct {
	*logrus.TextFormatter
}

TestLogFormatter removes the last newline character

func NewTestLogFormatter

func NewTestLogFormatter() *TestLogFormatter

NewTestLogFormatter constructor

func (*TestLogFormatter) Format

func (f *TestLogFormatter) Format(entry *logrus.Entry) ([]byte, error)

Format like a text log but strip the last newline

type TestLogWriter

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

TestLogWriter writes our logs to the test output

func NewTestLogWriter

func NewTestLogWriter(t *testing.T) *TestLogWriter

NewTestLogWriter constructor

func (*TestLogWriter) Write

func (l *TestLogWriter) Write(p []byte) (int, error)

Write for io.Writer

type TestSuite

type TestSuite struct {
	suite.Suite
	// contains filtered or unexported fields
}

TestSuite is our base class for test suites

func (*TestSuite) FailNow

func (s *TestSuite) FailNow()

FailNow just proxies to testing.T.FailNow

func (*TestSuite) SetupTest

func (s *TestSuite) SetupTest()

SetupTest mostly just configures logging now

func (*TestSuite) Skip

func (s *TestSuite) Skip(msg string)

Skip just proxies to testing.T.Skip

func (*TestSuite) TearDownTest

func (s *TestSuite) TearDownTest()

TearDownTest cleans up our working dir if we made one

func (*TestSuite) WorkingDir

func (s *TestSuite) WorkingDir() string

WorkingDir makes a new temp dir to run tests in

type Timer

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

Timer so we can dump step timings

func NewTimer

func NewTimer() *Timer

NewTimer ctor

func (*Timer) Elapsed

func (t *Timer) Elapsed() time.Duration

Elapsed duration

func (*Timer) Reset

func (t *Timer) Reset()

Reset that timer

func (*Timer) String

func (t *Timer) String() string

String repr for time

type VerboseFormatter

type VerboseFormatter struct {
	// Set to true to bypass checking for a TTY before outputting colors.
	ForceColors   bool
	DisableColors bool
	// Set to true to disable timestamp logging (useful when the output
	// is redirected to a logging system already adding a timestamp)
	DisableTimestamp bool
}

VerboseFormatter gives us very informative output

func (*VerboseFormatter) Format

func (f *VerboseFormatter) Format(entry *logrus.Entry) ([]byte, error)

Format verbosely

type Versions

type Versions struct {
	CompiledAt time.Time `json:"compiledAt,omitempty"`
	GitCommit  string    `json:"gitCommit,omitempty"`
	Version    string    `json:"version,omitempty"`
}

Versions contains GitCommit and Version as a JSON marshall friendly struct.

func GetVersions

func GetVersions() *Versions

GetVersions returns a Versions struct filled with the current values.

func (*Versions) FullVersion

func (v *Versions) FullVersion() string

FullVersion returns the semver version and the git version if available. TODO(mh): I'd like to make the above methods of Versions

Because I'd like to reuse them on `Versions` objects used in updating

Jump to

Keyboard shortcuts

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