util

package
v0.0.0-...-2386a5e Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2015 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	GlobalOptions *Options = NewOptions()
	VersionMajor           = 0
	VersionMinor           = 5
	VersionPatch           = 0
)

Functions

func DirExists

func DirExists(path string) bool

Utility method to determine if a dir (NOT file) exists

func ExecForManyFilesSplitIfRequired

func ExecForManyFilesSplitIfRequired(files []string,
	errorCallback func(args []string, output string, err error) (abort bool),
	name string, baseargs ...string)

Execute 1:n os.exec.Command instances for a list of files, splitting where the command line might get too long. name is the command name as per exec.Command Files are appended to the end of the argument list errorCallback is called for any errors so caller can decide whether to abort

func FileExists

func FileExists(path string) bool

Utility method to determine if a file (NOT dir) exists

func FileExistsAndIsOfSize

func FileExistsAndIsOfSize(path string, sz int64) bool

Utility method to determine if a file/dir exists and is of a specific size

func FileOrDirExists

func FileOrDirExists(path string) (exists bool, isDir bool)

Utility method to determine if a file/dir exists

func FilenamePassesIncludeExcludeFilter

func FilenamePassesIncludeExcludeFilter(filename string, includePaths, excludePaths []string) bool

Return whether a given filename passes the include / exclude path filters Only paths that are in includePaths and outside excludePaths are passed If includePaths is empty that filter always passes and the same with excludePaths Both path lists support wildcard matches

func FormatBytes

func FormatBytes(sz int64) (suffix string, scaled float32)

func FormatFloat

func FormatFloat(f float32) string

func FormatSize

func FormatSize(sz int64) string

Format a number of bytes into a display format

func FormatTransferRate

func FormatTransferRate(bytesPerSecond int64) string

Format a bytes per second transfer rate into a display format

func GetGitDir

func GetGitDir() string

Gets the git data dir of git repository (the .git dir, or where .git file points)

func GetMaxCommandLineArguments

func GetMaxCommandLineArguments() int

Get the maximum number of arguments we want to try passing to the command line

func GetMaxCommandLineLength

func GetMaxCommandLineLength() int

Get the maximum length of a command on the command line

func GetRepoRoot

func GetRepoRoot() (path string, isSeparateGitDir bool, reterr error)

Gets the root folder of this git repository (the one containing .git)

func InitLogging

func InitLogging()

Initialise logging, make sure GlobalOptions is initialised

func IsWindows

func IsWindows() bool

Are we running on Windows? Need to handle some extra path shenanigans

func LoadConfig

func LoadConfig(opts *Options)

Load config from gitconfig and populate opts

func Log

func Log(msgs ...interface{})

Log output message to console and log with newline (if not quiet) You probably don't want to use this since most info messages are for an interactive user only; see util.LogConsole instead for that

func LogAllConsoleOutputToStdErr

func LogAllConsoleOutputToStdErr()

Always send all console output to stderr, including info/debug messages This is mostly useful when stdout is reserved for piping content

func LogConsole

func LogConsole(msgs ...interface{})

Write an informational message to the console with newline (if not quiet), and not the log

func LogConsoleDebug

func LogConsoleDebug(msgs ...interface{})

Write a debug message to the console with newline (if verbose), and not the log

func LogConsoleDebugf

func LogConsoleDebugf(format string, v ...interface{})

Write a debug message to the console (if verbose), and not the log

func LogConsoleError

func LogConsoleError(msgs ...interface{})

Write an error message to the console with newline and not the log

func LogConsoleErrorf

func LogConsoleErrorf(format string, v ...interface{})

Write an error message to the console and not the log

func LogConsoleOverwrite

func LogConsoleOverwrite(newString string, lastLineLength int)

Overwrite the current line in the console (e.g. for progressive update), if not quiet Requires the previous line length so that it can clear it with spaces Does not add a newline after writing

func LogConsoleSpinner

func LogConsoleSpinner(prefix string)

Render a 'spinner' in the console, with optional prefix (which must stay constant between calls unless you clear the line)

func LogConsoleSpinnerFinish

func LogConsoleSpinnerFinish(prefix string)

Finish a spinner progress with a check mark and a newline

func LogConsolef

func LogConsolef(format string, v ...interface{})

Write an informational message to the console (if not quiet), and not the log

func LogDebug

func LogDebug(msgs ...interface{})

Log debug message to console and log with newline (if verbose)

func LogDebugf

func LogDebugf(format string, v ...interface{})

Log debug message to console and log with format (if verbose)

func LogError

func LogError(msgs ...interface{})

Log error message to console and log with newline & spaces in between

func LogErrorf

func LogErrorf(format string, v ...interface{})

Log error to console and log with format (no implicit newline)

func LogSuppressAllConsoleOutput

func LogSuppressAllConsoleOutput()

Suppress all console output

func Logf

func Logf(format string, v ...interface{})

Log output message to console and log with format (if not quiet) You probably don't want to use this since most info messages are for an interactive user only; see LogConsolef instead for that

func MakeRepoFileListRelativeToCwd

func MakeRepoFileListRelativeToCwd(repofiles []string) []string

Make a list of filenames expressed relative to the root of the repo relative to the current working dir. This is useful when needing to call out to git, but the user may be in a subdir of their repo

func ParseSize

func ParseSize(str string) (int64, error)

Parse a string representing a size into a number of bytes supports m/mb = megabytes, g/gb = gigabytes etc (case insensitive)

func ReadConfig

func ReadConfig() map[string]string

Read .gitconfig / .git/config for specific options to override Returns a map of setting=value, where group levels are indicated by dot-notation e.g. git-lob.logfile=blah all keys are converted to lower case for easier matching

func ReadConfigFile

func ReadConfigFile(filepath string) (map[string]string, error)

Read a specific .gitconfig-formatted config file Returns a map of setting=value, where group levels are indicated by dot-notation e.g. git-lob.logfile=blah all keys are converted to lower case for easier matching

func ReadConfigStream

func ReadConfigStream(in io.Reader, dir string) (map[string]string, error)

func ShutDownLogging

func ShutDownLogging()

func StringBinarySearch

func StringBinarySearch(sortedSlice []string, searchTerm string) (bool, int)

Search a sorted slice of strings for a specific string Returns boolean for if found, and either location or insertion point

func StringRemoveDuplicates

func StringRemoveDuplicates(s *[]string)

Remove duplicates from a slice of strings (in place) Linear to logarithmic time, doesn't change the ordering of the slice allocates/frees a new map of up to the size of the slice though

func Version

func Version() string

func WriteConfigFile

func WriteConfigFile(filepath string, contents map[string]string) error

Write a .gitconfig-style config file Takes a map of setting=value, where group levels are indicated by dot-notation e.g. git-lob.logfile=blah Note: overwrites whole file & loses comments if you ReadConfigFile then WriteConfigFile only intended for internal use, don't use on user-edited files This is NOT a merge-on-write user-friendly config updater (like SourceTree has)

func WriteConfigStream

func WriteConfigStream(out io.Writer, contents map[string]string) error

Types

type Options

type Options struct {
	// Help option was requested
	HelpRequested bool
	// Output verbosely (to console & log)
	Verbose bool
	// Output quietly (to console)
	Quiet bool
	// Don't actually perform any tasks
	DryRun bool
	// Never prompt for user input, rely on command line options only
	NonInteractive bool
	// The command to run
	Command string
	// Other value options not converted
	StringOpts map[string]string
	// Other boolean options not converted
	BoolOpts StringSet
	// Other arguments to the command
	Args []string
	// Whether to write output to a log
	LogEnabled bool
	// Log file (optional, defaults to ~/git-lob.log if not specified)
	LogFile string
	// Log verbosely even if main Verbose option is disabled for console
	VerboseLog bool
	// Shared folder in which to store binary files for all repos
	SharedStore string
	// Auto fetch (download) on checkout?
	AutoFetchEnabled bool
	// 'Recent' window in days for fetching all refs (branches/tags) compared to current date
	FetchRefsPeriodDays int
	// 'Recent' window in days for fetching commits on HEAD compared to latest commit date
	FetchCommitsPeriodHEAD int
	// 'Recent' window in days for fetching commits on other branches/tags compared to latest commit date
	FetchCommitsPeriodOther int
	// Retention window in days for refs compared to current date
	RetentionRefsPeriod int
	// Retention window in days for commits on HEAD compared to latest commit date
	RetentionCommitsPeriodHEAD int
	// Retention window in days for commits on other branches/tags compared to latest commit date
	RetentionCommitsPeriodOther int
	// The remote to check for unpushed commits before pruning ('*' means 'any')
	PruneRemote string
	// Whether to always operate prune old in safe mode
	PruneSafeMode bool
	// List of paths to include when fetching
	FetchIncludePaths []string
	// List of paths to exclude when fetching
	FetchExcludePaths []string
	// Size above which we'll try to download deltas on fetch (smart servers only)
	FetchDeltasAboveSize int64
	// Size above which we'll try to upload deltas on push (smart servers only)
	PushDeltasAboveSize int64
	// The command to run over SSH on a remote smart server to push/pull (default "git-lob-server")
	SSHServerCommand string
	// Combination of root .gitconfig and repository config as map
	GitConfig map[string]string
}

Options (command line or config file) Only general options, command-specific ones dealt with in commands

func NewOptions

func NewOptions() *Options

type ProgressCallback

type ProgressCallback func(data *ProgressCallbackData) (abort bool)

Callback when progress is made during process return true to abort the (entire) process

type ProgressCallbackData

type ProgressCallbackData struct {
	// What stage of the process this is for, preparing, transferring or skipping something
	Type ProgressCallbackType
	// Either a general message or an item name (e.g. file name in download stage)
	Desc string
	// If applicable, how many bytes transferred for this item
	ItemBytesDone int64
	// If applicable, how many bytes comprise this item
	ItemBytes int64
	// The number of bytes transferred for all items
	TotalBytesDone int64
	// The number of bytes needed to transfer all of this process
	TotalBytes int64
}

Collected callback data for a progress operation

type ProgressCallbackType

type ProgressCallbackType int
const (
	// Process is figuring out what to do
	ProgressCalculate ProgressCallbackType = iota
	// Process is transferring data
	ProgressTransferBytes ProgressCallbackType = iota
	// Process is skipping data because it's already up to date
	ProgressSkip ProgressCallbackType = iota
	// Process did not find the requested data, moving on
	ProgressNotFound ProgressCallbackType = iota
	// Non-fatal error
	ProgressError ProgressCallbackType = iota
)

type ProgressResults

type ProgressResults struct {
	// Items transferred fully
	TransferredCount int
	// Items skipped (not needed)
	SkippedCount int
	// Items that failed (but did not stop process)
	ErrorCount int
	// Items which were not found in source
	NotFoundCount int
}

Summarised results of some progress action

func ReportProgressToConsole

func ReportProgressToConsole(callbackChan <-chan *ProgressCallbackData, op string, freq time.Duration) *ProgressResults

Function to periodically (based on freq) report progress of a transfer process to the console callbackChan must be a channel of updates which is being populated with ProgressCallbackData from a goroutine at an unknown frequency. This function will then print updates every freq seconds of the updates received so far, collapsing duplicates (in the case of very frequent transfer updates) and filling in the blanks with an updated transfer rate in the case of no updates in the time.

type StringSet

type StringSet map[string]struct{}

The primary type that represents a set

func NewStringSet

func NewStringSet() StringSet

Creates and returns a reference to an empty set.

func NewStringSetFromSlice

func NewStringSetFromSlice(s []string) StringSet

Creates and returns a reference to a set from an existing slice

func (StringSet) Add

func (set StringSet) Add(i string) bool

Adds an item to the current set if it doesn't already exist in the set.

func (StringSet) Cardinality

func (set StringSet) Cardinality() int

Cardinality returns how many items are currently in the set.

func (*StringSet) Clear

func (set *StringSet) Clear()

Clears the entire set to be the empty set.

func (StringSet) Clone

func (set StringSet) Clone() StringSet

Returns a clone of the set. Does NOT clone the underlying elements.

func (StringSet) Contains

func (set StringSet) Contains(i string) bool

Determines if a given item is already in the set.

func (StringSet) ContainsAll

func (set StringSet) ContainsAll(i ...string) bool

Determines if the given items are all in the set

func (StringSet) Difference

func (set StringSet) Difference(other StringSet) StringSet

Returns a new set with items in the current set but not in the other set

func (StringSet) Equal

func (set StringSet) Equal(other StringSet) bool

Equal determines if two sets are equal to each other. If they both are the same size and have the same items they are considered equal. Order of items is not relevent for sets to be equal.

func (StringSet) Intersect

func (set StringSet) Intersect(other StringSet) StringSet

Returns a new set with items that exist only in both sets.

func (StringSet) IsSubset

func (set StringSet) IsSubset(other StringSet) bool

Determines if every item in the other set is in this set.

func (StringSet) IsSuperset

func (set StringSet) IsSuperset(other StringSet) bool

Determines if every item of this set is in the other set.

func (StringSet) Iter

func (set StringSet) Iter() <-chan string

Iter() returns a channel of type string that you can range over.

func (StringSet) Remove

func (set StringSet) Remove(i string)

Allows the removal of a single item in the set.

func (StringSet) SymmetricDifference

func (set StringSet) SymmetricDifference(other StringSet) StringSet

Returns a new set with items in the current set or the other set but not in both.

func (StringSet) Union

func (set StringSet) Union(other StringSet) StringSet

Returns a new set with all items in both sets.

type TransferRateCalculator

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

Calculates transfer rates by averaging over n samples

func NewTransferRateCalculator

func NewTransferRateCalculator(numSamples int) *TransferRateCalculator

func (*TransferRateCalculator) AddSample

func (t *TransferRateCalculator) AddSample(bytesPerSecond int64)

func (*TransferRateCalculator) Average

func (t *TransferRateCalculator) Average() int64

Jump to

Keyboard shortcuts

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