repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_js.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_js.go
// +build js package logrus func isTerminal(fd int) bool { return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go
// +build appengine package logrus import ( "io" ) func checkIfTerminal(w io.Writer) bool { return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/entry.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/entry.go
package logrus import ( "bytes" "context" "fmt" "os" "reflect" "runtime" "strings" "sync" "time" ) var ( // qualified package name, cached at first use logrusPackage string // Positions in the call stack when tracing to report the calling method minimumCallerDepth int // Used for caller information initialisation callerInitOnce sync.Once ) const ( maximumCallerDepth int = 25 knownLogrusFrames int = 4 ) func init() { // start at the bottom of the stack before the package-name cache is primed minimumCallerDepth = 1 } // Defines the key when adding errors using WithError. var ErrorKey = "error" // An entry is the final or intermediate Logrus logging entry. It contains all // the fields passed with WithField{,s}. It's finally logged when Trace, Debug, // Info, Warn, Error, Fatal or Panic is called on it. These objects can be // reused and passed around as much as you wish to avoid field duplication. type Entry struct { Logger *Logger // Contains all the fields set by the user. Data Fields // Time at which the log entry was created Time time.Time // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic // This field will be set on entry firing and the value will be equal to the one in Logger struct field. Level Level // Calling method, with package name Caller *runtime.Frame // Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic Message string // When formatter is called in entry.log(), a Buffer may be set to entry Buffer *bytes.Buffer // Contains the context set by the user. Useful for hook processing etc. Context context.Context // err may contain a field formatting error err string } func NewEntry(logger *Logger) *Entry { return &Entry{ Logger: logger, // Default is three fields, plus one optional. Give a little extra room. Data: make(Fields, 6), } } func (entry *Entry) Dup() *Entry { data := make(Fields, len(entry.Data)) for k, v := range entry.Data { data[k] = v } return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err} } // Returns the bytes representation of this entry from the formatter. func (entry *Entry) Bytes() ([]byte, error) { return entry.Logger.Formatter.Format(entry) } // Returns the string representation from the reader and ultimately the // formatter. func (entry *Entry) String() (string, error) { serialized, err := entry.Bytes() if err != nil { return "", err } str := string(serialized) return str, nil } // Add an error as single field (using the key defined in ErrorKey) to the Entry. func (entry *Entry) WithError(err error) *Entry { return entry.WithField(ErrorKey, err) } // Add a context to the Entry. func (entry *Entry) WithContext(ctx context.Context) *Entry { dataCopy := make(Fields, len(entry.Data)) for k, v := range entry.Data { dataCopy[k] = v } return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx} } // Add a single field to the Entry. func (entry *Entry) WithField(key string, value interface{}) *Entry { return entry.WithFields(Fields{key: value}) } // Add a map of fields to the Entry. func (entry *Entry) WithFields(fields Fields) *Entry { data := make(Fields, len(entry.Data)+len(fields)) for k, v := range entry.Data { data[k] = v } fieldErr := entry.err for k, v := range fields { isErrField := false if t := reflect.TypeOf(v); t != nil { switch { case t.Kind() == reflect.Func, t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func: isErrField = true } } if isErrField { tmp := fmt.Sprintf("can not add field %q", k) if fieldErr != "" { fieldErr = entry.err + ", " + tmp } else { fieldErr = tmp } } else { data[k] = v } } return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context} } // Overrides the time of the Entry. func (entry *Entry) WithTime(t time.Time) *Entry { dataCopy := make(Fields, len(entry.Data)) for k, v := range entry.Data { dataCopy[k] = v } return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context} } // getPackageName reduces a fully qualified function name to the package name // There really ought to be to be a better way... func getPackageName(f string) string { for { lastPeriod := strings.LastIndex(f, ".") lastSlash := strings.LastIndex(f, "/") if lastPeriod > lastSlash { f = f[:lastPeriod] } else { break } } return f } // getCaller retrieves the name of the first non-logrus calling function func getCaller() *runtime.Frame { // cache this package's fully-qualified name callerInitOnce.Do(func() { pcs := make([]uintptr, maximumCallerDepth) _ = runtime.Callers(0, pcs) // dynamic get the package name and the minimum caller depth for i := 0; i < maximumCallerDepth; i++ { funcName := runtime.FuncForPC(pcs[i]).Name() if strings.Contains(funcName, "getCaller") { logrusPackage = getPackageName(funcName) break } } minimumCallerDepth = knownLogrusFrames }) // Restrict the lookback frames to avoid runaway lookups pcs := make([]uintptr, maximumCallerDepth) depth := runtime.Callers(minimumCallerDepth, pcs) frames := runtime.CallersFrames(pcs[:depth]) for f, again := frames.Next(); again; f, again = frames.Next() { pkg := getPackageName(f.Function) // If the caller isn't part of this package, we're done if pkg != logrusPackage { return &f //nolint:scopelint } } // if we got here, we failed to find the caller's context return nil } func (entry Entry) HasCaller() (has bool) { return entry.Logger != nil && entry.Logger.ReportCaller && entry.Caller != nil } func (entry *Entry) log(level Level, msg string) { var buffer *bytes.Buffer newEntry := entry.Dup() if newEntry.Time.IsZero() { newEntry.Time = time.Now() } newEntry.Level = level newEntry.Message = msg newEntry.Logger.mu.Lock() reportCaller := newEntry.Logger.ReportCaller bufPool := newEntry.getBufferPool() newEntry.Logger.mu.Unlock() if reportCaller { newEntry.Caller = getCaller() } newEntry.fireHooks() buffer = bufPool.Get() defer func() { newEntry.Buffer = nil buffer.Reset() bufPool.Put(buffer) }() buffer.Reset() newEntry.Buffer = buffer newEntry.write() newEntry.Buffer = nil // To avoid Entry#log() returning a value that only would make sense for // panic() to use in Entry#Panic(), we avoid the allocation by checking // directly here. if level <= PanicLevel { panic(newEntry) } } func (entry *Entry) getBufferPool() (pool BufferPool) { if entry.Logger.BufferPool != nil { return entry.Logger.BufferPool } return bufferPool } func (entry *Entry) fireHooks() { var tmpHooks LevelHooks entry.Logger.mu.Lock() tmpHooks = make(LevelHooks, len(entry.Logger.Hooks)) for k, v := range entry.Logger.Hooks { tmpHooks[k] = v } entry.Logger.mu.Unlock() err := tmpHooks.Fire(entry.Level, entry) if err != nil { fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) } } func (entry *Entry) write() { entry.Logger.mu.Lock() defer entry.Logger.mu.Unlock() serialized, err := entry.Logger.Formatter.Format(entry) if err != nil { fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) return } if _, err := entry.Logger.Out.Write(serialized); err != nil { fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) } } // Log will log a message at the level given as parameter. // Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. // For this behaviour Entry.Panic or Entry.Fatal should be used instead. func (entry *Entry) Log(level Level, args ...interface{}) { if entry.Logger.IsLevelEnabled(level) { entry.log(level, fmt.Sprint(args...)) } } func (entry *Entry) Trace(args ...interface{}) { entry.Log(TraceLevel, args...) } func (entry *Entry) Debug(args ...interface{}) { entry.Log(DebugLevel, args...) } func (entry *Entry) Print(args ...interface{}) { entry.Info(args...) } func (entry *Entry) Info(args ...interface{}) { entry.Log(InfoLevel, args...) } func (entry *Entry) Warn(args ...interface{}) { entry.Log(WarnLevel, args...) } func (entry *Entry) Warning(args ...interface{}) { entry.Warn(args...) } func (entry *Entry) Error(args ...interface{}) { entry.Log(ErrorLevel, args...) } func (entry *Entry) Fatal(args ...interface{}) { entry.Log(FatalLevel, args...) entry.Logger.Exit(1) } func (entry *Entry) Panic(args ...interface{}) { entry.Log(PanicLevel, args...) } // Entry Printf family functions func (entry *Entry) Logf(level Level, format string, args ...interface{}) { if entry.Logger.IsLevelEnabled(level) { entry.Log(level, fmt.Sprintf(format, args...)) } } func (entry *Entry) Tracef(format string, args ...interface{}) { entry.Logf(TraceLevel, format, args...) } func (entry *Entry) Debugf(format string, args ...interface{}) { entry.Logf(DebugLevel, format, args...) } func (entry *Entry) Infof(format string, args ...interface{}) { entry.Logf(InfoLevel, format, args...) } func (entry *Entry) Printf(format string, args ...interface{}) { entry.Infof(format, args...) } func (entry *Entry) Warnf(format string, args ...interface{}) { entry.Logf(WarnLevel, format, args...) } func (entry *Entry) Warningf(format string, args ...interface{}) { entry.Warnf(format, args...) } func (entry *Entry) Errorf(format string, args ...interface{}) { entry.Logf(ErrorLevel, format, args...) } func (entry *Entry) Fatalf(format string, args ...interface{}) { entry.Logf(FatalLevel, format, args...) entry.Logger.Exit(1) } func (entry *Entry) Panicf(format string, args ...interface{}) { entry.Logf(PanicLevel, format, args...) } // Entry Println family functions func (entry *Entry) Logln(level Level, args ...interface{}) { if entry.Logger.IsLevelEnabled(level) { entry.Log(level, entry.sprintlnn(args...)) } } func (entry *Entry) Traceln(args ...interface{}) { entry.Logln(TraceLevel, args...) } func (entry *Entry) Debugln(args ...interface{}) { entry.Logln(DebugLevel, args...) } func (entry *Entry) Infoln(args ...interface{}) { entry.Logln(InfoLevel, args...) } func (entry *Entry) Println(args ...interface{}) { entry.Infoln(args...) } func (entry *Entry) Warnln(args ...interface{}) { entry.Logln(WarnLevel, args...) } func (entry *Entry) Warningln(args ...interface{}) { entry.Warnln(args...) } func (entry *Entry) Errorln(args ...interface{}) { entry.Logln(ErrorLevel, args...) } func (entry *Entry) Fatalln(args ...interface{}) { entry.Logln(FatalLevel, args...) entry.Logger.Exit(1) } func (entry *Entry) Panicln(args ...interface{}) { entry.Logln(PanicLevel, args...) } // Sprintlnn => Sprint no newline. This is to get the behavior of how // fmt.Sprintln where spaces are always added between operands, regardless of // their type. Instead of vendoring the Sprintln implementation to spare a // string allocation, we do the simplest thing. func (entry *Entry) sprintlnn(args ...interface{}) string { msg := fmt.Sprintln(args...) return msg[:len(msg)-1] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/logrus.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/logrus.go
package logrus import ( "fmt" "log" "strings" ) // Fields type, used to pass to `WithFields`. type Fields map[string]interface{} // Level type type Level uint32 // Convert the Level to a string. E.g. PanicLevel becomes "panic". func (level Level) String() string { if b, err := level.MarshalText(); err == nil { return string(b) } else { return "unknown" } } // ParseLevel takes a string level and returns the Logrus log level constant. func ParseLevel(lvl string) (Level, error) { switch strings.ToLower(lvl) { case "panic": return PanicLevel, nil case "fatal": return FatalLevel, nil case "error": return ErrorLevel, nil case "warn", "warning": return WarnLevel, nil case "info": return InfoLevel, nil case "debug": return DebugLevel, nil case "trace": return TraceLevel, nil } var l Level return l, fmt.Errorf("not a valid logrus Level: %q", lvl) } // UnmarshalText implements encoding.TextUnmarshaler. func (level *Level) UnmarshalText(text []byte) error { l, err := ParseLevel(string(text)) if err != nil { return err } *level = l return nil } func (level Level) MarshalText() ([]byte, error) { switch level { case TraceLevel: return []byte("trace"), nil case DebugLevel: return []byte("debug"), nil case InfoLevel: return []byte("info"), nil case WarnLevel: return []byte("warning"), nil case ErrorLevel: return []byte("error"), nil case FatalLevel: return []byte("fatal"), nil case PanicLevel: return []byte("panic"), nil } return nil, fmt.Errorf("not a valid logrus level %d", level) } // A constant exposing all logging levels var AllLevels = []Level{ PanicLevel, FatalLevel, ErrorLevel, WarnLevel, InfoLevel, DebugLevel, TraceLevel, } // These are the different logging levels. You can set the logging level to log // on your instance of logger, obtained with `logrus.New()`. const ( // PanicLevel level, highest level of severity. Logs and then calls panic with the // message passed to Debug, Info, ... PanicLevel Level = iota // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the // logging level is set to Panic. FatalLevel // ErrorLevel level. Logs. Used for errors that should definitely be noted. // Commonly used for hooks to send errors to an error tracking service. ErrorLevel // WarnLevel level. Non-critical entries that deserve eyes. WarnLevel // InfoLevel level. General operational entries about what's going on inside the // application. InfoLevel // DebugLevel level. Usually only enabled when debugging. Very verbose logging. DebugLevel // TraceLevel level. Designates finer-grained informational events than the Debug. TraceLevel ) // Won't compile if StdLogger can't be realized by a log.Logger var ( _ StdLogger = &log.Logger{} _ StdLogger = &Entry{} _ StdLogger = &Logger{} ) // StdLogger is what your logrus-enabled library should take, that way // it'll accept a stdlib logger and a logrus logger. There's no standard // interface, this is the closest we get, unfortunately. type StdLogger interface { Print(...interface{}) Printf(string, ...interface{}) Println(...interface{}) Fatal(...interface{}) Fatalf(string, ...interface{}) Fatalln(...interface{}) Panic(...interface{}) Panicf(string, ...interface{}) Panicln(...interface{}) } // The FieldLogger interface generalizes the Entry and Logger types type FieldLogger interface { WithField(key string, value interface{}) *Entry WithFields(fields Fields) *Entry WithError(err error) *Entry Debugf(format string, args ...interface{}) Infof(format string, args ...interface{}) Printf(format string, args ...interface{}) Warnf(format string, args ...interface{}) Warningf(format string, args ...interface{}) Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) Panicf(format string, args ...interface{}) Debug(args ...interface{}) Info(args ...interface{}) Print(args ...interface{}) Warn(args ...interface{}) Warning(args ...interface{}) Error(args ...interface{}) Fatal(args ...interface{}) Panic(args ...interface{}) Debugln(args ...interface{}) Infoln(args ...interface{}) Println(args ...interface{}) Warnln(args ...interface{}) Warningln(args ...interface{}) Errorln(args ...interface{}) Fatalln(args ...interface{}) Panicln(args ...interface{}) // IsDebugEnabled() bool // IsInfoEnabled() bool // IsWarnEnabled() bool // IsErrorEnabled() bool // IsFatalEnabled() bool // IsPanicEnabled() bool } // Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is // here for consistancy. Do not use. Use Logger or Entry instead. type Ext1FieldLogger interface { FieldLogger Tracef(format string, args ...interface{}) Trace(args ...interface{}) Traceln(args ...interface{}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go
// +build js nacl plan9 package logrus import ( "io" ) func checkIfTerminal(w io.Writer) bool { return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/writer.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/writer.go
package logrus import ( "bufio" "io" "runtime" "strings" ) // Writer at INFO level. See WriterLevel for details. func (logger *Logger) Writer() *io.PipeWriter { return logger.WriterLevel(InfoLevel) } // WriterLevel returns an io.Writer that can be used to write arbitrary text to // the logger at the given log level. Each line written to the writer will be // printed in the usual way using formatters and hooks. The writer is part of an // io.Pipe and it is the callers responsibility to close the writer when done. // This can be used to override the standard library logger easily. func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { return NewEntry(logger).WriterLevel(level) } // Writer returns an io.Writer that writes to the logger at the info log level func (entry *Entry) Writer() *io.PipeWriter { return entry.WriterLevel(InfoLevel) } // WriterLevel returns an io.Writer that writes to the logger at the given log level func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { reader, writer := io.Pipe() var printFunc func(args ...interface{}) // Determine which log function to use based on the specified log level switch level { case TraceLevel: printFunc = entry.Trace case DebugLevel: printFunc = entry.Debug case InfoLevel: printFunc = entry.Info case WarnLevel: printFunc = entry.Warn case ErrorLevel: printFunc = entry.Error case FatalLevel: printFunc = entry.Fatal case PanicLevel: printFunc = entry.Panic default: printFunc = entry.Print } // Start a new goroutine to scan the input and write it to the logger using the specified print function. // It splits the input into chunks of up to 64KB to avoid buffer overflows. go entry.writerScanner(reader, printFunc) // Set a finalizer function to close the writer when it is garbage collected runtime.SetFinalizer(writer, writerFinalizer) return writer } // writerScanner scans the input from the reader and writes it to the logger func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { scanner := bufio.NewScanner(reader) // Set the buffer size to the maximum token size to avoid buffer overflows scanner.Buffer(make([]byte, bufio.MaxScanTokenSize), bufio.MaxScanTokenSize) // Define a split function to split the input into chunks of up to 64KB chunkSize := bufio.MaxScanTokenSize // 64KB splitFunc := func(data []byte, atEOF bool) (int, []byte, error) { if len(data) >= chunkSize { return chunkSize, data[:chunkSize], nil } return bufio.ScanLines(data, atEOF) } // Use the custom split function to split the input scanner.Split(splitFunc) // Scan the input and write it to the logger using the specified print function for scanner.Scan() { printFunc(strings.TrimRight(scanner.Text(), "\r\n")) } // If there was an error while scanning the input, log an error if err := scanner.Err(); err != nil { entry.Errorf("Error while reading from Writer: %s", err) } // Close the reader when we are done reader.Close() } // WriterFinalizer is a finalizer function that closes then given writer when it is garbage collected func writerFinalizer(writer *io.PipeWriter) { writer.Close() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_windows.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_windows.go
// +build !appengine,!js,windows package logrus import ( "io" "os" "golang.org/x/sys/windows" ) func checkIfTerminal(w io.Writer) bool { switch v := w.(type) { case *os.File: handle := windows.Handle(v.Fd()) var mode uint32 if err := windows.GetConsoleMode(handle, &mode); err != nil { return false } mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING if err := windows.SetConsoleMode(handle, mode); err != nil { return false } return true } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/formatter.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/formatter.go
package logrus import "time" // Default key names for the default fields const ( defaultTimestampFormat = time.RFC3339 FieldKeyMsg = "msg" FieldKeyLevel = "level" FieldKeyTime = "time" FieldKeyLogrusError = "logrus_error" FieldKeyFunc = "func" FieldKeyFile = "file" ) // The Formatter interface is used to implement a custom Formatter. It takes an // `Entry`. It exposes all the fields, including the default ones: // // * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. // * `entry.Data["time"]`. The timestamp. // * `entry.Data["level"]. The level the entry was logged at. // // Any additional fields added with `WithField` or `WithFields` are also in // `entry.Data`. Format is expected to return an array of bytes which are then // logged to `logger.Out`. type Formatter interface { Format(*Entry) ([]byte, error) } // This is to not silently overwrite `time`, `msg`, `func` and `level` fields when // dumping it. If this code wasn't there doing: // // logrus.WithField("level", 1).Info("hello") // // Would just silently drop the user provided level. Instead with this code // it'll logged as: // // {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} // // It's not exported because it's still using Data in an opinionated way. It's to // avoid code duplication between the two default formatters. func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) { timeKey := fieldMap.resolve(FieldKeyTime) if t, ok := data[timeKey]; ok { data["fields."+timeKey] = t delete(data, timeKey) } msgKey := fieldMap.resolve(FieldKeyMsg) if m, ok := data[msgKey]; ok { data["fields."+msgKey] = m delete(data, msgKey) } levelKey := fieldMap.resolve(FieldKeyLevel) if l, ok := data[levelKey]; ok { data["fields."+levelKey] = l delete(data, levelKey) } logrusErrKey := fieldMap.resolve(FieldKeyLogrusError) if l, ok := data[logrusErrKey]; ok { data["fields."+logrusErrKey] = l delete(data, logrusErrKey) } // If reportCaller is not set, 'func' will not conflict. if reportCaller { funcKey := fieldMap.resolve(FieldKeyFunc) if l, ok := data[funcKey]; ok { data["fields."+funcKey] = l } fileKey := fieldMap.resolve(FieldKeyFile) if l, ok := data[fileKey]; ok { data["fields."+fileKey] = l } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/buffer_pool.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/buffer_pool.go
package logrus import ( "bytes" "sync" ) var ( bufferPool BufferPool ) type BufferPool interface { Put(*bytes.Buffer) Get() *bytes.Buffer } type defaultPool struct { pool *sync.Pool } func (p *defaultPool) Put(buf *bytes.Buffer) { p.pool.Put(buf) } func (p *defaultPool) Get() *bytes.Buffer { return p.pool.Get().(*bytes.Buffer) } // SetBufferPool allows to replace the default logrus buffer pool // to better meets the specific needs of an application. func SetBufferPool(bp BufferPool) { bufferPool = bp } func init() { SetBufferPool(&defaultPool{ pool: &sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, }, }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/alt_exit.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/alt_exit.go
package logrus // The following code was sourced and modified from the // https://github.com/tebeka/atexit package governed by the following license: // // Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import ( "fmt" "os" ) var handlers = []func(){} func runHandler(handler func()) { defer func() { if err := recover(); err != nil { fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) } }() handler() } func runHandlers() { for _, handler := range handlers { runHandler(handler) } } // Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) func Exit(code int) { runHandlers() os.Exit(code) } // RegisterExitHandler appends a Logrus Exit handler to the list of handlers, // call logrus.Exit to invoke all handlers. The handlers will also be invoked when // any Fatal log entry is made. // // This method is useful when a caller wishes to use logrus to log a fatal // message but also needs to gracefully shutdown. An example usecase could be // closing database connections, or sending a alert that the application is // closing. func RegisterExitHandler(handler func()) { handlers = append(handlers, handler) } // DeferExitHandler prepends a Logrus Exit handler to the list of handlers, // call logrus.Exit to invoke all handlers. The handlers will also be invoked when // any Fatal log entry is made. // // This method is useful when a caller wishes to use logrus to log a fatal // message but also needs to gracefully shutdown. An example usecase could be // closing database connections, or sending a alert that the application is // closing. func DeferExitHandler(handler func()) { handlers = append([]func(){handler}, handlers...) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/hooks.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/hooks.go
package logrus // A hook to be fired when logging on the logging levels returned from // `Levels()` on your implementation of the interface. Note that this is not // fired in a goroutine or a channel with workers, you should handle such // functionality yourself if your call is non-blocking and you don't wish for // the logging calls for levels returned from `Levels()` to block. type Hook interface { Levels() []Level Fire(*Entry) error } // Internal type for storing the hooks on a logger instance. type LevelHooks map[Level][]Hook // Add a hook to an instance of logger. This is called with // `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. func (hooks LevelHooks) Add(hook Hook) { for _, level := range hook.Levels() { hooks[level] = append(hooks[level], hook) } } // Fire all the hooks for the passed level. Used by `entry.log` to fire // appropriate hooks for a log entry. func (hooks LevelHooks) Fire(level Level, entry *Entry) error { for _, hook := range hooks[level] { if err := hook.Fire(entry); err != nil { return err } } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go
// +build darwin dragonfly freebsd netbsd openbsd // +build !js package logrus import "golang.org/x/sys/unix" const ioctlReadTermios = unix.TIOCGETA func isTerminal(fd int) bool { _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) return err == nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_unix.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_unix.go
// +build linux aix zos // +build !js package logrus import "golang.org/x/sys/unix" const ioctlReadTermios = unix.TCGETS func isTerminal(fd int) bool { _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) return err == nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/exported.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/exported.go
package logrus import ( "context" "io" "time" ) var ( // std is the name of the standard logger in stdlib `log` std = New() ) func StandardLogger() *Logger { return std } // SetOutput sets the standard logger output. func SetOutput(out io.Writer) { std.SetOutput(out) } // SetFormatter sets the standard logger formatter. func SetFormatter(formatter Formatter) { std.SetFormatter(formatter) } // SetReportCaller sets whether the standard logger will include the calling // method as a field. func SetReportCaller(include bool) { std.SetReportCaller(include) } // SetLevel sets the standard logger level. func SetLevel(level Level) { std.SetLevel(level) } // GetLevel returns the standard logger level. func GetLevel() Level { return std.GetLevel() } // IsLevelEnabled checks if the log level of the standard logger is greater than the level param func IsLevelEnabled(level Level) bool { return std.IsLevelEnabled(level) } // AddHook adds a hook to the standard logger hooks. func AddHook(hook Hook) { std.AddHook(hook) } // WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. func WithError(err error) *Entry { return std.WithField(ErrorKey, err) } // WithContext creates an entry from the standard logger and adds a context to it. func WithContext(ctx context.Context) *Entry { return std.WithContext(ctx) } // WithField creates an entry from the standard logger and adds a field to // it. If you want multiple fields, use `WithFields`. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithField(key string, value interface{}) *Entry { return std.WithField(key, value) } // WithFields creates an entry from the standard logger and adds multiple // fields to it. This is simply a helper for `WithField`, invoking it // once for each field. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithFields(fields Fields) *Entry { return std.WithFields(fields) } // WithTime creates an entry from the standard logger and overrides the time of // logs generated with it. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the Entry it returns. func WithTime(t time.Time) *Entry { return std.WithTime(t) } // Trace logs a message at level Trace on the standard logger. func Trace(args ...interface{}) { std.Trace(args...) } // Debug logs a message at level Debug on the standard logger. func Debug(args ...interface{}) { std.Debug(args...) } // Print logs a message at level Info on the standard logger. func Print(args ...interface{}) { std.Print(args...) } // Info logs a message at level Info on the standard logger. func Info(args ...interface{}) { std.Info(args...) } // Warn logs a message at level Warn on the standard logger. func Warn(args ...interface{}) { std.Warn(args...) } // Warning logs a message at level Warn on the standard logger. func Warning(args ...interface{}) { std.Warning(args...) } // Error logs a message at level Error on the standard logger. func Error(args ...interface{}) { std.Error(args...) } // Panic logs a message at level Panic on the standard logger. func Panic(args ...interface{}) { std.Panic(args...) } // Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatal(args ...interface{}) { std.Fatal(args...) } // TraceFn logs a message from a func at level Trace on the standard logger. func TraceFn(fn LogFunction) { std.TraceFn(fn) } // DebugFn logs a message from a func at level Debug on the standard logger. func DebugFn(fn LogFunction) { std.DebugFn(fn) } // PrintFn logs a message from a func at level Info on the standard logger. func PrintFn(fn LogFunction) { std.PrintFn(fn) } // InfoFn logs a message from a func at level Info on the standard logger. func InfoFn(fn LogFunction) { std.InfoFn(fn) } // WarnFn logs a message from a func at level Warn on the standard logger. func WarnFn(fn LogFunction) { std.WarnFn(fn) } // WarningFn logs a message from a func at level Warn on the standard logger. func WarningFn(fn LogFunction) { std.WarningFn(fn) } // ErrorFn logs a message from a func at level Error on the standard logger. func ErrorFn(fn LogFunction) { std.ErrorFn(fn) } // PanicFn logs a message from a func at level Panic on the standard logger. func PanicFn(fn LogFunction) { std.PanicFn(fn) } // FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1. func FatalFn(fn LogFunction) { std.FatalFn(fn) } // Tracef logs a message at level Trace on the standard logger. func Tracef(format string, args ...interface{}) { std.Tracef(format, args...) } // Debugf logs a message at level Debug on the standard logger. func Debugf(format string, args ...interface{}) { std.Debugf(format, args...) } // Printf logs a message at level Info on the standard logger. func Printf(format string, args ...interface{}) { std.Printf(format, args...) } // Infof logs a message at level Info on the standard logger. func Infof(format string, args ...interface{}) { std.Infof(format, args...) } // Warnf logs a message at level Warn on the standard logger. func Warnf(format string, args ...interface{}) { std.Warnf(format, args...) } // Warningf logs a message at level Warn on the standard logger. func Warningf(format string, args ...interface{}) { std.Warningf(format, args...) } // Errorf logs a message at level Error on the standard logger. func Errorf(format string, args ...interface{}) { std.Errorf(format, args...) } // Panicf logs a message at level Panic on the standard logger. func Panicf(format string, args ...interface{}) { std.Panicf(format, args...) } // Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatalf(format string, args ...interface{}) { std.Fatalf(format, args...) } // Traceln logs a message at level Trace on the standard logger. func Traceln(args ...interface{}) { std.Traceln(args...) } // Debugln logs a message at level Debug on the standard logger. func Debugln(args ...interface{}) { std.Debugln(args...) } // Println logs a message at level Info on the standard logger. func Println(args ...interface{}) { std.Println(args...) } // Infoln logs a message at level Info on the standard logger. func Infoln(args ...interface{}) { std.Infoln(args...) } // Warnln logs a message at level Warn on the standard logger. func Warnln(args ...interface{}) { std.Warnln(args...) } // Warningln logs a message at level Warn on the standard logger. func Warningln(args ...interface{}) { std.Warningln(args...) } // Errorln logs a message at level Error on the standard logger. func Errorln(args ...interface{}) { std.Errorln(args...) } // Panicln logs a message at level Panic on the standard logger. func Panicln(args ...interface{}) { std.Panicln(args...) } // Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1. func Fatalln(args ...interface{}) { std.Fatalln(args...) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/doc.go
/* Package logrus is a structured logger for Go, completely API compatible with the standard library logger. The simplest way to use Logrus is simply the package-level exported logger: package main import ( log "github.com/sirupsen/logrus" ) func main() { log.WithFields(log.Fields{ "animal": "walrus", "number": 1, "size": 10, }).Info("A walrus appears") } Output: time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 For a full guide visit https://github.com/sirupsen/logrus */ package logrus
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/logger.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/logger.go
package logrus import ( "context" "io" "os" "sync" "sync/atomic" "time" ) // LogFunction For big messages, it can be more efficient to pass a function // and only call it if the log level is actually enables rather than // generating the log message and then checking if the level is enabled type LogFunction func() []interface{} type Logger struct { // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a // file, or leave it default which is `os.Stderr`. You can also set this to // something more adventurous, such as logging to Kafka. Out io.Writer // Hooks for the logger instance. These allow firing events based on logging // levels and log entries. For example, to send errors to an error tracking // service, log to StatsD or dump the core on fatal errors. Hooks LevelHooks // All log entries pass through the formatter before logged to Out. The // included formatters are `TextFormatter` and `JSONFormatter` for which // TextFormatter is the default. In development (when a TTY is attached) it // logs with colors, but to a file it wouldn't. You can easily implement your // own that implements the `Formatter` interface, see the `README` or included // formatters for examples. Formatter Formatter // Flag for whether to log caller info (off by default) ReportCaller bool // The logging level the logger should log at. This is typically (and defaults // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be // logged. Level Level // Used to sync writing to the log. Locking is enabled by Default mu MutexWrap // Reusable empty entry entryPool sync.Pool // Function to exit the application, defaults to `os.Exit()` ExitFunc exitFunc // The buffer pool used to format the log. If it is nil, the default global // buffer pool will be used. BufferPool BufferPool } type exitFunc func(int) type MutexWrap struct { lock sync.Mutex disabled bool } func (mw *MutexWrap) Lock() { if !mw.disabled { mw.lock.Lock() } } func (mw *MutexWrap) Unlock() { if !mw.disabled { mw.lock.Unlock() } } func (mw *MutexWrap) Disable() { mw.disabled = true } // Creates a new logger. Configuration should be set by changing `Formatter`, // `Out` and `Hooks` directly on the default logger instance. You can also just // instantiate your own: // // var log = &logrus.Logger{ // Out: os.Stderr, // Formatter: new(logrus.TextFormatter), // Hooks: make(logrus.LevelHooks), // Level: logrus.DebugLevel, // } // // It's recommended to make this a global instance called `log`. func New() *Logger { return &Logger{ Out: os.Stderr, Formatter: new(TextFormatter), Hooks: make(LevelHooks), Level: InfoLevel, ExitFunc: os.Exit, ReportCaller: false, } } func (logger *Logger) newEntry() *Entry { entry, ok := logger.entryPool.Get().(*Entry) if ok { return entry } return NewEntry(logger) } func (logger *Logger) releaseEntry(entry *Entry) { entry.Data = map[string]interface{}{} logger.entryPool.Put(entry) } // WithField allocates a new entry and adds a field to it. // Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to // this new returned entry. // If you want multiple fields, use `WithFields`. func (logger *Logger) WithField(key string, value interface{}) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithField(key, value) } // Adds a struct of fields to the log entry. All it does is call `WithField` for // each `Field`. func (logger *Logger) WithFields(fields Fields) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithFields(fields) } // Add an error as single field to the log entry. All it does is call // `WithError` for the given `error`. func (logger *Logger) WithError(err error) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithError(err) } // Add a context to the log entry. func (logger *Logger) WithContext(ctx context.Context) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithContext(ctx) } // Overrides the time of the log entry. func (logger *Logger) WithTime(t time.Time) *Entry { entry := logger.newEntry() defer logger.releaseEntry(entry) return entry.WithTime(t) } func (logger *Logger) Logf(level Level, format string, args ...interface{}) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() entry.Logf(level, format, args...) logger.releaseEntry(entry) } } func (logger *Logger) Tracef(format string, args ...interface{}) { logger.Logf(TraceLevel, format, args...) } func (logger *Logger) Debugf(format string, args ...interface{}) { logger.Logf(DebugLevel, format, args...) } func (logger *Logger) Infof(format string, args ...interface{}) { logger.Logf(InfoLevel, format, args...) } func (logger *Logger) Printf(format string, args ...interface{}) { entry := logger.newEntry() entry.Printf(format, args...) logger.releaseEntry(entry) } func (logger *Logger) Warnf(format string, args ...interface{}) { logger.Logf(WarnLevel, format, args...) } func (logger *Logger) Warningf(format string, args ...interface{}) { logger.Warnf(format, args...) } func (logger *Logger) Errorf(format string, args ...interface{}) { logger.Logf(ErrorLevel, format, args...) } func (logger *Logger) Fatalf(format string, args ...interface{}) { logger.Logf(FatalLevel, format, args...) logger.Exit(1) } func (logger *Logger) Panicf(format string, args ...interface{}) { logger.Logf(PanicLevel, format, args...) } // Log will log a message at the level given as parameter. // Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. // For this behaviour Logger.Panic or Logger.Fatal should be used instead. func (logger *Logger) Log(level Level, args ...interface{}) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() entry.Log(level, args...) logger.releaseEntry(entry) } } func (logger *Logger) LogFn(level Level, fn LogFunction) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() entry.Log(level, fn()...) logger.releaseEntry(entry) } } func (logger *Logger) Trace(args ...interface{}) { logger.Log(TraceLevel, args...) } func (logger *Logger) Debug(args ...interface{}) { logger.Log(DebugLevel, args...) } func (logger *Logger) Info(args ...interface{}) { logger.Log(InfoLevel, args...) } func (logger *Logger) Print(args ...interface{}) { entry := logger.newEntry() entry.Print(args...) logger.releaseEntry(entry) } func (logger *Logger) Warn(args ...interface{}) { logger.Log(WarnLevel, args...) } func (logger *Logger) Warning(args ...interface{}) { logger.Warn(args...) } func (logger *Logger) Error(args ...interface{}) { logger.Log(ErrorLevel, args...) } func (logger *Logger) Fatal(args ...interface{}) { logger.Log(FatalLevel, args...) logger.Exit(1) } func (logger *Logger) Panic(args ...interface{}) { logger.Log(PanicLevel, args...) } func (logger *Logger) TraceFn(fn LogFunction) { logger.LogFn(TraceLevel, fn) } func (logger *Logger) DebugFn(fn LogFunction) { logger.LogFn(DebugLevel, fn) } func (logger *Logger) InfoFn(fn LogFunction) { logger.LogFn(InfoLevel, fn) } func (logger *Logger) PrintFn(fn LogFunction) { entry := logger.newEntry() entry.Print(fn()...) logger.releaseEntry(entry) } func (logger *Logger) WarnFn(fn LogFunction) { logger.LogFn(WarnLevel, fn) } func (logger *Logger) WarningFn(fn LogFunction) { logger.WarnFn(fn) } func (logger *Logger) ErrorFn(fn LogFunction) { logger.LogFn(ErrorLevel, fn) } func (logger *Logger) FatalFn(fn LogFunction) { logger.LogFn(FatalLevel, fn) logger.Exit(1) } func (logger *Logger) PanicFn(fn LogFunction) { logger.LogFn(PanicLevel, fn) } func (logger *Logger) Logln(level Level, args ...interface{}) { if logger.IsLevelEnabled(level) { entry := logger.newEntry() entry.Logln(level, args...) logger.releaseEntry(entry) } } func (logger *Logger) Traceln(args ...interface{}) { logger.Logln(TraceLevel, args...) } func (logger *Logger) Debugln(args ...interface{}) { logger.Logln(DebugLevel, args...) } func (logger *Logger) Infoln(args ...interface{}) { logger.Logln(InfoLevel, args...) } func (logger *Logger) Println(args ...interface{}) { entry := logger.newEntry() entry.Println(args...) logger.releaseEntry(entry) } func (logger *Logger) Warnln(args ...interface{}) { logger.Logln(WarnLevel, args...) } func (logger *Logger) Warningln(args ...interface{}) { logger.Warnln(args...) } func (logger *Logger) Errorln(args ...interface{}) { logger.Logln(ErrorLevel, args...) } func (logger *Logger) Fatalln(args ...interface{}) { logger.Logln(FatalLevel, args...) logger.Exit(1) } func (logger *Logger) Panicln(args ...interface{}) { logger.Logln(PanicLevel, args...) } func (logger *Logger) Exit(code int) { runHandlers() if logger.ExitFunc == nil { logger.ExitFunc = os.Exit } logger.ExitFunc(code) } //When file is opened with appending mode, it's safe to //write concurrently to a file (within 4k message on Linux). //In these cases user can choose to disable the lock. func (logger *Logger) SetNoLock() { logger.mu.Disable() } func (logger *Logger) level() Level { return Level(atomic.LoadUint32((*uint32)(&logger.Level))) } // SetLevel sets the logger level. func (logger *Logger) SetLevel(level Level) { atomic.StoreUint32((*uint32)(&logger.Level), uint32(level)) } // GetLevel returns the logger level. func (logger *Logger) GetLevel() Level { return logger.level() } // AddHook adds a hook to the logger hooks. func (logger *Logger) AddHook(hook Hook) { logger.mu.Lock() defer logger.mu.Unlock() logger.Hooks.Add(hook) } // IsLevelEnabled checks if the log level of the logger is greater than the level param func (logger *Logger) IsLevelEnabled(level Level) bool { return logger.level() >= level } // SetFormatter sets the logger formatter. func (logger *Logger) SetFormatter(formatter Formatter) { logger.mu.Lock() defer logger.mu.Unlock() logger.Formatter = formatter } // SetOutput sets the logger output. func (logger *Logger) SetOutput(output io.Writer) { logger.mu.Lock() defer logger.mu.Unlock() logger.Out = output } func (logger *Logger) SetReportCaller(reportCaller bool) { logger.mu.Lock() defer logger.mu.Unlock() logger.ReportCaller = reportCaller } // ReplaceHooks replaces the logger hooks and returns the old ones func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks { logger.mu.Lock() oldHooks := logger.Hooks logger.Hooks = hooks logger.mu.Unlock() return oldHooks } // SetBufferPool sets the logger buffer pool. func (logger *Logger) SetBufferPool(pool BufferPool) { logger.mu.Lock() defer logger.mu.Unlock() logger.BufferPool = pool }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/json_formatter.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/json_formatter.go
package logrus import ( "bytes" "encoding/json" "fmt" "runtime" ) type fieldKey string // FieldMap allows customization of the key names for default fields. type FieldMap map[fieldKey]string func (f FieldMap) resolve(key fieldKey) string { if k, ok := f[key]; ok { return k } return string(key) } // JSONFormatter formats logs into parsable json type JSONFormatter struct { // TimestampFormat sets the format used for marshaling timestamps. // The format to use is the same than for time.Format or time.Parse from the standard // library. // The standard Library already provides a set of predefined format. TimestampFormat string // DisableTimestamp allows disabling automatic timestamps in output DisableTimestamp bool // DisableHTMLEscape allows disabling html escaping in output DisableHTMLEscape bool // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key. DataKey string // FieldMap allows users to customize the names of keys for default fields. // As an example: // formatter := &JSONFormatter{ // FieldMap: FieldMap{ // FieldKeyTime: "@timestamp", // FieldKeyLevel: "@level", // FieldKeyMsg: "@message", // FieldKeyFunc: "@caller", // }, // } FieldMap FieldMap // CallerPrettyfier can be set by the user to modify the content // of the function and file keys in the json data when ReportCaller is // activated. If any of the returned value is the empty string the // corresponding key will be removed from json fields. CallerPrettyfier func(*runtime.Frame) (function string, file string) // PrettyPrint will indent all json logs PrettyPrint bool } // Format renders a single log entry func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { data := make(Fields, len(entry.Data)+4) for k, v := range entry.Data { switch v := v.(type) { case error: // Otherwise errors are ignored by `encoding/json` // https://github.com/sirupsen/logrus/issues/137 data[k] = v.Error() default: data[k] = v } } if f.DataKey != "" { newData := make(Fields, 4) newData[f.DataKey] = data data = newData } prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) timestampFormat := f.TimestampFormat if timestampFormat == "" { timestampFormat = defaultTimestampFormat } if entry.err != "" { data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err } if !f.DisableTimestamp { data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) } data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() if entry.HasCaller() { funcVal := entry.Caller.Function fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) if f.CallerPrettyfier != nil { funcVal, fileVal = f.CallerPrettyfier(entry.Caller) } if funcVal != "" { data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal } if fileVal != "" { data[f.FieldMap.resolve(FieldKeyFile)] = fileVal } } var b *bytes.Buffer if entry.Buffer != nil { b = entry.Buffer } else { b = &bytes.Buffer{} } encoder := json.NewEncoder(b) encoder.SetEscapeHTML(!f.DisableHTMLEscape) if f.PrettyPrint { encoder.SetIndent("", " ") } if err := encoder.Encode(data); err != nil { return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err) } return b.Bytes(), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/text_formatter.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/text_formatter.go
package logrus import ( "bytes" "fmt" "os" "runtime" "sort" "strconv" "strings" "sync" "time" "unicode/utf8" ) const ( red = 31 yellow = 33 blue = 36 gray = 37 ) var baseTimestamp time.Time func init() { baseTimestamp = time.Now() } // TextFormatter formats logs into text type TextFormatter struct { // Set to true to bypass checking for a TTY before outputting colors. ForceColors bool // Force disabling colors. DisableColors bool // Force quoting of all values ForceQuote bool // DisableQuote disables quoting for all values. // DisableQuote will have a lower priority than ForceQuote. // If both of them are set to true, quote will be forced on all values. DisableQuote bool // Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/ EnvironmentOverrideColors bool // Disable timestamp logging. useful when output is redirected to logging // system that already adds timestamps. DisableTimestamp bool // Enable logging the full timestamp when a TTY is attached instead of just // the time passed since beginning of execution. FullTimestamp bool // TimestampFormat to use for display when a full timestamp is printed. // The format to use is the same than for time.Format or time.Parse from the standard // library. // The standard Library already provides a set of predefined format. TimestampFormat string // The fields are sorted by default for a consistent output. For applications // that log extremely frequently and don't use the JSON formatter this may not // be desired. DisableSorting bool // The keys sorting function, when uninitialized it uses sort.Strings. SortingFunc func([]string) // Disables the truncation of the level text to 4 characters. DisableLevelTruncation bool // PadLevelText Adds padding the level text so that all the levels output at the same length // PadLevelText is a superset of the DisableLevelTruncation option PadLevelText bool // QuoteEmptyFields will wrap empty fields in quotes if true QuoteEmptyFields bool // Whether the logger's out is to a terminal isTerminal bool // FieldMap allows users to customize the names of keys for default fields. // As an example: // formatter := &TextFormatter{ // FieldMap: FieldMap{ // FieldKeyTime: "@timestamp", // FieldKeyLevel: "@level", // FieldKeyMsg: "@message"}} FieldMap FieldMap // CallerPrettyfier can be set by the user to modify the content // of the function and file keys in the data when ReportCaller is // activated. If any of the returned value is the empty string the // corresponding key will be removed from fields. CallerPrettyfier func(*runtime.Frame) (function string, file string) terminalInitOnce sync.Once // The max length of the level text, generated dynamically on init levelTextMaxLength int } func (f *TextFormatter) init(entry *Entry) { if entry.Logger != nil { f.isTerminal = checkIfTerminal(entry.Logger.Out) } // Get the max length of the level text for _, level := range AllLevels { levelTextLength := utf8.RuneCount([]byte(level.String())) if levelTextLength > f.levelTextMaxLength { f.levelTextMaxLength = levelTextLength } } } func (f *TextFormatter) isColored() bool { isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows")) if f.EnvironmentOverrideColors { switch force, ok := os.LookupEnv("CLICOLOR_FORCE"); { case ok && force != "0": isColored = true case ok && force == "0", os.Getenv("CLICOLOR") == "0": isColored = false } } return isColored && !f.DisableColors } // Format renders a single log entry func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { data := make(Fields) for k, v := range entry.Data { data[k] = v } prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) keys := make([]string, 0, len(data)) for k := range data { keys = append(keys, k) } var funcVal, fileVal string fixedKeys := make([]string, 0, 4+len(data)) if !f.DisableTimestamp { fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime)) } fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel)) if entry.Message != "" { fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg)) } if entry.err != "" { fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError)) } if entry.HasCaller() { if f.CallerPrettyfier != nil { funcVal, fileVal = f.CallerPrettyfier(entry.Caller) } else { funcVal = entry.Caller.Function fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) } if funcVal != "" { fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc)) } if fileVal != "" { fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile)) } } if !f.DisableSorting { if f.SortingFunc == nil { sort.Strings(keys) fixedKeys = append(fixedKeys, keys...) } else { if !f.isColored() { fixedKeys = append(fixedKeys, keys...) f.SortingFunc(fixedKeys) } else { f.SortingFunc(keys) } } } else { fixedKeys = append(fixedKeys, keys...) } var b *bytes.Buffer if entry.Buffer != nil { b = entry.Buffer } else { b = &bytes.Buffer{} } f.terminalInitOnce.Do(func() { f.init(entry) }) timestampFormat := f.TimestampFormat if timestampFormat == "" { timestampFormat = defaultTimestampFormat } if f.isColored() { f.printColored(b, entry, keys, data, timestampFormat) } else { for _, key := range fixedKeys { var value interface{} switch { case key == f.FieldMap.resolve(FieldKeyTime): value = entry.Time.Format(timestampFormat) case key == f.FieldMap.resolve(FieldKeyLevel): value = entry.Level.String() case key == f.FieldMap.resolve(FieldKeyMsg): value = entry.Message case key == f.FieldMap.resolve(FieldKeyLogrusError): value = entry.err case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller(): value = funcVal case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller(): value = fileVal default: value = data[key] } f.appendKeyValue(b, key, value) } } b.WriteByte('\n') return b.Bytes(), nil } func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) { var levelColor int switch entry.Level { case DebugLevel, TraceLevel: levelColor = gray case WarnLevel: levelColor = yellow case ErrorLevel, FatalLevel, PanicLevel: levelColor = red case InfoLevel: levelColor = blue default: levelColor = blue } levelText := strings.ToUpper(entry.Level.String()) if !f.DisableLevelTruncation && !f.PadLevelText { levelText = levelText[0:4] } if f.PadLevelText { // Generates the format string used in the next line, for example "%-6s" or "%-7s". // Based on the max level text length. formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s" // Formats the level text by appending spaces up to the max length, for example: // - "INFO " // - "WARNING" levelText = fmt.Sprintf(formatString, levelText) } // Remove a single newline if it already exists in the message to keep // the behavior of logrus text_formatter the same as the stdlib log package entry.Message = strings.TrimSuffix(entry.Message, "\n") caller := "" if entry.HasCaller() { funcVal := fmt.Sprintf("%s()", entry.Caller.Function) fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) if f.CallerPrettyfier != nil { funcVal, fileVal = f.CallerPrettyfier(entry.Caller) } if fileVal == "" { caller = funcVal } else if funcVal == "" { caller = fileVal } else { caller = fileVal + " " + funcVal } } switch { case f.DisableTimestamp: fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message) case !f.FullTimestamp: fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message) default: fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message) } for _, k := range keys { v := data[k] fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) f.appendValue(b, v) } } func (f *TextFormatter) needsQuoting(text string) bool { if f.ForceQuote { return true } if f.QuoteEmptyFields && len(text) == 0 { return true } if f.DisableQuote { return false } for _, ch := range text { if !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') { return true } } return false } func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { if b.Len() > 0 { b.WriteByte(' ') } b.WriteString(key) b.WriteByte('=') f.appendValue(b, value) } func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { stringVal, ok := value.(string) if !ok { stringVal = fmt.Sprint(value) } if !f.needsQuoting(stringVal) { b.WriteString(stringVal) } else { b.WriteString(fmt.Sprintf("%q", stringVal)) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go
// +build !appengine,!js,!windows,!nacl,!plan9 package logrus import ( "io" "os" ) func checkIfTerminal(w io.Writer) bool { switch v := w.(type) { case *os.File: return isTerminal(int(v.Fd())) default: return false } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers.go
package gomega import ( "fmt" "time" "github.com/google/go-cmp/cmp" "github.com/onsi/gomega/matchers" "github.com/onsi/gomega/types" ) // Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about // types when performing comparisons. // It is an error for both actual and expected to be nil. Use BeNil() instead. func Equal(expected any) types.GomegaMatcher { return &matchers.EqualMatcher{ Expected: expected, } } // BeEquivalentTo is more lax than Equal, allowing equality between different types. // This is done by converting actual to have the type of expected before // attempting equality with reflect.DeepEqual. // It is an error for actual and expected to be nil. Use BeNil() instead. func BeEquivalentTo(expected any) types.GomegaMatcher { return &matchers.BeEquivalentToMatcher{ Expected: expected, } } // BeComparableTo uses gocmp.Equal from github.com/google/go-cmp (instead of reflect.DeepEqual) to perform a deep comparison. // You can pass cmp.Option as options. // It is an error for actual and expected to be nil. Use BeNil() instead. func BeComparableTo(expected any, opts ...cmp.Option) types.GomegaMatcher { return &matchers.BeComparableToMatcher{ Expected: expected, Options: opts, } } // BeIdenticalTo uses the == operator to compare actual with expected. // BeIdenticalTo is strict about types when performing comparisons. // It is an error for both actual and expected to be nil. Use BeNil() instead. func BeIdenticalTo(expected any) types.GomegaMatcher { return &matchers.BeIdenticalToMatcher{ Expected: expected, } } // BeNil succeeds if actual is nil func BeNil() types.GomegaMatcher { return &matchers.BeNilMatcher{} } // BeTrue succeeds if actual is true // // In general, it's better to use `BeTrueBecause(reason)` to provide a more useful error message if a true check fails. func BeTrue() types.GomegaMatcher { return &matchers.BeTrueMatcher{} } // BeFalse succeeds if actual is false // // In general, it's better to use `BeFalseBecause(reason)` to provide a more useful error message if a false check fails. func BeFalse() types.GomegaMatcher { return &matchers.BeFalseMatcher{} } // BeTrueBecause succeeds if actual is true and displays the provided reason if it is false // fmt.Sprintf is used to render the reason func BeTrueBecause(format string, args ...any) types.GomegaMatcher { return &matchers.BeTrueMatcher{Reason: fmt.Sprintf(format, args...)} } // BeFalseBecause succeeds if actual is false and displays the provided reason if it is true. // fmt.Sprintf is used to render the reason func BeFalseBecause(format string, args ...any) types.GomegaMatcher { return &matchers.BeFalseMatcher{Reason: fmt.Sprintf(format, args...)} } // HaveOccurred succeeds if actual is a non-nil error // The typical Go error checking pattern looks like: // // err := SomethingThatMightFail() // Expect(err).ShouldNot(HaveOccurred()) func HaveOccurred() types.GomegaMatcher { return &matchers.HaveOccurredMatcher{} } // Succeed passes if actual is a nil error // Succeed is intended to be used with functions that return a single error value. Instead of // // err := SomethingThatMightFail() // Expect(err).ShouldNot(HaveOccurred()) // // You can write: // // Expect(SomethingThatMightFail()).Should(Succeed()) // // It is a mistake to use Succeed with a function that has multiple return values. Gomega's Ω and Expect // functions automatically trigger failure if any return values after the first return value are non-zero/non-nil. // This means that Ω(MultiReturnFunc()).ShouldNot(Succeed()) can never pass. func Succeed() types.GomegaMatcher { return &matchers.SucceedMatcher{} } // MatchError succeeds if actual is a non-nil error that matches the passed in // string, error, function, or matcher. // // These are valid use-cases: // // When passed a string: // // Expect(err).To(MatchError("an error")) // // asserts that err.Error() == "an error" // // When passed an error: // // Expect(err).To(MatchError(SomeError)) // // First checks if errors.Is(err, SomeError). // If that fails then it checks if reflect.DeepEqual(err, SomeError) repeatedly for err and any errors wrapped by err // // When passed a matcher: // // Expect(err).To(MatchError(ContainSubstring("sprocket not found"))) // // the matcher is passed err.Error(). In this case it asserts that err.Error() contains substring "sprocket not found" // // When passed a func(err) bool and a description: // // Expect(err).To(MatchError(os.IsNotExist, "IsNotExist")) // // the function is passed err and matches if the return value is true. The description is required to allow Gomega // to print a useful error message. // // It is an error for err to be nil or an object that does not implement the // Error interface // // The optional second argument is a description of the error function, if used. This is required when passing a function but is ignored in all other cases. func MatchError(expected any, functionErrorDescription ...any) types.GomegaMatcher { return &matchers.MatchErrorMatcher{ Expected: expected, FuncErrDescription: functionErrorDescription, } } // BeClosed succeeds if actual is a closed channel. // It is an error to pass a non-channel to BeClosed, it is also an error to pass nil // // In order to check whether or not the channel is closed, Gomega must try to read from the channel // (even in the `ShouldNot(BeClosed())` case). You should keep this in mind if you wish to make subsequent assertions about // values coming down the channel. // // Also, if you are testing that a *buffered* channel is closed you must first read all values out of the channel before // asserting that it is closed (it is not possible to detect that a buffered-channel has been closed until all its buffered values are read). // // Finally, as a corollary: it is an error to check whether or not a send-only channel is closed. func BeClosed() types.GomegaMatcher { return &matchers.BeClosedMatcher{} } // Receive succeeds if there is a value to be received on actual. // Actual must be a channel (and cannot be a send-only channel) -- anything else is an error. // // Receive returns immediately and never blocks: // // - If there is nothing on the channel `c` then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. // // - If the channel `c` is closed then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. // // - If there is something on the channel `c` ready to be read, then Expect(c).Should(Receive()) will pass and Ω(c).ShouldNot(Receive()) will fail. // // If you have a go-routine running in the background that will write to channel `c` you can: // // Eventually(c).Should(Receive()) // // This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`) // // A similar use-case is to assert that no go-routine writes to a channel (for a period of time). You can do this with `Consistently`: // // Consistently(c).ShouldNot(Receive()) // // You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example: // // Expect(c).Should(Receive(Equal("foo"))) // // When given a matcher, `Receive` will always fail if there is nothing to be received on the channel. // // Passing Receive a matcher is especially useful when paired with Eventually: // // Eventually(c).Should(Receive(ContainSubstring("bar"))) // // will repeatedly attempt to pull values out of `c` until a value matching "bar" is received. // // Furthermore, if you want to have a reference to the value *sent* to the channel you can pass the `Receive` matcher a pointer to a variable of the appropriate type: // // var myThing thing // Eventually(thingChan).Should(Receive(&myThing)) // Expect(myThing.Sprocket).Should(Equal("foo")) // Expect(myThing.IsValid()).Should(BeTrue()) // // Finally, if you want to match the received object as well as get the actual received value into a variable, so you can reason further about the value received, // you can pass a pointer to a variable of the appropriate type first, and second a matcher: // // var myThing thing // Eventually(thingChan).Should(Receive(&myThing, ContainSubstring("bar"))) func Receive(args ...any) types.GomegaMatcher { return &matchers.ReceiveMatcher{ Args: args, } } // BeSent succeeds if a value can be sent to actual. // Actual must be a channel (and cannot be a receive-only channel) that can sent the type of the value passed into BeSent -- anything else is an error. // In addition, actual must not be closed. // // BeSent never blocks: // // - If the channel `c` is not ready to receive then Expect(c).Should(BeSent("foo")) will fail immediately // - If the channel `c` is eventually ready to receive then Eventually(c).Should(BeSent("foo")) will succeed.. presuming the channel becomes ready to receive before Eventually's timeout // - If the channel `c` is closed then Expect(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately // // Of course, the value is actually sent to the channel. The point of `BeSent` is less to make an assertion about the availability of the channel (which is typically an implementation detail that your test should not be concerned with). // Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends. func BeSent(arg any) types.GomegaMatcher { return &matchers.BeSentMatcher{ Arg: arg, } } // MatchRegexp succeeds if actual is a string or stringer that matches the // passed-in regexp. Optional arguments can be provided to construct a regexp // via fmt.Sprintf(). func MatchRegexp(regexp string, args ...any) types.GomegaMatcher { return &matchers.MatchRegexpMatcher{ Regexp: regexp, Args: args, } } // ContainSubstring succeeds if actual is a string or stringer that contains the // passed-in substring. Optional arguments can be provided to construct the substring // via fmt.Sprintf(). func ContainSubstring(substr string, args ...any) types.GomegaMatcher { return &matchers.ContainSubstringMatcher{ Substr: substr, Args: args, } } // HavePrefix succeeds if actual is a string or stringer that contains the // passed-in string as a prefix. Optional arguments can be provided to construct // via fmt.Sprintf(). func HavePrefix(prefix string, args ...any) types.GomegaMatcher { return &matchers.HavePrefixMatcher{ Prefix: prefix, Args: args, } } // HaveSuffix succeeds if actual is a string or stringer that contains the // passed-in string as a suffix. Optional arguments can be provided to construct // via fmt.Sprintf(). func HaveSuffix(suffix string, args ...any) types.GomegaMatcher { return &matchers.HaveSuffixMatcher{ Suffix: suffix, Args: args, } } // MatchJSON succeeds if actual is a string or stringer of JSON that matches // the expected JSON. The JSONs are decoded and the resulting objects are compared via // reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. func MatchJSON(json any) types.GomegaMatcher { return &matchers.MatchJSONMatcher{ JSONToMatch: json, } } // MatchXML succeeds if actual is a string or stringer of XML that matches // the expected XML. The XMLs are decoded and the resulting objects are compared via // reflect.DeepEqual so things like whitespaces shouldn't matter. func MatchXML(xml any) types.GomegaMatcher { return &matchers.MatchXMLMatcher{ XMLToMatch: xml, } } // MatchYAML succeeds if actual is a string or stringer of YAML that matches // the expected YAML. The YAML's are decoded and the resulting objects are compared via // reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. func MatchYAML(yaml any) types.GomegaMatcher { return &matchers.MatchYAMLMatcher{ YAMLToMatch: yaml, } } // BeEmpty succeeds if actual is empty. Actual must be of type string, array, map, chan, or slice. func BeEmpty() types.GomegaMatcher { return &matchers.BeEmptyMatcher{} } // HaveLen succeeds if actual has the passed-in length. Actual must be of type string, array, map, chan, or slice. func HaveLen(count int) types.GomegaMatcher { return &matchers.HaveLenMatcher{ Count: count, } } // HaveCap succeeds if actual has the passed-in capacity. Actual must be of type array, chan, or slice. func HaveCap(count int) types.GomegaMatcher { return &matchers.HaveCapMatcher{ Count: count, } } // BeZero succeeds if actual is the zero value for its type or if actual is nil. func BeZero() types.GomegaMatcher { return &matchers.BeZeroMatcher{} } // ContainElement succeeds if actual contains the passed in element. By default // ContainElement() uses Equal() to perform the match, however a matcher can be // passed in instead: // // Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar"))) // // Actual must be an array, slice or map. For maps, ContainElement searches // through the map's values. // // If you want to have a copy of the matching element(s) found you can pass a // pointer to a variable of the appropriate type. If the variable isn't a slice // or map, then exactly one match will be expected and returned. If the variable // is a slice or map, then at least one match is expected and all matches will be // stored in the variable. // // var findings []string // Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubString("Bar", &findings))) func ContainElement(element any, result ...any) types.GomegaMatcher { return &matchers.ContainElementMatcher{ Element: element, Result: result, } } // BeElementOf succeeds if actual is contained in the passed in elements. // BeElementOf() always uses Equal() to perform the match. // When the passed in elements are comprised of a single element that is either an Array or Slice, BeElementOf() behaves // as the reverse of ContainElement() that operates with Equal() to perform the match. // // Expect(2).Should(BeElementOf([]int{1, 2})) // Expect(2).Should(BeElementOf([2]int{1, 2})) // // Otherwise, BeElementOf() provides a syntactic sugar for Or(Equal(_), Equal(_), ...): // // Expect(2).Should(BeElementOf(1, 2)) // // Actual must be typed. func BeElementOf(elements ...any) types.GomegaMatcher { return &matchers.BeElementOfMatcher{ Elements: elements, } } // BeKeyOf succeeds if actual is contained in the keys of the passed in map. // BeKeyOf() always uses Equal() to perform the match between actual and the map keys. // // Expect("foo").Should(BeKeyOf(map[string]bool{"foo": true, "bar": false})) func BeKeyOf(element any) types.GomegaMatcher { return &matchers.BeKeyOfMatcher{ Map: element, } } // ConsistOf succeeds if actual contains precisely the elements passed into the matcher. The ordering of the elements does not matter. // By default ConsistOf() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples: // // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo")) // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo")) // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo"))) // // Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values. // // You typically pass variadic arguments to ConsistOf (as in the examples above). However, if you need to pass in a slice you can provided that it // is the only element passed in to ConsistOf: // // Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"})) // // Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []any are different types - hence the need for this special rule. func ConsistOf(elements ...any) types.GomegaMatcher { return &matchers.ConsistOfMatcher{ Elements: elements, } } // HaveExactElements succeeds if actual contains elements that precisely match the elements passed into the matcher. The ordering of the elements does matter. // By default HaveExactElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples: // // Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements("Foo", "FooBar")) // Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements("Foo", ContainSubstring("Bar"))) // Expect([]string{"Foo", "FooBar"}).Should(HaveExactElements(ContainSubstring("Foo"), ContainSubstring("Foo"))) // // Actual must be an array or slice. func HaveExactElements(elements ...any) types.GomegaMatcher { return &matchers.HaveExactElementsMatcher{ Elements: elements, } } // ContainElements succeeds if actual contains the passed in elements. The ordering of the elements does not matter. // By default ContainElements() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples: // // Expect([]string{"Foo", "FooBar"}).Should(ContainElements("FooBar")) // Expect([]string{"Foo", "FooBar"}).Should(ContainElements(ContainSubstring("Bar"), "Foo")) // // Actual must be an array, slice or map. // For maps, ContainElements searches through the map's values. func ContainElements(elements ...any) types.GomegaMatcher { return &matchers.ContainElementsMatcher{ Elements: elements, } } // HaveEach succeeds if actual solely contains elements that match the passed in element. // Please note that if actual is empty, HaveEach always will fail. // By default HaveEach() uses Equal() to perform the match, however a // matcher can be passed in instead: // // Expect([]string{"Foo", "FooBar"}).Should(HaveEach(ContainSubstring("Foo"))) // // Actual must be an array, slice or map. // For maps, HaveEach searches through the map's values. func HaveEach(element any) types.GomegaMatcher { return &matchers.HaveEachMatcher{ Element: element, } } // HaveKey succeeds if actual is a map with the passed in key. // By default HaveKey uses Equal() to perform the match, however a // matcher can be passed in instead: // // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) func HaveKey(key any) types.GomegaMatcher { return &matchers.HaveKeyMatcher{ Key: key, } } // HaveKeyWithValue succeeds if actual is a map with the passed in key and value. // By default HaveKeyWithValue uses Equal() to perform the match, however a // matcher can be passed in instead: // // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar")) // Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar")) func HaveKeyWithValue(key any, value any) types.GomegaMatcher { return &matchers.HaveKeyWithValueMatcher{ Key: key, Value: value, } } // HaveField succeeds if actual is a struct and the value at the passed in field // matches the passed in matcher. By default HaveField used Equal() to perform the match, // however a matcher can be passed in in stead. // // The field must be a string that resolves to the name of a field in the struct. Structs can be traversed // using the '.' delimiter. If the field ends with '()' a method named field is assumed to exist on the struct and is invoked. // Such methods must take no arguments and return a single value: // // type Book struct { // Title string // Author Person // } // type Person struct { // FirstName string // LastName string // DOB time.Time // } // Expect(book).To(HaveField("Title", "Les Miserables")) // Expect(book).To(HaveField("Title", ContainSubstring("Les")) // Expect(book).To(HaveField("Author.FirstName", Equal("Victor")) // Expect(book).To(HaveField("Author.DOB.Year()", BeNumerically("<", 1900)) func HaveField(field string, expected any) types.GomegaMatcher { return &matchers.HaveFieldMatcher{ Field: field, Expected: expected, } } // HaveExistingField succeeds if actual is a struct and the specified field // exists. // // HaveExistingField can be combined with HaveField in order to cover use cases // with optional fields. HaveField alone would trigger an error in such situations. // // Expect(MrHarmless).NotTo(And(HaveExistingField("Title"), HaveField("Title", "Supervillain"))) func HaveExistingField(field string) types.GomegaMatcher { return &matchers.HaveExistingFieldMatcher{ Field: field, } } // HaveValue applies the given matcher to the value of actual, optionally and // repeatedly dereferencing pointers or taking the concrete value of interfaces. // Thus, the matcher will always be applied to non-pointer and non-interface // values only. HaveValue will fail with an error if a pointer or interface is // nil. It will also fail for more than 31 pointer or interface dereferences to // guard against mistakenly applying it to arbitrarily deep linked pointers. // // HaveValue differs from gstruct.PointTo in that it does not expect actual to // be a pointer (as gstruct.PointTo does) but instead also accepts non-pointer // and even interface values. // // actual := 42 // Expect(actual).To(HaveValue(42)) // Expect(&actual).To(HaveValue(42)) func HaveValue(matcher types.GomegaMatcher) types.GomegaMatcher { return &matchers.HaveValueMatcher{ Matcher: matcher, } } // BeNumerically performs numerical assertions in a type-agnostic way. // Actual and expected should be numbers, though the specific type of // number is irrelevant (float32, float64, uint8, etc...). // // There are six, self-explanatory, supported comparators: // // Expect(1.0).Should(BeNumerically("==", 1)) // Expect(1.0).Should(BeNumerically("~", 0.999, 0.01)) // Expect(1.0).Should(BeNumerically(">", 0.9)) // Expect(1.0).Should(BeNumerically(">=", 1.0)) // Expect(1.0).Should(BeNumerically("<", 3)) // Expect(1.0).Should(BeNumerically("<=", 1.0)) func BeNumerically(comparator string, compareTo ...any) types.GomegaMatcher { return &matchers.BeNumericallyMatcher{ Comparator: comparator, CompareTo: compareTo, } } // BeTemporally compares time.Time's like BeNumerically // Actual and expected must be time.Time. The comparators are the same as for BeNumerically // // Expect(time.Now()).Should(BeTemporally(">", time.Time{})) // Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second)) func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher { return &matchers.BeTemporallyMatcher{ Comparator: comparator, CompareTo: compareTo, Threshold: threshold, } } // BeAssignableToTypeOf succeeds if actual is assignable to the type of expected. // It will return an error when one of the values is nil. // // Expect(0).Should(BeAssignableToTypeOf(0)) // Same values // Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type // Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type // Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) func BeAssignableToTypeOf(expected any) types.GomegaMatcher { return &matchers.AssignableToTypeOfMatcher{ Expected: expected, } } // Panic succeeds if actual is a function that, when invoked, panics. // Actual must be a function that takes no arguments and returns no results. func Panic() types.GomegaMatcher { return &matchers.PanicMatcher{} } // PanicWith succeeds if actual is a function that, when invoked, panics with a specific value. // Actual must be a function that takes no arguments and returns no results. // // By default PanicWith uses Equal() to perform the match, however a // matcher can be passed in instead: // // Expect(fn).Should(PanicWith(MatchRegexp(`.+Foo$`))) func PanicWith(expected any) types.GomegaMatcher { return &matchers.PanicMatcher{Expected: expected} } // BeAnExistingFile succeeds if a file exists. // Actual must be a string representing the abs path to the file being checked. func BeAnExistingFile() types.GomegaMatcher { return &matchers.BeAnExistingFileMatcher{} } // BeARegularFile succeeds if a file exists and is a regular file. // Actual must be a string representing the abs path to the file being checked. func BeARegularFile() types.GomegaMatcher { return &matchers.BeARegularFileMatcher{} } // BeADirectory succeeds if a file exists and is a directory. // Actual must be a string representing the abs path to the file being checked. func BeADirectory() types.GomegaMatcher { return &matchers.BeADirectoryMatcher{} } // HaveHTTPStatus succeeds if the Status or StatusCode field of an HTTP response matches. // Actual must be either a *http.Response or *httptest.ResponseRecorder. // Expected must be either an int or a string. // // Expect(resp).Should(HaveHTTPStatus(http.StatusOK)) // asserts that resp.StatusCode == 200 // Expect(resp).Should(HaveHTTPStatus("404 Not Found")) // asserts that resp.Status == "404 Not Found" // Expect(resp).Should(HaveHTTPStatus(http.StatusOK, http.StatusNoContent)) // asserts that resp.StatusCode == 200 || resp.StatusCode == 204 func HaveHTTPStatus(expected ...any) types.GomegaMatcher { return &matchers.HaveHTTPStatusMatcher{Expected: expected} } // HaveHTTPHeaderWithValue succeeds if the header is found and the value matches. // Actual must be either a *http.Response or *httptest.ResponseRecorder. // Expected must be a string header name, followed by a header value which // can be a string, or another matcher. func HaveHTTPHeaderWithValue(header string, value any) types.GomegaMatcher { return &matchers.HaveHTTPHeaderWithValueMatcher{ Header: header, Value: value, } } // HaveHTTPBody matches if the body matches. // Actual must be either a *http.Response or *httptest.ResponseRecorder. // Expected must be either a string, []byte, or other matcher func HaveHTTPBody(expected any) types.GomegaMatcher { return &matchers.HaveHTTPBodyMatcher{Expected: expected} } // And succeeds only if all of the given matchers succeed. // The matchers are tried in order, and will fail-fast if one doesn't succeed. // // Expect("hi").To(And(HaveLen(2), Equal("hi")) // // And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. func And(ms ...types.GomegaMatcher) types.GomegaMatcher { return &matchers.AndMatcher{Matchers: ms} } // SatisfyAll is an alias for And(). // // Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi"))) func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher { return And(matchers...) } // Or succeeds if any of the given matchers succeed. // The matchers are tried in order and will return immediately upon the first successful match. // // Expect("hi").To(Or(HaveLen(3), HaveLen(2)) // // And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. func Or(ms ...types.GomegaMatcher) types.GomegaMatcher { return &matchers.OrMatcher{Matchers: ms} } // SatisfyAny is an alias for Or(). // // Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2)) func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher { return Or(matchers...) } // Not negates the given matcher; it succeeds if the given matcher fails. // // Expect(1).To(Not(Equal(2)) // // And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. func Not(matcher types.GomegaMatcher) types.GomegaMatcher { return &matchers.NotMatcher{Matcher: matcher} } // WithTransform applies the `transform` to the actual value and matches it against `matcher`. // The given transform must be either a function of one parameter that returns one value or a // function of one parameter that returns two values, where the second value must be of the // error type. // // var plus1 = func(i int) int { return i + 1 } // Expect(1).To(WithTransform(plus1, Equal(2)) // // var failingplus1 = func(i int) (int, error) { return 42, "this does not compute" } // Expect(1).To(WithTransform(failingplus1, Equal(2))) // // And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. func WithTransform(transform any, matcher types.GomegaMatcher) types.GomegaMatcher { return matchers.NewWithTransformMatcher(transform, matcher) } // Satisfy matches the actual value against the `predicate` function. // The given predicate must be a function of one parameter that returns bool. // // var isEven = func(i int) bool { return i%2 == 0 } // Expect(2).To(Satisfy(isEven)) func Satisfy(predicate any) types.GomegaMatcher { return matchers.NewSatisfyMatcher(predicate) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/gomega_dsl.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/gomega_dsl.go
/* Gomega is the Ginkgo BDD-style testing framework's preferred matcher library. The godoc documentation describes Gomega's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/gomega/ Gomega on Github: http://github.com/onsi/gomega Learn more about Ginkgo online: http://onsi.github.io/ginkgo Ginkgo on Github: http://github.com/onsi/ginkgo Gomega is MIT-Licensed */ package gomega import ( "errors" "fmt" "time" "github.com/onsi/gomega/internal" "github.com/onsi/gomega/types" ) const GOMEGA_VERSION = "1.38.2" const nilGomegaPanic = `You are trying to make an assertion, but haven't registered Gomega's fail handler. If you're using Ginkgo then you probably forgot to put your assertion in an It(). Alternatively, you may have forgotten to register a fail handler with RegisterFailHandler() or RegisterTestingT(). Depending on your vendoring solution you may be inadvertently importing gomega and subpackages (e.g. ghhtp, gexec,...) from different locations. ` // Gomega describes the essential Gomega DSL. This interface allows libraries // to abstract between the standard package-level function implementations // and alternatives like *WithT. // // The types in the top-level DSL have gotten a bit messy due to earlier deprecations that avoid stuttering // and due to an accidental use of a concrete type (*WithT) in an earlier release. // // As of 1.15 both the WithT and Ginkgo variants of Gomega are implemented by the same underlying object // however one (the Ginkgo variant) is exported as an interface (types.Gomega) whereas the other (the withT variant) // is shared as a concrete type (*WithT, which is aliased to *internal.Gomega). 1.15 did not clean this mess up to ensure // that declarations of *WithT in existing code are not broken by the upgrade to 1.15. type Gomega = types.Gomega // DefaultGomega supplies the standard package-level implementation var Default = Gomega(internal.NewGomega(internal.FetchDefaultDurationBundle())) // NewGomega returns an instance of Gomega wired into the passed-in fail handler. // You generally don't need to use this when using Ginkgo - RegisterFailHandler will wire up the global gomega // However creating a NewGomega with a custom fail handler can be useful in contexts where you want to use Gomega's // rich ecosystem of matchers without causing a test to fail. For example, to aggregate a series of potential failures // or for use in a non-test setting. func NewGomega(fail types.GomegaFailHandler) Gomega { return internal.NewGomega(internalGomega(Default).DurationBundle).ConfigureWithFailHandler(fail) } // WithT wraps a *testing.T and provides `Expect`, `Eventually`, and `Consistently` methods. This allows you to leverage // Gomega's rich ecosystem of matchers in standard `testing` test suites. // // Use `NewWithT` to instantiate a `WithT` // // As of 1.15 both the WithT and Ginkgo variants of Gomega are implemented by the same underlying object // however one (the Ginkgo variant) is exported as an interface (types.Gomega) whereas the other (the withT variant) // is shared as a concrete type (*WithT, which is aliased to *internal.Gomega). 1.15 did not clean this mess up to ensure // that declarations of *WithT in existing code are not broken by the upgrade to 1.15. type WithT = internal.Gomega // GomegaWithT is deprecated in favor of gomega.WithT, which does not stutter. type GomegaWithT = WithT // inner is an interface that allows users to provide a wrapper around Default. The wrapper // must implement the inner interface and return either the original Default or the result of // a call to NewGomega(). type inner interface { Inner() Gomega } func internalGomega(g Gomega) *internal.Gomega { if v, ok := g.(inner); ok { return v.Inner().(*internal.Gomega) } return g.(*internal.Gomega) } // NewWithT takes a *testing.T and returns a `gomega.WithT` allowing you to use `Expect`, `Eventually`, and `Consistently` along with // Gomega's rich ecosystem of matchers in standard `testing` test suits. // // func TestFarmHasCow(t *testing.T) { // g := gomega.NewWithT(t) // // f := farm.New([]string{"Cow", "Horse"}) // g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow") // } func NewWithT(t types.GomegaTestingT) *WithT { return internal.NewGomega(internalGomega(Default).DurationBundle).ConfigureWithT(t) } // NewGomegaWithT is deprecated in favor of gomega.NewWithT, which does not stutter. var NewGomegaWithT = NewWithT // RegisterFailHandler connects Ginkgo to Gomega. When a matcher fails // the fail handler passed into RegisterFailHandler is called. func RegisterFailHandler(fail types.GomegaFailHandler) { internalGomega(Default).ConfigureWithFailHandler(fail) } // RegisterFailHandlerWithT is deprecated and will be removed in a future release. // users should use RegisterFailHandler, or RegisterTestingT func RegisterFailHandlerWithT(_ types.GomegaTestingT, fail types.GomegaFailHandler) { fmt.Println("RegisterFailHandlerWithT is deprecated. Please use RegisterFailHandler or RegisterTestingT instead.") internalGomega(Default).ConfigureWithFailHandler(fail) } // RegisterTestingT connects Gomega to Golang's XUnit style // Testing.T tests. It is now deprecated and you should use NewWithT() instead to get a fresh instance of Gomega for each test. func RegisterTestingT(t types.GomegaTestingT) { internalGomega(Default).ConfigureWithT(t) } // InterceptGomegaFailures runs a given callback and returns an array of // failure messages generated by any Gomega assertions within the callback. // Execution continues after the first failure allowing users to collect all failures // in the callback. // // This is most useful when testing custom matchers, but can also be used to check // on a value using a Gomega assertion without causing a test failure. func InterceptGomegaFailures(f func()) []string { originalHandler := internalGomega(Default).Fail failures := []string{} internalGomega(Default).Fail = func(message string, callerSkip ...int) { failures = append(failures, message) } defer func() { internalGomega(Default).Fail = originalHandler }() f() return failures } // InterceptGomegaFailure runs a given callback and returns the first // failure message generated by any Gomega assertions within the callback, wrapped in an error. // // The callback ceases execution as soon as the first failed assertion occurs, however Gomega // does not register a failure with the FailHandler registered via RegisterFailHandler - it is up // to the user to decide what to do with the returned error func InterceptGomegaFailure(f func()) (err error) { originalHandler := internalGomega(Default).Fail internalGomega(Default).Fail = func(message string, callerSkip ...int) { err = errors.New(message) panic("stop execution") } defer func() { internalGomega(Default).Fail = originalHandler if e := recover(); e != nil { if err == nil { panic(e) } } }() f() return err } func ensureDefaultGomegaIsConfigured() { if !internalGomega(Default).IsConfigured() { panic(nilGomegaPanic) } } // Ω wraps an actual value allowing assertions to be made on it: // // Ω("foo").Should(Equal("foo")) // // If Ω is passed more than one argument it will pass the *first* argument to the matcher. // All subsequent arguments will be required to be nil/zero. // // This is convenient if you want to make an assertion on a method/function that returns // a value and an error - a common pattern in Go. // // For example, given a function with signature: // // func MyAmazingThing() (int, error) // // Then: // // Ω(MyAmazingThing()).Should(Equal(3)) // // Will succeed only if `MyAmazingThing()` returns `(3, nil)` // // Ω and Expect are identical func Ω(actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.Ω(actual, extra...) } // Expect wraps an actual value allowing assertions to be made on it: // // Expect("foo").To(Equal("foo")) // // If Expect is passed more than one argument it will pass the *first* argument to the matcher. // All subsequent arguments will be required to be nil/zero. // // This is convenient if you want to make an assertion on a method/function that returns // a value and an error - a common pattern in Go. // // For example, given a function with signature: // // func MyAmazingThing() (int, error) // // Then: // // Expect(MyAmazingThing()).Should(Equal(3)) // // Will succeed only if `MyAmazingThing()` returns `(3, nil)` // // Expect and Ω are identical func Expect(actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.Expect(actual, extra...) } // ExpectWithOffset wraps an actual value allowing assertions to be made on it: // // ExpectWithOffset(1, "foo").To(Equal("foo")) // // Unlike `Expect` and `Ω`, `ExpectWithOffset` takes an additional integer argument // that is used to modify the call-stack offset when computing line numbers. It is // the same as `Expect(...).WithOffset`. // // This is most useful in helper functions that make assertions. If you want Gomega's // error message to refer to the calling line in the test (as opposed to the line in the helper function) // set the first argument of `ExpectWithOffset` appropriately. func ExpectWithOffset(offset int, actual any, extra ...any) Assertion { ensureDefaultGomegaIsConfigured() return Default.ExpectWithOffset(offset, actual, extra...) } /* Eventually enables making assertions on asynchronous behavior. Eventually checks that an assertion *eventually* passes. Eventually blocks when called and attempts an assertion periodically until it passes or a timeout occurs. Both the timeout and polling interval are configurable as optional arguments. The first optional argument is the timeout (which defaults to 1s), the second is the polling interval (which defaults to 10ms). Both intervals can be specified as time.Duration, parsable duration strings or floats/integers (in which case they are interpreted as seconds). In addition an optional context.Context can be passed in - Eventually will keep trying until either the timeout expires or the context is cancelled, whichever comes first. Eventually works with any Gomega compatible matcher and supports making assertions against three categories of actual value: **Category 1: Making Eventually assertions on values** There are several examples of values that can change over time. These can be passed in to Eventually and will be passed to the matcher repeatedly until a match occurs. For example: c := make(chan bool) go DoStuff(c) Eventually(c, "50ms").Should(BeClosed()) will poll the channel repeatedly until it is closed. In this example `Eventually` will block until either the specified timeout of 50ms has elapsed or the channel is closed, whichever comes first. Several Gomega libraries allow you to use Eventually in this way. For example, the gomega/gexec package allows you to block until a *gexec.Session exits successfully via: Eventually(session).Should(gexec.Exit(0)) And the gomega/gbytes package allows you to monitor a streaming *gbytes.Buffer until a given string is seen: Eventually(buffer).Should(gbytes.Say("hello there")) In these examples, both `session` and `buffer` are designed to be thread-safe when polled by the `Exit` and `Say` matchers. This is not true in general of most raw values, so while it is tempting to do something like: // THIS IS NOT THREAD-SAFE var s *string go mutateStringEventually(s) Eventually(s).Should(Equal("I've changed")) this will trigger Go's race detector as the goroutine polling via Eventually will race over the value of s with the goroutine mutating the string. For cases like this you can use channels or introduce your own locking around s by passing Eventually a function. **Category 2: Make Eventually assertions on functions** Eventually can be passed functions that **return at least one value**. When configured this way, Eventually will poll the function repeatedly and pass the first returned value to the matcher. For example: Eventually(func() int { return client.FetchCount() }).Should(BeNumerically(">=", 17)) will repeatedly poll client.FetchCount until the BeNumerically matcher is satisfied. (Note that this example could have been written as Eventually(client.FetchCount).Should(BeNumerically(">=", 17))) If multiple values are returned by the function, Eventually will pass the first value to the matcher and require that all others are zero-valued. This allows you to pass Eventually a function that returns a value and an error - a common pattern in Go. For example, consider a method that returns a value and an error: func FetchFromDB() (string, error) Then Eventually(FetchFromDB).Should(Equal("got it")) will pass only if and when the returned error is nil *and* the returned string satisfies the matcher. Eventually can also accept functions that take arguments, however you must provide those arguments using .WithArguments(). For example, consider a function that takes a user-id and makes a network request to fetch a full name: func FetchFullName(userId int) (string, error) You can poll this function like so: Eventually(FetchFullName).WithArguments(1138).Should(Equal("Wookie")) It is important to note that the function passed into Eventually is invoked *synchronously* when polled. Eventually does not (in fact, it cannot) kill the function if it takes longer to return than Eventually's configured timeout. A common practice here is to use a context. Here's an example that combines Ginkgo's spec timeout support with Eventually: It("fetches the correct count", func(ctx SpecContext) { Eventually(ctx, func() int { return client.FetchCount(ctx, "/users") }).Should(BeNumerically(">=", 17)) }, SpecTimeout(time.Second)) you an also use Eventually().WithContext(ctx) to pass in the context. Passed-in contexts play nicely with passed-in arguments as long as the context appears first. You can rewrite the above example as: It("fetches the correct count", func(ctx SpecContext) { Eventually(client.FetchCount).WithContext(ctx).WithArguments("/users").Should(BeNumerically(">=", 17)) }, SpecTimeout(time.Second)) Either way the context passed to Eventually is also passed to the underlying function. Now, when Ginkgo cancels the context both the FetchCount client and Gomega will be informed and can exit. By default, when a context is passed to Eventually *without* an explicit timeout, Gomega will rely solely on the context's cancellation to determine when to stop polling. If you want to specify a timeout in addition to the context you can do so using the .WithTimeout() method. For example: Eventually(client.FetchCount).WithContext(ctx).WithTimeout(10*time.Second).Should(BeNumerically(">=", 17)) now either the context cancellation or the timeout will cause Eventually to stop polling. If, instead, you would like to opt out of this behavior and have Gomega's default timeouts govern Eventuallys that take a context you can call: EnforceDefaultTimeoutsWhenUsingContexts() in the DSL (or on a Gomega instance). Now all calls to Eventually that take a context will fail if either the context is cancelled or the default timeout elapses. **Category 3: Making assertions _in_ the function passed into Eventually** When testing complex systems it can be valuable to assert that a _set_ of assertions passes Eventually. Eventually supports this by accepting functions that take a single Gomega argument and return zero or more values. Here's an example that makes some assertions and returns a value and error: Eventually(func(g Gomega) (Widget, error) { ids, err := client.FetchIDs() g.Expect(err).NotTo(HaveOccurred()) g.Expect(ids).To(ContainElement(1138)) return client.FetchWidget(1138) }).Should(Equal(expectedWidget)) will pass only if all the assertions in the polled function pass and the return value satisfied the matcher. Eventually also supports a special case polling function that takes a single Gomega argument and returns no values. Eventually assumes such a function is making assertions and is designed to work with the Succeed matcher to validate that all assertions have passed. For example: Eventually(func(g Gomega) { model, err := client.Find(1138) g.Expect(err).NotTo(HaveOccurred()) g.Expect(model.Reticulate()).To(Succeed()) g.Expect(model.IsReticulated()).To(BeTrue()) g.Expect(model.Save()).To(Succeed()) }).Should(Succeed()) will rerun the function until all assertions pass. You can also pass additional arguments to functions that take a Gomega. The only rule is that the Gomega argument must be first. If you also want to pass the context attached to Eventually you must ensure that is the second argument. For example: Eventually(func(g Gomega, ctx context.Context, path string, expected ...string){ tok, err := client.GetToken(ctx) g.Expect(err).NotTo(HaveOccurred()) elements, err := client.Fetch(ctx, tok, path) g.Expect(err).NotTo(HaveOccurred()) g.Expect(elements).To(ConsistOf(expected)) }).WithContext(ctx).WithArguments("/names", "Joe", "Jane", "Sam").Should(Succeed()) You can ensure that you get a number of consecutive successful tries before succeeding using `MustPassRepeatedly(int)`. For Example: int count := 0 Eventually(func() bool { count++ return count > 2 }).MustPassRepeatedly(2).Should(BeTrue()) // Because we had to wait for 2 calls that returned true Expect(count).To(Equal(3)) Finally, in addition to passing timeouts and a context to Eventually you can be more explicit with Eventually's chaining configuration methods: Eventually(..., "10s", "2s", ctx).Should(...) is equivalent to Eventually(...).WithTimeout(10*time.Second).WithPolling(2*time.Second).WithContext(ctx).Should(...) */ func Eventually(actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.Eventually(actualOrCtx, args...) } // EventuallyWithOffset operates like Eventually but takes an additional // initial argument to indicate an offset in the call stack. This is useful when building helper // functions that contain matchers. To learn more, read about `ExpectWithOffset`. // // `EventuallyWithOffset` is the same as `Eventually(...).WithOffset`. // // `EventuallyWithOffset` specifying a timeout interval (and an optional polling interval) are // the same as `Eventually(...).WithOffset(...).WithTimeout` or // `Eventually(...).WithOffset(...).WithTimeout(...).WithPolling`. func EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.EventuallyWithOffset(offset, actualOrCtx, args...) } /* Consistently, like Eventually, enables making assertions on asynchronous behavior. Consistently blocks when called for a specified duration. During that duration Consistently repeatedly polls its matcher and ensures that it is satisfied. If the matcher is consistently satisfied, then Consistently will pass. Otherwise Consistently will fail. Both the total waiting duration and the polling interval are configurable as optional arguments. The first optional argument is the duration that Consistently will run for (defaults to 100ms), and the second argument is the polling interval (defaults to 10ms). As with Eventually, these intervals can be passed in as time.Duration, parsable duration strings or an integer or float number of seconds. You can also pass in an optional context.Context - Consistently will exit early (with a failure) if the context is cancelled before the waiting duration expires. Consistently accepts the same three categories of actual as Eventually, check the Eventually docs to learn more. Consistently is useful in cases where you want to assert that something *does not happen* for a period of time. For example, you may want to assert that a goroutine does *not* send data down a channel. In this case you could write: Consistently(channel, "200ms").ShouldNot(Receive()) This will block for 200 milliseconds and repeatedly check the channel and ensure nothing has been received. */ func Consistently(actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.Consistently(actualOrCtx, args...) } // ConsistentlyWithOffset operates like Consistently but takes an additional // initial argument to indicate an offset in the call stack. This is useful when building helper // functions that contain matchers. To learn more, read about `ExpectWithOffset`. // // `ConsistentlyWithOffset` is the same as `Consistently(...).WithOffset` and // optional `WithTimeout` and `WithPolling`. func ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion { ensureDefaultGomegaIsConfigured() return Default.ConsistentlyWithOffset(offset, actualOrCtx, args...) } /* StopTrying can be used to signal to Eventually and Consistently that they should abort and stop trying. This always results in a failure of the assertion - and the failure message is the content of the StopTrying signal. You can send the StopTrying signal by either returning StopTrying("message") as an error from your passed-in function _or_ by calling StopTrying("message").Now() to trigger a panic and end execution. You can also wrap StopTrying around an error with `StopTrying("message").Wrap(err)` and can attach additional objects via `StopTrying("message").Attach("description", object). When rendered, the signal will include the wrapped error and any attached objects rendered using Gomega's default formatting. Here are a couple of examples. This is how you might use StopTrying() as an error to signal that Eventually should stop: playerIndex, numPlayers := 0, 11 Eventually(func() (string, error) { if playerIndex == numPlayers { return "", StopTrying("no more players left") } name := client.FetchPlayer(playerIndex) playerIndex += 1 return name, nil }).Should(Equal("Patrick Mahomes")) And here's an example where `StopTrying().Now()` is called to halt execution immediately: Eventually(func() []string { names, err := client.FetchAllPlayers() if err == client.IRRECOVERABLE_ERROR { StopTrying("Irrecoverable error occurred").Wrap(err).Now() } return names }).Should(ContainElement("Patrick Mahomes")) */ var StopTrying = internal.StopTrying /* TryAgainAfter(<duration>) allows you to adjust the polling interval for the _next_ iteration of `Eventually` or `Consistently`. Like `StopTrying` you can either return `TryAgainAfter` as an error or trigger it immedieately with `.Now()` When `TryAgainAfter(<duration>` is triggered `Eventually` and `Consistently` will wait for that duration. If a timeout occurs before the next poll is triggered both `Eventually` and `Consistently` will always fail with the content of the TryAgainAfter message. As with StopTrying you can `.Wrap()` and error and `.Attach()` additional objects to `TryAgainAfter`. */ var TryAgainAfter = internal.TryAgainAfter /* PollingSignalError is the error returned by StopTrying() and TryAgainAfter() */ type PollingSignalError = internal.PollingSignalError // SetDefaultEventuallyTimeout sets the default timeout duration for Eventually. Eventually will repeatedly poll your condition until it succeeds, or until this timeout elapses. func SetDefaultEventuallyTimeout(t time.Duration) { Default.SetDefaultEventuallyTimeout(t) } // SetDefaultEventuallyPollingInterval sets the default polling interval for Eventually. func SetDefaultEventuallyPollingInterval(t time.Duration) { Default.SetDefaultEventuallyPollingInterval(t) } // SetDefaultConsistentlyDuration sets the default duration for Consistently. Consistently will verify that your condition is satisfied for this long. func SetDefaultConsistentlyDuration(t time.Duration) { Default.SetDefaultConsistentlyDuration(t) } // SetDefaultConsistentlyPollingInterval sets the default polling interval for Consistently. func SetDefaultConsistentlyPollingInterval(t time.Duration) { Default.SetDefaultConsistentlyPollingInterval(t) } // EnforceDefaultTimeoutsWhenUsingContexts forces `Eventually` to apply a default timeout even when a context is provided. func EnforceDefaultTimeoutsWhenUsingContexts() { Default.EnforceDefaultTimeoutsWhenUsingContexts() } // DisableDefaultTimeoutsWhenUsingContext disables the default timeout when a context is provided to `Eventually`. func DisableDefaultTimeoutsWhenUsingContext() { Default.DisableDefaultTimeoutsWhenUsingContext() } // AsyncAssertion is returned by Eventually and Consistently and polls the actual value passed into Eventually against // the matcher passed to the Should and ShouldNot methods. // // Both Should and ShouldNot take a variadic optionalDescription argument. // This argument allows you to make your failure messages more descriptive. // If a single argument of type `func() string` is passed, this function will be lazily evaluated if a failure occurs // and the returned string is used to annotate the failure message. // Otherwise, this argument is passed on to fmt.Sprintf() and then used to annotate the failure message. // // Both Should and ShouldNot return a boolean that is true if the assertion passed and false if it failed. // // Example: // // Eventually(myChannel).Should(Receive(), "Something should have come down the pipe.") // Consistently(myChannel).ShouldNot(Receive(), func() string { return "Nothing should have come down the pipe." }) type AsyncAssertion = types.AsyncAssertion // GomegaAsyncAssertion is deprecated in favor of AsyncAssertion, which does not stutter. type GomegaAsyncAssertion = types.AsyncAssertion // Assertion is returned by Ω and Expect and compares the actual value to the matcher // passed to the Should/ShouldNot and To/ToNot/NotTo methods. // // Typically Should/ShouldNot are used with Ω and To/ToNot/NotTo are used with Expect // though this is not enforced. // // All methods take a variadic optionalDescription argument. // This argument allows you to make your failure messages more descriptive. // If a single argument of type `func() string` is passed, this function will be lazily evaluated if a failure occurs // and the returned string is used to annotate the failure message. // Otherwise, this argument is passed on to fmt.Sprintf() and then used to annotate the failure message. // // All methods return a bool that is true if the assertion passed and false if it failed. // // Example: // // Ω(farm.HasCow()).Should(BeTrue(), "Farm %v should have a cow", farm) type Assertion = types.Assertion // GomegaAssertion is deprecated in favor of Assertion, which does not stutter. type GomegaAssertion = types.Assertion // OmegaMatcher is deprecated in favor of the better-named and better-organized types.GomegaMatcher but sticks around to support existing code that uses it type OmegaMatcher = types.GomegaMatcher
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/types/types.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/types/types.go
package types import ( "context" "time" ) type GomegaFailHandler func(message string, callerSkip ...int) // A simple *testing.T interface wrapper type GomegaTestingT interface { Helper() Fatalf(format string, args ...any) } // Gomega represents an object that can perform synchronous and asynchronous assertions with Gomega matchers type Gomega interface { Ω(actual any, extra ...any) Assertion Expect(actual any, extra ...any) Assertion ExpectWithOffset(offset int, actual any, extra ...any) Assertion Eventually(actualOrCtx any, args ...any) AsyncAssertion EventuallyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion Consistently(actualOrCtx any, args ...any) AsyncAssertion ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) AsyncAssertion SetDefaultEventuallyTimeout(time.Duration) SetDefaultEventuallyPollingInterval(time.Duration) SetDefaultConsistentlyDuration(time.Duration) SetDefaultConsistentlyPollingInterval(time.Duration) EnforceDefaultTimeoutsWhenUsingContexts() DisableDefaultTimeoutsWhenUsingContext() } // All Gomega matchers must implement the GomegaMatcher interface // // For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding-your-own-matchers type GomegaMatcher interface { Match(actual any) (success bool, err error) FailureMessage(actual any) (message string) NegatedFailureMessage(actual any) (message string) } /* GomegaMatchers that also match the OracleMatcher interface can convey information about whether or not their result will change upon future attempts. This allows `Eventually` and `Consistently` to short circuit if success becomes impossible. For example, a process' exit code can never change. So, gexec's Exit matcher returns `true` for `MatchMayChangeInTheFuture` until the process exits, at which point it returns `false` forevermore. */ type OracleMatcher interface { MatchMayChangeInTheFuture(actual any) bool } func MatchMayChangeInTheFuture(matcher GomegaMatcher, value any) bool { oracleMatcher, ok := matcher.(OracleMatcher) if !ok { return true } return oracleMatcher.MatchMayChangeInTheFuture(value) } // AsyncAssertions are returned by Eventually and Consistently and enable matchers to be polled repeatedly to ensure // they are eventually satisfied type AsyncAssertion interface { Should(matcher GomegaMatcher, optionalDescription ...any) bool ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool // equivalent to above To(matcher GomegaMatcher, optionalDescription ...any) bool ToNot(matcher GomegaMatcher, optionalDescription ...any) bool NotTo(matcher GomegaMatcher, optionalDescription ...any) bool WithOffset(offset int) AsyncAssertion WithTimeout(interval time.Duration) AsyncAssertion WithPolling(interval time.Duration) AsyncAssertion Within(timeout time.Duration) AsyncAssertion ProbeEvery(interval time.Duration) AsyncAssertion WithContext(ctx context.Context) AsyncAssertion WithArguments(argsToForward ...any) AsyncAssertion MustPassRepeatedly(count int) AsyncAssertion } // Assertions are returned by Ω and Expect and enable assertions against Gomega matchers type Assertion interface { Should(matcher GomegaMatcher, optionalDescription ...any) bool ShouldNot(matcher GomegaMatcher, optionalDescription ...any) bool To(matcher GomegaMatcher, optionalDescription ...any) bool ToNot(matcher GomegaMatcher, optionalDescription ...any) bool NotTo(matcher GomegaMatcher, optionalDescription ...any) bool WithOffset(offset int) Assertion Error() Assertion }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/polling_signal_error.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/polling_signal_error.go
package internal import ( "errors" "fmt" "time" ) type PollingSignalErrorType int const ( PollingSignalErrorTypeStopTrying PollingSignalErrorType = iota PollingSignalErrorTypeTryAgainAfter ) type PollingSignalError interface { error Wrap(err error) PollingSignalError Attach(description string, obj any) PollingSignalError Successfully() PollingSignalError Now() } var StopTrying = func(message string) PollingSignalError { return &PollingSignalErrorImpl{ message: message, pollingSignalErrorType: PollingSignalErrorTypeStopTrying, } } var TryAgainAfter = func(duration time.Duration) PollingSignalError { return &PollingSignalErrorImpl{ message: fmt.Sprintf("told to try again after %s", duration), duration: duration, pollingSignalErrorType: PollingSignalErrorTypeTryAgainAfter, } } type PollingSignalErrorAttachment struct { Description string Object any } type PollingSignalErrorImpl struct { message string wrappedErr error pollingSignalErrorType PollingSignalErrorType duration time.Duration successful bool Attachments []PollingSignalErrorAttachment } func (s *PollingSignalErrorImpl) Wrap(err error) PollingSignalError { s.wrappedErr = err return s } func (s *PollingSignalErrorImpl) Attach(description string, obj any) PollingSignalError { s.Attachments = append(s.Attachments, PollingSignalErrorAttachment{description, obj}) return s } func (s *PollingSignalErrorImpl) Error() string { if s.wrappedErr == nil { return s.message } else { return s.message + ": " + s.wrappedErr.Error() } } func (s *PollingSignalErrorImpl) Unwrap() error { if s == nil { return nil } return s.wrappedErr } func (s *PollingSignalErrorImpl) Successfully() PollingSignalError { s.successful = true return s } func (s *PollingSignalErrorImpl) Now() { panic(s) } func (s *PollingSignalErrorImpl) IsStopTrying() bool { return s.pollingSignalErrorType == PollingSignalErrorTypeStopTrying } func (s *PollingSignalErrorImpl) IsSuccessful() bool { return s.successful } func (s *PollingSignalErrorImpl) IsTryAgainAfter() bool { return s.pollingSignalErrorType == PollingSignalErrorTypeTryAgainAfter } func (s *PollingSignalErrorImpl) TryAgainDuration() time.Duration { return s.duration } func AsPollingSignalError(actual any) (*PollingSignalErrorImpl, bool) { if actual == nil { return nil, false } if actualErr, ok := actual.(error); ok { var target *PollingSignalErrorImpl if errors.As(actualErr, &target) { return target, true } else { return nil, false } } return nil, false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/duration_bundle.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/duration_bundle.go
package internal import ( "fmt" "os" "reflect" "time" ) type DurationBundle struct { EventuallyTimeout time.Duration EventuallyPollingInterval time.Duration ConsistentlyDuration time.Duration ConsistentlyPollingInterval time.Duration EnforceDefaultTimeoutsWhenUsingContexts bool } const ( EventuallyTimeoutEnvVarName = "GOMEGA_DEFAULT_EVENTUALLY_TIMEOUT" EventuallyPollingIntervalEnvVarName = "GOMEGA_DEFAULT_EVENTUALLY_POLLING_INTERVAL" ConsistentlyDurationEnvVarName = "GOMEGA_DEFAULT_CONSISTENTLY_DURATION" ConsistentlyPollingIntervalEnvVarName = "GOMEGA_DEFAULT_CONSISTENTLY_POLLING_INTERVAL" EnforceDefaultTimeoutsWhenUsingContextsEnvVarName = "GOMEGA_ENFORCE_DEFAULT_TIMEOUTS_WHEN_USING_CONTEXTS" ) func FetchDefaultDurationBundle() DurationBundle { _, EnforceDefaultTimeoutsWhenUsingContexts := os.LookupEnv(EnforceDefaultTimeoutsWhenUsingContextsEnvVarName) return DurationBundle{ EventuallyTimeout: durationFromEnv(EventuallyTimeoutEnvVarName, time.Second), EventuallyPollingInterval: durationFromEnv(EventuallyPollingIntervalEnvVarName, 10*time.Millisecond), ConsistentlyDuration: durationFromEnv(ConsistentlyDurationEnvVarName, 100*time.Millisecond), ConsistentlyPollingInterval: durationFromEnv(ConsistentlyPollingIntervalEnvVarName, 10*time.Millisecond), EnforceDefaultTimeoutsWhenUsingContexts: EnforceDefaultTimeoutsWhenUsingContexts, } } func durationFromEnv(key string, defaultDuration time.Duration) time.Duration { value := os.Getenv(key) if value == "" { return defaultDuration } duration, err := time.ParseDuration(value) if err != nil { panic(fmt.Sprintf("Expected a duration when using %s! Parse error %v", key, err)) } return duration } func toDuration(input any) (time.Duration, error) { duration, ok := input.(time.Duration) if ok { return duration, nil } value := reflect.ValueOf(input) kind := reflect.TypeOf(input).Kind() if reflect.Int <= kind && kind <= reflect.Int64 { return time.Duration(value.Int()) * time.Second, nil } else if reflect.Uint <= kind && kind <= reflect.Uint64 { return time.Duration(value.Uint()) * time.Second, nil } else if reflect.Float32 <= kind && kind <= reflect.Float64 { return time.Duration(value.Float() * float64(time.Second)), nil } else if reflect.String == kind { duration, err := time.ParseDuration(value.String()) if err != nil { return 0, fmt.Errorf("%#v is not a valid parsable duration string: %w", input, err) } return duration, nil } return 0, fmt.Errorf("%#v is not a valid interval. Must be a time.Duration, a parsable duration string, or a number.", input) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/gomega.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/gomega.go
package internal import ( "context" "time" "github.com/onsi/gomega/types" ) type Gomega struct { Fail types.GomegaFailHandler THelper func() DurationBundle DurationBundle } func NewGomega(bundle DurationBundle) *Gomega { return &Gomega{ Fail: nil, THelper: nil, DurationBundle: bundle, } } func (g *Gomega) IsConfigured() bool { return g.Fail != nil && g.THelper != nil } func (g *Gomega) ConfigureWithFailHandler(fail types.GomegaFailHandler) *Gomega { g.Fail = fail g.THelper = func() {} return g } func (g *Gomega) ConfigureWithT(t types.GomegaTestingT) *Gomega { g.Fail = func(message string, _ ...int) { t.Helper() t.Fatalf("\n%s", message) } g.THelper = t.Helper return g } func (g *Gomega) Ω(actual any, extra ...any) types.Assertion { return g.ExpectWithOffset(0, actual, extra...) } func (g *Gomega) Expect(actual any, extra ...any) types.Assertion { return g.ExpectWithOffset(0, actual, extra...) } func (g *Gomega) ExpectWithOffset(offset int, actual any, extra ...any) types.Assertion { return NewAssertion(actual, g, offset, extra...) } func (g *Gomega) Eventually(actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeEventually, 0, actualOrCtx, args...) } func (g *Gomega) EventuallyWithOffset(offset int, actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeEventually, offset, actualOrCtx, args...) } func (g *Gomega) Consistently(actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeConsistently, 0, actualOrCtx, args...) } func (g *Gomega) ConsistentlyWithOffset(offset int, actualOrCtx any, args ...any) types.AsyncAssertion { return g.makeAsyncAssertion(AsyncAssertionTypeConsistently, offset, actualOrCtx, args...) } func (g *Gomega) makeAsyncAssertion(asyncAssertionType AsyncAssertionType, offset int, actualOrCtx any, args ...any) types.AsyncAssertion { baseOffset := 3 timeoutInterval := -time.Duration(1) pollingInterval := -time.Duration(1) intervals := []any{} var ctx context.Context actual := actualOrCtx startingIndex := 0 if _, isCtx := actualOrCtx.(context.Context); isCtx && len(args) > 0 { // the first argument is a context, we should accept it as the context _only if_ it is **not** the only argument **and** the second argument is not a parseable duration // this is due to an unfortunate ambiguity in early version of Gomega in which multi-type durations are allowed after the actual if _, err := toDuration(args[0]); err != nil { ctx = actualOrCtx.(context.Context) actual = args[0] startingIndex = 1 } } for _, arg := range args[startingIndex:] { switch v := arg.(type) { case context.Context: ctx = v default: intervals = append(intervals, arg) } } var err error if len(intervals) > 0 { timeoutInterval, err = toDuration(intervals[0]) if err != nil { g.Fail(err.Error(), offset+baseOffset) } } if len(intervals) > 1 { pollingInterval, err = toDuration(intervals[1]) if err != nil { g.Fail(err.Error(), offset+baseOffset) } } return NewAsyncAssertion(asyncAssertionType, actual, g, timeoutInterval, pollingInterval, 1, ctx, offset) } func (g *Gomega) SetDefaultEventuallyTimeout(t time.Duration) { g.DurationBundle.EventuallyTimeout = t } func (g *Gomega) SetDefaultEventuallyPollingInterval(t time.Duration) { g.DurationBundle.EventuallyPollingInterval = t } func (g *Gomega) SetDefaultConsistentlyDuration(t time.Duration) { g.DurationBundle.ConsistentlyDuration = t } func (g *Gomega) SetDefaultConsistentlyPollingInterval(t time.Duration) { g.DurationBundle.ConsistentlyPollingInterval = t } func (g *Gomega) EnforceDefaultTimeoutsWhenUsingContexts() { g.DurationBundle.EnforceDefaultTimeoutsWhenUsingContexts = true } func (g *Gomega) DisableDefaultTimeoutsWhenUsingContext() { g.DurationBundle.EnforceDefaultTimeoutsWhenUsingContexts = false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/async_assertion.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/async_assertion.go
package internal import ( "context" "errors" "fmt" "reflect" "runtime" "sync" "time" "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" ) var errInterface = reflect.TypeOf((*error)(nil)).Elem() var gomegaType = reflect.TypeOf((*types.Gomega)(nil)).Elem() var contextType = reflect.TypeOf(new(context.Context)).Elem() type formattedGomegaError interface { FormattedGomegaError() string } type asyncPolledActualError struct { message string } func (err *asyncPolledActualError) Error() string { return err.message } func (err *asyncPolledActualError) FormattedGomegaError() string { return err.message } type contextWithAttachProgressReporter interface { AttachProgressReporter(func() string) func() } type asyncGomegaHaltExecutionError struct{} func (a asyncGomegaHaltExecutionError) GinkgoRecoverShouldIgnoreThisPanic() {} func (a asyncGomegaHaltExecutionError) Error() string { return `An assertion has failed in a goroutine. You should call defer GinkgoRecover() at the top of the goroutine that caused this panic. This will allow Ginkgo and Gomega to correctly capture and manage this panic.` } type AsyncAssertionType uint const ( AsyncAssertionTypeEventually AsyncAssertionType = iota AsyncAssertionTypeConsistently ) func (at AsyncAssertionType) String() string { switch at { case AsyncAssertionTypeEventually: return "Eventually" case AsyncAssertionTypeConsistently: return "Consistently" } return "INVALID ASYNC ASSERTION TYPE" } type AsyncAssertion struct { asyncType AsyncAssertionType actualIsFunc bool actual any argsToForward []any timeoutInterval time.Duration pollingInterval time.Duration mustPassRepeatedly int ctx context.Context offset int g *Gomega } func NewAsyncAssertion(asyncType AsyncAssertionType, actualInput any, g *Gomega, timeoutInterval time.Duration, pollingInterval time.Duration, mustPassRepeatedly int, ctx context.Context, offset int) *AsyncAssertion { out := &AsyncAssertion{ asyncType: asyncType, timeoutInterval: timeoutInterval, pollingInterval: pollingInterval, mustPassRepeatedly: mustPassRepeatedly, offset: offset, ctx: ctx, g: g, } out.actual = actualInput if actualInput != nil && reflect.TypeOf(actualInput).Kind() == reflect.Func { out.actualIsFunc = true } return out } func (assertion *AsyncAssertion) WithOffset(offset int) types.AsyncAssertion { assertion.offset = offset return assertion } func (assertion *AsyncAssertion) WithTimeout(interval time.Duration) types.AsyncAssertion { assertion.timeoutInterval = interval return assertion } func (assertion *AsyncAssertion) WithPolling(interval time.Duration) types.AsyncAssertion { assertion.pollingInterval = interval return assertion } func (assertion *AsyncAssertion) Within(timeout time.Duration) types.AsyncAssertion { assertion.timeoutInterval = timeout return assertion } func (assertion *AsyncAssertion) ProbeEvery(interval time.Duration) types.AsyncAssertion { assertion.pollingInterval = interval return assertion } func (assertion *AsyncAssertion) WithContext(ctx context.Context) types.AsyncAssertion { assertion.ctx = ctx return assertion } func (assertion *AsyncAssertion) WithArguments(argsToForward ...any) types.AsyncAssertion { assertion.argsToForward = argsToForward return assertion } func (assertion *AsyncAssertion) MustPassRepeatedly(count int) types.AsyncAssertion { assertion.mustPassRepeatedly = count return assertion } func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Asynchronous assertion", optionalDescription...) return assertion.match(matcher, true, optionalDescription...) } func (assertion *AsyncAssertion) To(matcher types.GomegaMatcher, optionalDescription ...any) bool { return assertion.Should(matcher, optionalDescription...) } func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Asynchronous assertion", optionalDescription...) return assertion.match(matcher, false, optionalDescription...) } func (assertion *AsyncAssertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { return assertion.ShouldNot(matcher, optionalDescription...) } func (assertion *AsyncAssertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...any) bool { return assertion.ShouldNot(matcher, optionalDescription...) } func (assertion *AsyncAssertion) buildDescription(optionalDescription ...any) string { switch len(optionalDescription) { case 0: return "" case 1: if describe, ok := optionalDescription[0].(func() string); ok { return describe() + "\n" } } return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" } func (assertion *AsyncAssertion) processReturnValues(values []reflect.Value) (any, error) { if len(values) == 0 { return nil, &asyncPolledActualError{ message: fmt.Sprintf("The function passed to %s did not return any values", assertion.asyncType), } } actual := values[0].Interface() if _, ok := AsPollingSignalError(actual); ok { return actual, actual.(error) } var err error for i, extraValue := range values[1:] { extra := extraValue.Interface() if extra == nil { continue } if _, ok := AsPollingSignalError(extra); ok { return actual, extra.(error) } extraType := reflect.TypeOf(extra) zero := reflect.Zero(extraType).Interface() if reflect.DeepEqual(extra, zero) { continue } if i == len(values)-2 && extraType.Implements(errInterface) { err = extra.(error) } if err == nil { err = &asyncPolledActualError{ message: fmt.Sprintf("The function passed to %s had an unexpected non-nil/non-zero return value at index %d:\n%s", assertion.asyncType, i+1, format.Object(extra, 1)), } } } return actual, err } func (assertion *AsyncAssertion) invalidFunctionError(t reflect.Type) error { return fmt.Errorf(`The function passed to %s had an invalid signature of %s. Functions passed to %s must either: (a) have return values or (b) take a Gomega interface as their first argument and use that Gomega instance to make assertions. You can learn more at https://onsi.github.io/gomega/#eventually `, assertion.asyncType, t, assertion.asyncType) } func (assertion *AsyncAssertion) noConfiguredContextForFunctionError() error { return fmt.Errorf(`The function passed to %s requested a context.Context, but no context has been provided. Please pass one in using %s().WithContext(). You can learn more at https://onsi.github.io/gomega/#eventually `, assertion.asyncType, assertion.asyncType) } func (assertion *AsyncAssertion) argumentMismatchError(t reflect.Type, numProvided int) error { have := "have" if numProvided == 1 { have = "has" } return fmt.Errorf(`The function passed to %s has signature %s takes %d arguments but %d %s been provided. Please use %s().WithArguments() to pass the correct set of arguments. You can learn more at https://onsi.github.io/gomega/#eventually `, assertion.asyncType, t, t.NumIn(), numProvided, have, assertion.asyncType) } func (assertion *AsyncAssertion) invalidMustPassRepeatedlyError(reason string) error { return fmt.Errorf(`Invalid use of MustPassRepeatedly with %s %s You can learn more at https://onsi.github.io/gomega/#eventually `, assertion.asyncType, reason) } func (assertion *AsyncAssertion) buildActualPoller() (func() (any, error), error) { if !assertion.actualIsFunc { return func() (any, error) { return assertion.actual, nil }, nil } actualValue := reflect.ValueOf(assertion.actual) actualType := reflect.TypeOf(assertion.actual) numIn, numOut, isVariadic := actualType.NumIn(), actualType.NumOut(), actualType.IsVariadic() if numIn == 0 && numOut == 0 { return nil, assertion.invalidFunctionError(actualType) } takesGomega, takesContext := false, false if numIn > 0 { takesGomega, takesContext = actualType.In(0).Implements(gomegaType), actualType.In(0).Implements(contextType) } if takesGomega && numIn > 1 && actualType.In(1).Implements(contextType) { takesContext = true } if takesContext && len(assertion.argsToForward) > 0 && reflect.TypeOf(assertion.argsToForward[0]).Implements(contextType) { takesContext = false } if !takesGomega && numOut == 0 { return nil, assertion.invalidFunctionError(actualType) } if takesContext && assertion.ctx == nil { return nil, assertion.noConfiguredContextForFunctionError() } var assertionFailure error inValues := []reflect.Value{} if takesGomega { inValues = append(inValues, reflect.ValueOf(NewGomega(assertion.g.DurationBundle).ConfigureWithFailHandler(func(message string, callerSkip ...int) { skip := 0 if len(callerSkip) > 0 { skip = callerSkip[0] } _, file, line, _ := runtime.Caller(skip + 1) assertionFailure = &asyncPolledActualError{ message: fmt.Sprintf("The function passed to %s failed at %s:%d with:\n%s", assertion.asyncType, file, line, message), } // we throw an asyncGomegaHaltExecutionError so that defer GinkgoRecover() can catch this error if the user makes an assertion in a goroutine panic(asyncGomegaHaltExecutionError{}) }))) } if takesContext { inValues = append(inValues, reflect.ValueOf(assertion.ctx)) } for _, arg := range assertion.argsToForward { inValues = append(inValues, reflect.ValueOf(arg)) } if !isVariadic && numIn != len(inValues) { return nil, assertion.argumentMismatchError(actualType, len(inValues)) } else if isVariadic && len(inValues) < numIn-1 { return nil, assertion.argumentMismatchError(actualType, len(inValues)) } if assertion.mustPassRepeatedly != 1 && assertion.asyncType != AsyncAssertionTypeEventually { return nil, assertion.invalidMustPassRepeatedlyError("it can only be used with Eventually") } if assertion.mustPassRepeatedly < 1 { return nil, assertion.invalidMustPassRepeatedlyError("parameter can't be < 1") } return func() (actual any, err error) { var values []reflect.Value assertionFailure = nil defer func() { if numOut == 0 && takesGomega { actual = assertionFailure } else { actual, err = assertion.processReturnValues(values) _, isAsyncError := AsPollingSignalError(err) if assertionFailure != nil && !isAsyncError { err = assertionFailure } } if e := recover(); e != nil { if _, isAsyncError := AsPollingSignalError(e); isAsyncError { err = e.(error) } else if assertionFailure == nil { panic(e) } } }() values = actualValue.Call(inValues) return }, nil } func (assertion *AsyncAssertion) afterTimeout() <-chan time.Time { if assertion.timeoutInterval >= 0 { return time.After(assertion.timeoutInterval) } if assertion.asyncType == AsyncAssertionTypeConsistently { return time.After(assertion.g.DurationBundle.ConsistentlyDuration) } else { if assertion.ctx == nil || assertion.g.DurationBundle.EnforceDefaultTimeoutsWhenUsingContexts { return time.After(assertion.g.DurationBundle.EventuallyTimeout) } else { return nil } } } func (assertion *AsyncAssertion) afterPolling() <-chan time.Time { if assertion.pollingInterval >= 0 { return time.After(assertion.pollingInterval) } if assertion.asyncType == AsyncAssertionTypeConsistently { return time.After(assertion.g.DurationBundle.ConsistentlyPollingInterval) } else { return time.After(assertion.g.DurationBundle.EventuallyPollingInterval) } } func (assertion *AsyncAssertion) matcherSaysStopTrying(matcher types.GomegaMatcher, value any) bool { if assertion.actualIsFunc || types.MatchMayChangeInTheFuture(matcher, value) { return false } return true } func (assertion *AsyncAssertion) pollMatcher(matcher types.GomegaMatcher, value any) (matches bool, err error) { defer func() { if e := recover(); e != nil { if _, isAsyncError := AsPollingSignalError(e); isAsyncError { err = e.(error) } else { panic(e) } } }() matches, err = matcher.Match(value) return } func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...any) bool { timer := time.Now() timeout := assertion.afterTimeout() lock := sync.Mutex{} var matches, hasLastValidActual bool var actual, lastValidActual any var actualErr, matcherErr error var oracleMatcherSaysStop bool assertion.g.THelper() pollActual, buildActualPollerErr := assertion.buildActualPoller() if buildActualPollerErr != nil { assertion.g.Fail(buildActualPollerErr.Error(), 2+assertion.offset) return false } actual, actualErr = pollActual() if actualErr == nil { lastValidActual = actual hasLastValidActual = true oracleMatcherSaysStop = assertion.matcherSaysStopTrying(matcher, actual) matches, matcherErr = assertion.pollMatcher(matcher, actual) } renderError := func(preamble string, err error) string { message := "" if pollingSignalErr, ok := AsPollingSignalError(err); ok { message = err.Error() for _, attachment := range pollingSignalErr.Attachments { message += fmt.Sprintf("\n%s:\n", attachment.Description) message += format.Object(attachment.Object, 1) } } else { message = preamble + "\n" + format.Object(err, 1) } return message } messageGenerator := func() string { // can be called out of band by Ginkgo if the user requests a progress report lock.Lock() defer lock.Unlock() message := "" if actualErr == nil { if matcherErr == nil { if desiredMatch != matches { if desiredMatch { message += matcher.FailureMessage(actual) } else { message += matcher.NegatedFailureMessage(actual) } } else { if assertion.asyncType == AsyncAssertionTypeConsistently { message += "There is no failure as the matcher passed to Consistently has not yet failed" } else { message += "There is no failure as the matcher passed to Eventually succeeded on its most recent iteration" } } } else { var fgErr formattedGomegaError if errors.As(matcherErr, &fgErr) { message += fgErr.FormattedGomegaError() + "\n" } else { message += renderError(fmt.Sprintf("The matcher passed to %s returned the following error:", assertion.asyncType), matcherErr) } } } else { var fgErr formattedGomegaError if errors.As(actualErr, &fgErr) { message += fgErr.FormattedGomegaError() + "\n" } else { message += renderError(fmt.Sprintf("The function passed to %s returned the following error:", assertion.asyncType), actualErr) } if hasLastValidActual { message += fmt.Sprintf("\nAt one point, however, the function did return successfully.\nYet, %s failed because", assertion.asyncType) _, e := matcher.Match(lastValidActual) if e != nil { message += renderError(" the matcher returned the following error:", e) } else { message += " the matcher was not satisfied:\n" if desiredMatch { message += matcher.FailureMessage(lastValidActual) } else { message += matcher.NegatedFailureMessage(lastValidActual) } } } } description := assertion.buildDescription(optionalDescription...) return fmt.Sprintf("%s%s", description, message) } fail := func(preamble string) { assertion.g.THelper() assertion.g.Fail(fmt.Sprintf("%s after %.3fs.\n%s", preamble, time.Since(timer).Seconds(), messageGenerator()), 3+assertion.offset) } var contextDone <-chan struct{} if assertion.ctx != nil { contextDone = assertion.ctx.Done() if v, ok := assertion.ctx.Value("GINKGO_SPEC_CONTEXT").(contextWithAttachProgressReporter); ok { detach := v.AttachProgressReporter(messageGenerator) defer detach() } } // Used to count the number of times in a row a step passed passedRepeatedlyCount := 0 for { var nextPoll <-chan time.Time = nil var isTryAgainAfterError = false for _, err := range []error{actualErr, matcherErr} { if pollingSignalErr, ok := AsPollingSignalError(err); ok { if pollingSignalErr.IsStopTrying() { if pollingSignalErr.IsSuccessful() { if assertion.asyncType == AsyncAssertionTypeEventually { fail("Told to stop trying (and ignoring call to Successfully(), as it is only relevant with Consistently)") } else { return true // early escape hatch for Consistently } } else { fail("Told to stop trying") } return false } if pollingSignalErr.IsTryAgainAfter() { nextPoll = time.After(pollingSignalErr.TryAgainDuration()) isTryAgainAfterError = true } } } if actualErr == nil && matcherErr == nil && matches == desiredMatch { if assertion.asyncType == AsyncAssertionTypeEventually { passedRepeatedlyCount += 1 if passedRepeatedlyCount == assertion.mustPassRepeatedly { return true } } } else if !isTryAgainAfterError { if assertion.asyncType == AsyncAssertionTypeConsistently { fail("Failed") return false } // Reset the consecutive pass count passedRepeatedlyCount = 0 } if oracleMatcherSaysStop { if assertion.asyncType == AsyncAssertionTypeEventually { fail("No future change is possible. Bailing out early") return false } else { return true } } if nextPoll == nil { nextPoll = assertion.afterPolling() } select { case <-nextPoll: a, e := pollActual() lock.Lock() actual, actualErr = a, e lock.Unlock() if actualErr == nil { lock.Lock() lastValidActual = actual hasLastValidActual = true lock.Unlock() oracleMatcherSaysStop = assertion.matcherSaysStopTrying(matcher, actual) m, e := assertion.pollMatcher(matcher, actual) lock.Lock() matches, matcherErr = m, e lock.Unlock() } case <-contextDone: err := context.Cause(assertion.ctx) if err != nil && err != context.Canceled { fail(fmt.Sprintf("Context was cancelled (cause: %s)", err)) } else { fail("Context was cancelled") } return false case <-timeout: if assertion.asyncType == AsyncAssertionTypeEventually { fail("Timed out") return false } else { if isTryAgainAfterError { fail("Timed out while waiting on TryAgainAfter") return false } return true } } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/assertion.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/assertion.go
package internal import ( "fmt" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" ) type Assertion struct { actuals []any // actual value plus all extra values actualIndex int // value to pass to the matcher vet vetinari // the vet to call before calling Gomega matcher offset int g *Gomega } // ...obligatory discworld reference, as "vetineer" doesn't sound ... quite right. type vetinari func(assertion *Assertion, optionalDescription ...any) bool func NewAssertion(actualInput any, g *Gomega, offset int, extra ...any) *Assertion { return &Assertion{ actuals: append([]any{actualInput}, extra...), actualIndex: 0, vet: (*Assertion).vetActuals, offset: offset, g: g, } } func (assertion *Assertion) WithOffset(offset int) types.Assertion { assertion.offset = offset return assertion } func (assertion *Assertion) Error() types.Assertion { return &Assertion{ actuals: assertion.actuals, actualIndex: len(assertion.actuals) - 1, vet: (*Assertion).vetError, offset: assertion.offset, g: assertion.g, } } func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, true, optionalDescription...) } func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, true, optionalDescription...) } func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...any) bool { assertion.g.THelper() vetOptionalDescription("Assertion", optionalDescription...) return assertion.vet(assertion, optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } func (assertion *Assertion) buildDescription(optionalDescription ...any) string { switch len(optionalDescription) { case 0: return "" case 1: if describe, ok := optionalDescription[0].(func() string); ok { return describe() + "\n" } } return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" } func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...any) bool { actualInput := assertion.actuals[assertion.actualIndex] matches, err := matcher.Match(actualInput) assertion.g.THelper() if err != nil { description := assertion.buildDescription(optionalDescription...) assertion.g.Fail(description+err.Error(), 2+assertion.offset) return false } if matches != desiredMatch { var message string if desiredMatch { message = matcher.FailureMessage(actualInput) } else { message = matcher.NegatedFailureMessage(actualInput) } description := assertion.buildDescription(optionalDescription...) assertion.g.Fail(description+message, 2+assertion.offset) return false } return true } // vetActuals vets the actual values, with the (optional) exception of a // specific value, such as the first value in case non-error assertions, or the // last value in case of Error()-based assertions. func (assertion *Assertion) vetActuals(optionalDescription ...any) bool { success, message := vetActuals(assertion.actuals, assertion.actualIndex) if success { return true } description := assertion.buildDescription(optionalDescription...) assertion.g.THelper() assertion.g.Fail(description+message, 2+assertion.offset) return false } // vetError vets the actual values, except for the final error value, in case // the final error value is non-zero. Otherwise, it doesn't vet the actual // values, as these are allowed to take on any values unless there is a non-zero // error value. func (assertion *Assertion) vetError(optionalDescription ...any) bool { if err := assertion.actuals[assertion.actualIndex]; err != nil { // Go error result idiom: all other actual values must be zero values. return assertion.vetActuals(optionalDescription...) } return true } // vetActuals vets a slice of actual values, optionally skipping a particular // value slice element, such as the first or last value slice element. func vetActuals(actuals []any, skipIndex int) (bool, string) { for i, actual := range actuals { if i == skipIndex { continue } if actual != nil { zeroValue := reflect.Zero(reflect.TypeOf(actual)).Interface() if !reflect.DeepEqual(zeroValue, actual) { var message string if err, ok := actual.(error); ok { message = fmt.Sprintf("Unexpected error: %s\n%s", err, format.Object(err, 1)) } else { message = fmt.Sprintf("Unexpected non-nil/non-zero argument at index %d:\n\t<%T>: %#v", i, actual, actual) } return false, message } } } return true, "" }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/vetoptdesc.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/vetoptdesc.go
package internal import ( "fmt" "github.com/onsi/gomega/types" ) // vetOptionalDescription vets the optional description args: if it finds any // Gomega matcher at the beginning it panics. This allows for rendering Gomega // matchers as part of an optional Description, as long as they're not in the // first slot. func vetOptionalDescription(assertion string, optionalDescription ...any) { if len(optionalDescription) == 0 { return } if _, isGomegaMatcher := optionalDescription[0].(types.GomegaMatcher); isGomegaMatcher { panic(fmt.Sprintf("%s has a GomegaMatcher as the first element of optionalDescription.\n\t"+ "Do you mean to use And/Or/SatisfyAll/SatisfyAny to combine multiple matchers?", assertion)) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/gutil/post_ioutil.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/gutil/post_ioutil.go
//go:build go1.16 // +build go1.16 // Package gutil is a replacement for ioutil, which should not be used in new // code as of Go 1.16. With Go 1.16 and higher, this implementation // uses the ioutil replacement functions in "io" and "os" with some // Gomega specifics. This means that we should not get deprecation warnings // for ioutil when they are added. package gutil import ( "io" "os" ) func NopCloser(r io.Reader) io.ReadCloser { return io.NopCloser(r) } func ReadAll(r io.Reader) ([]byte, error) { return io.ReadAll(r) } func ReadDir(dirname string) ([]string, error) { entries, err := os.ReadDir(dirname) if err != nil { return nil, err } var names []string for _, entry := range entries { names = append(names, entry.Name()) } return names, nil } func ReadFile(filename string) ([]byte, error) { return os.ReadFile(filename) } func MkdirTemp(dir, pattern string) (string, error) { return os.MkdirTemp(dir, pattern) } func WriteFile(filename string, data []byte) error { return os.WriteFile(filename, data, 0644) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/gutil/using_ioutil.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/internal/gutil/using_ioutil.go
//go:build !go1.16 // +build !go1.16 // Package gutil is a replacement for ioutil, which should not be used in new // code as of Go 1.16. With Go 1.15 and lower, this implementation // uses the ioutil functions, meaning that although Gomega is not officially // supported on these versions, it is still likely to work. package gutil import ( "io" "io/ioutil" ) func NopCloser(r io.Reader) io.ReadCloser { return ioutil.NopCloser(r) } func ReadAll(r io.Reader) ([]byte, error) { return ioutil.ReadAll(r) } func ReadDir(dirname string) ([]string, error) { files, err := ioutil.ReadDir(dirname) if err != nil { return nil, err } var names []string for _, file := range files { names = append(names, file.Name()) } return names, nil } func ReadFile(filename string) ([]byte, error) { return ioutil.ReadFile(filename) } func MkdirTemp(dir, pattern string) (string, error) { return ioutil.TempDir(dir, pattern) } func WriteFile(filename string, data []byte) error { return ioutil.WriteFile(filename, data, 0644) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go
// untested sections: 2 package matchers import "github.com/onsi/gomega/format" type BeNilMatcher struct { } func (matcher *BeNilMatcher) Match(actual any) (success bool, err error) { return isNil(actual), nil } func (matcher *BeNilMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be nil") } func (matcher *BeNilMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be nil") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go
// untested sections: 2 package matchers import ( "fmt" "github.com/onsi/gomega/format" ) type BeFalseMatcher struct { Reason string } func (matcher *BeFalseMatcher) Match(actual any) (success bool, err error) { if !isBool(actual) { return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) } return actual == false, nil } func (matcher *BeFalseMatcher) FailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "to be false") } else { return matcher.Reason } } func (matcher *BeFalseMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "not to be false") } else { return fmt.Sprintf(`Expected not false but got false\nNegation of "%s" failed`, matcher.Reason) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/and.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/and.go
package matchers import ( "fmt" "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" ) type AndMatcher struct { Matchers []types.GomegaMatcher // state firstFailedMatcher types.GomegaMatcher } func (m *AndMatcher) Match(actual any) (success bool, err error) { m.firstFailedMatcher = nil for _, matcher := range m.Matchers { success, err := matcher.Match(actual) if !success || err != nil { m.firstFailedMatcher = matcher return false, err } } return true, nil } func (m *AndMatcher) FailureMessage(actual any) (message string) { return m.firstFailedMatcher.FailureMessage(actual) } func (m *AndMatcher) NegatedFailureMessage(actual any) (message string) { // not the most beautiful list of matchers, but not bad either... return format.Message(actual, fmt.Sprintf("To not satisfy all of these matchers: %s", m.Matchers)) } func (m *AndMatcher) MatchMayChangeInTheFuture(actual any) bool { /* Example with 3 matchers: A, B, C Match evaluates them: T, F, <?> => F So match is currently F, what should MatchMayChangeInTheFuture() return? Seems like it only depends on B, since currently B MUST change to allow the result to become T Match eval: T, T, T => T So match is currently T, what should MatchMayChangeInTheFuture() return? Seems to depend on ANY of them being able to change to F. */ if m.firstFailedMatcher == nil { // so all matchers succeeded.. Any one of them changing would change the result. for _, matcher := range m.Matchers { if types.MatchMayChangeInTheFuture(matcher, actual) { return true } } return false // none of were going to change } // one of the matchers failed.. it must be able to change in order to affect the result return types.MatchMayChangeInTheFuture(m.firstFailedMatcher, actual) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go
// untested sections: 3 package matchers import ( "fmt" "time" "github.com/onsi/gomega/format" ) type BeTemporallyMatcher struct { Comparator string CompareTo time.Time Threshold []time.Duration } func (matcher *BeTemporallyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo) } func (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo) } func (matcher *BeTemporallyMatcher) Match(actual any) (bool, error) { // predicate to test for time.Time type isTime := func(t any) bool { _, ok := t.(time.Time) return ok } if !isTime(actual) { return false, fmt.Errorf("Expected a time.Time. Got:\n%s", format.Object(actual, 1)) } switch matcher.Comparator { case "==", "~", ">", ">=", "<", "<=": default: return false, fmt.Errorf("Unknown comparator: %s", matcher.Comparator) } var threshold = time.Millisecond if len(matcher.Threshold) == 1 { threshold = matcher.Threshold[0] } return matcher.matchTimes(actual.(time.Time), matcher.CompareTo, threshold), nil } func (matcher *BeTemporallyMatcher) matchTimes(actual, compareTo time.Time, threshold time.Duration) (success bool) { switch matcher.Comparator { case "==": return actual.Equal(compareTo) case "~": diff := actual.Sub(compareTo) return -threshold <= diff && diff <= threshold case ">": return actual.After(compareTo) case ">=": return !actual.Before(compareTo) case "<": return actual.Before(compareTo) case "<=": return !actual.After(compareTo) } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go
package matchers import ( "bytes" "encoding/xml" "errors" "fmt" "io" "reflect" "sort" "strings" "github.com/onsi/gomega/format" "golang.org/x/net/html/charset" ) type MatchXMLMatcher struct { XMLToMatch any } func (matcher *MatchXMLMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.formattedPrint(actual) if err != nil { return false, err } aval, err := parseXmlContent(actualString) if err != nil { return false, fmt.Errorf("Actual '%s' should be valid XML, but it is not.\nUnderlying error:%s", actualString, err) } eval, err := parseXmlContent(expectedString) if err != nil { return false, fmt.Errorf("Expected '%s' should be valid XML, but it is not.\nUnderlying error:%s", expectedString, err) } return reflect.DeepEqual(aval, eval), nil } func (matcher *MatchXMLMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.formattedPrint(actual) return fmt.Sprintf("Expected\n%s\nto match XML of\n%s", actualString, expectedString) } func (matcher *MatchXMLMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.formattedPrint(actual) return fmt.Sprintf("Expected\n%s\nnot to match XML of\n%s", actualString, expectedString) } func (matcher *MatchXMLMatcher) formattedPrint(actual any) (actualString, expectedString string, err error) { var ok bool actualString, ok = toString(actual) if !ok { return "", "", fmt.Errorf("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) } expectedString, ok = toString(matcher.XMLToMatch) if !ok { return "", "", fmt.Errorf("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.XMLToMatch, 1)) } return actualString, expectedString, nil } func parseXmlContent(content string) (*xmlNode, error) { allNodes := []*xmlNode{} dec := newXmlDecoder(strings.NewReader(content)) for { tok, err := dec.Token() if err != nil { if err == io.EOF { break } return nil, fmt.Errorf("failed to decode next token: %v", err) // untested section } lastNodeIndex := len(allNodes) - 1 var lastNode *xmlNode if len(allNodes) > 0 { lastNode = allNodes[lastNodeIndex] } else { lastNode = &xmlNode{} } switch tok := tok.(type) { case xml.StartElement: attrs := attributesSlice(tok.Attr) sort.Sort(attrs) allNodes = append(allNodes, &xmlNode{XMLName: tok.Name, XMLAttr: tok.Attr}) case xml.EndElement: if len(allNodes) > 1 { allNodes[lastNodeIndex-1].Nodes = append(allNodes[lastNodeIndex-1].Nodes, lastNode) allNodes = allNodes[:lastNodeIndex] } case xml.CharData: lastNode.Content = append(lastNode.Content, tok.Copy()...) case xml.Comment: lastNode.Comments = append(lastNode.Comments, tok.Copy()) // untested section case xml.ProcInst: lastNode.ProcInsts = append(lastNode.ProcInsts, tok.Copy()) } } if len(allNodes) == 0 { return nil, errors.New("found no nodes") } firstNode := allNodes[0] trimParentNodesContentSpaces(firstNode) return firstNode, nil } func newXmlDecoder(reader io.Reader) *xml.Decoder { dec := xml.NewDecoder(reader) dec.CharsetReader = charset.NewReaderLabel return dec } func trimParentNodesContentSpaces(node *xmlNode) { if len(node.Nodes) > 0 { node.Content = bytes.TrimSpace(node.Content) for _, childNode := range node.Nodes { trimParentNodesContentSpaces(childNode) } } } type xmlNode struct { XMLName xml.Name Comments []xml.Comment ProcInsts []xml.ProcInst XMLAttr []xml.Attr Content []byte Nodes []*xmlNode }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go
// untested sections: 3 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type BeSentMatcher struct { Arg any channelClosed bool } func (matcher *BeSentMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("BeSent expects a channel. Got:\n%s", format.Object(actual, 1)) } channelType := reflect.TypeOf(actual) channelValue := reflect.ValueOf(actual) if channelType.ChanDir() == reflect.RecvDir { return false, fmt.Errorf("BeSent matcher cannot be passed a receive-only channel. Got:\n%s", format.Object(actual, 1)) } argType := reflect.TypeOf(matcher.Arg) assignable := argType.AssignableTo(channelType.Elem()) if !assignable { return false, fmt.Errorf("Cannot pass:\n%s to the channel:\n%s\nThe types don't match.", format.Object(matcher.Arg, 1), format.Object(actual, 1)) } argValue := reflect.ValueOf(matcher.Arg) defer func() { if e := recover(); e != nil { success = false err = fmt.Errorf("Cannot send to a closed channel") matcher.channelClosed = true } }() winnerIndex, _, _ := reflect.Select([]reflect.SelectCase{ {Dir: reflect.SelectSend, Chan: channelValue, Send: argValue}, {Dir: reflect.SelectDefault}, }) var didSend bool if winnerIndex == 0 { didSend = true } return didSend, nil } func (matcher *BeSentMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to send:", matcher.Arg) } func (matcher *BeSentMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to send:", matcher.Arg) } func (matcher *BeSentMatcher) MatchMayChangeInTheFuture(actual any) bool { if !isChan(actual) { return false } return !matcher.channelClosed }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/with_transform.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/with_transform.go
package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/types" ) type WithTransformMatcher struct { // input Transform any // must be a function of one parameter that returns one value and an optional error Matcher types.GomegaMatcher // cached value transformArgType reflect.Type // state transformedValue any } // reflect.Type for error var errorT = reflect.TypeOf((*error)(nil)).Elem() func NewWithTransformMatcher(transform any, matcher types.GomegaMatcher) *WithTransformMatcher { if transform == nil { panic("transform function cannot be nil") } txType := reflect.TypeOf(transform) if txType.NumIn() != 1 { panic("transform function must have 1 argument") } if numout := txType.NumOut(); numout != 1 { if numout != 2 || !txType.Out(1).AssignableTo(errorT) { panic("transform function must either have 1 return value, or 1 return value plus 1 error value") } } return &WithTransformMatcher{ Transform: transform, Matcher: matcher, transformArgType: reflect.TypeOf(transform).In(0), } } func (m *WithTransformMatcher) Match(actual any) (bool, error) { // prepare a parameter to pass to the Transform function var param reflect.Value if actual != nil && reflect.TypeOf(actual).AssignableTo(m.transformArgType) { // The dynamic type of actual is compatible with the transform argument. param = reflect.ValueOf(actual) } else if actual == nil && m.transformArgType.Kind() == reflect.Interface { // The dynamic type of actual is unknown, so there's no way to make its // reflect.Value. Create a nil of the transform argument, which is known. param = reflect.Zero(m.transformArgType) } else { return false, fmt.Errorf("Transform function expects '%s' but we have '%T'", m.transformArgType, actual) } // call the Transform function with `actual` fn := reflect.ValueOf(m.Transform) result := fn.Call([]reflect.Value{param}) if len(result) == 2 { if !result[1].IsNil() { return false, fmt.Errorf("Transform function failed: %s", result[1].Interface().(error).Error()) } } m.transformedValue = result[0].Interface() // expect exactly one value return m.Matcher.Match(m.transformedValue) } func (m *WithTransformMatcher) FailureMessage(_ any) (message string) { return m.Matcher.FailureMessage(m.transformedValue) } func (m *WithTransformMatcher) NegatedFailureMessage(_ any) (message string) { return m.Matcher.NegatedFailureMessage(m.transformedValue) } func (m *WithTransformMatcher) MatchMayChangeInTheFuture(_ any) bool { // TODO: Maybe this should always just return true? (Only an issue for non-deterministic transformers.) // // Querying the next matcher is fine if the transformer always will return the same value. // But if the transformer is non-deterministic and returns a different value each time, then there // is no point in querying the next matcher, since it can only comment on the last transformed value. return types.MatchMayChangeInTheFuture(m.Matcher, m.transformedValue) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go
// untested sections: 2 package matchers import ( "fmt" "strings" "github.com/onsi/gomega/format" ) type ContainSubstringMatcher struct { Substr string Args []any } func (matcher *ContainSubstringMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("ContainSubstring matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) } return strings.Contains(actualString, matcher.stringToMatch()), nil } func (matcher *ContainSubstringMatcher) stringToMatch() string { stringToMatch := matcher.Substr if len(matcher.Args) > 0 { stringToMatch = fmt.Sprintf(matcher.Substr, matcher.Args...) } return stringToMatch } func (matcher *ContainSubstringMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain substring", matcher.stringToMatch()) } func (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain substring", matcher.stringToMatch()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/type_support.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/type_support.go
/* Gomega matchers This package implements the Gomega matchers and does not typically need to be imported. See the docs for Gomega for documentation on the matchers http://onsi.github.io/gomega/ */ // untested sections: 11 package matchers import ( "encoding/json" "fmt" "reflect" "github.com/onsi/gomega/matchers/internal/miter" ) type omegaMatcher interface { Match(actual any) (success bool, err error) FailureMessage(actual any) (message string) NegatedFailureMessage(actual any) (message string) } func isBool(a any) bool { return reflect.TypeOf(a).Kind() == reflect.Bool } func isNumber(a any) bool { if a == nil { return false } kind := reflect.TypeOf(a).Kind() return reflect.Int <= kind && kind <= reflect.Float64 } func isInteger(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Int <= kind && kind <= reflect.Int64 } func isUnsignedInteger(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Uint <= kind && kind <= reflect.Uint64 } func isFloat(a any) bool { kind := reflect.TypeOf(a).Kind() return reflect.Float32 <= kind && kind <= reflect.Float64 } func toInteger(a any) int64 { if isInteger(a) { return reflect.ValueOf(a).Int() } else if isUnsignedInteger(a) { return int64(reflect.ValueOf(a).Uint()) } else if isFloat(a) { return int64(reflect.ValueOf(a).Float()) } panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } func toUnsignedInteger(a any) uint64 { if isInteger(a) { return uint64(reflect.ValueOf(a).Int()) } else if isUnsignedInteger(a) { return reflect.ValueOf(a).Uint() } else if isFloat(a) { return uint64(reflect.ValueOf(a).Float()) } panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } func toFloat(a any) float64 { if isInteger(a) { return float64(reflect.ValueOf(a).Int()) } else if isUnsignedInteger(a) { return float64(reflect.ValueOf(a).Uint()) } else if isFloat(a) { return reflect.ValueOf(a).Float() } panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) } func isError(a any) bool { _, ok := a.(error) return ok } func isChan(a any) bool { if isNil(a) { return false } return reflect.TypeOf(a).Kind() == reflect.Chan } func isMap(a any) bool { if a == nil { return false } return reflect.TypeOf(a).Kind() == reflect.Map } func isArrayOrSlice(a any) bool { if a == nil { return false } switch reflect.TypeOf(a).Kind() { case reflect.Array, reflect.Slice: return true default: return false } } func isString(a any) bool { if a == nil { return false } return reflect.TypeOf(a).Kind() == reflect.String } func toString(a any) (string, bool) { aString, isString := a.(string) if isString { return aString, true } aBytes, isBytes := a.([]byte) if isBytes { return string(aBytes), true } aStringer, isStringer := a.(fmt.Stringer) if isStringer { return aStringer.String(), true } aJSONRawMessage, isJSONRawMessage := a.(json.RawMessage) if isJSONRawMessage { return string(aJSONRawMessage), true } return "", false } func lengthOf(a any) (int, bool) { if a == nil { return 0, false } switch reflect.TypeOf(a).Kind() { case reflect.Map, reflect.Array, reflect.String, reflect.Chan, reflect.Slice: return reflect.ValueOf(a).Len(), true case reflect.Func: if !miter.IsIter(a) { return 0, false } var l int if miter.IsSeq2(a) { miter.IterateKV(a, func(k, v reflect.Value) bool { l++; return true }) } else { miter.IterateV(a, func(v reflect.Value) bool { l++; return true }) } return l, true default: return 0, false } } func capOf(a any) (int, bool) { if a == nil { return 0, false } switch reflect.TypeOf(a).Kind() { case reflect.Array, reflect.Chan, reflect.Slice: return reflect.ValueOf(a).Cap(), true default: return 0, false } } func isNil(a any) bool { if a == nil { return true } switch reflect.TypeOf(a).Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return reflect.ValueOf(a).IsNil() } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go
package matchers import ( "errors" "fmt" "github.com/onsi/gomega/format" ) type formattedGomegaError interface { FormattedGomegaError() string } type SucceedMatcher struct { } func (matcher *SucceedMatcher) Match(actual any) (success bool, err error) { // is purely nil? if actual == nil { return true, nil } // must be an 'error' type if !isError(actual) { return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1)) } // must be nil (or a pointer to a nil) return isNil(actual), nil } func (matcher *SucceedMatcher) FailureMessage(actual any) (message string) { var fgErr formattedGomegaError if errors.As(actual.(error), &fgErr) { return fgErr.FormattedGomegaError() } return fmt.Sprintf("Expected success, but got an error:\n%s", format.Object(actual, 1)) } func (matcher *SucceedMatcher) NegatedFailureMessage(actual any) (message string) { return "Expected failure, but got no error." }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go
package matchers import ( "reflect" "github.com/onsi/gomega/format" ) type BeZeroMatcher struct { } func (matcher *BeZeroMatcher) Match(actual any) (success bool, err error) { if actual == nil { return true, nil } zeroValue := reflect.Zero(reflect.TypeOf(actual)).Interface() return reflect.DeepEqual(zeroValue, actual), nil } func (matcher *BeZeroMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be zero-valued") } func (matcher *BeZeroMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be zero-valued") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/consist_of.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/consist_of.go
// untested sections: 3 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/matchers/internal/miter" "github.com/onsi/gomega/matchers/support/goraph/bipartitegraph" ) type ConsistOfMatcher struct { Elements []any missingElements []any extraElements []any } func (matcher *ConsistOfMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ConsistOf matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) } matchers := matchers(matcher.Elements) values := valuesOf(actual) bipartiteGraph, err := bipartitegraph.NewBipartiteGraph(values, matchers, neighbours) if err != nil { return false, err } edges := bipartiteGraph.LargestMatching() if len(edges) == len(values) && len(edges) == len(matchers) { return true, nil } var missingMatchers []any matcher.extraElements, missingMatchers = bipartiteGraph.FreeLeftRight(edges) matcher.missingElements = equalMatchersToElements(missingMatchers) return false, nil } func neighbours(value, matcher any) (bool, error) { match, err := matcher.(omegaMatcher).Match(value) return match && err == nil, nil } func equalMatchersToElements(matchers []any) (elements []any) { for _, matcher := range matchers { if equalMatcher, ok := matcher.(*EqualMatcher); ok { elements = append(elements, equalMatcher.Expected) } else if _, ok := matcher.(*BeNilMatcher); ok { elements = append(elements, nil) } else { elements = append(elements, matcher) } } return } func flatten(elems []any) []any { if len(elems) != 1 || !(isArrayOrSlice(elems[0]) || (miter.IsIter(elems[0]) && !miter.IsSeq2(elems[0]))) { return elems } if miter.IsIter(elems[0]) { flattened := []any{} miter.IterateV(elems[0], func(v reflect.Value) bool { flattened = append(flattened, v.Interface()) return true }) return flattened } value := reflect.ValueOf(elems[0]) flattened := make([]any, value.Len()) for i := 0; i < value.Len(); i++ { flattened[i] = value.Index(i).Interface() } return flattened } func matchers(expectedElems []any) (matchers []any) { for _, e := range flatten(expectedElems) { if e == nil { matchers = append(matchers, &BeNilMatcher{}) } else if matcher, isMatcher := e.(omegaMatcher); isMatcher { matchers = append(matchers, matcher) } else { matchers = append(matchers, &EqualMatcher{Expected: e}) } } return } func presentable(elems []any) any { elems = flatten(elems) if len(elems) == 0 { return []any{} } sv := reflect.ValueOf(elems) firstEl := sv.Index(0) if firstEl.IsNil() { return elems } tt := firstEl.Elem().Type() for i := 1; i < sv.Len(); i++ { el := sv.Index(i) if el.IsNil() || (sv.Index(i).Elem().Type() != tt) { return elems } } ss := reflect.MakeSlice(reflect.SliceOf(tt), sv.Len(), sv.Len()) for i := 0; i < sv.Len(); i++ { ss.Index(i).Set(sv.Index(i).Elem()) } return ss.Interface() } func valuesOf(actual any) []any { value := reflect.ValueOf(actual) values := []any{} if miter.IsIter(actual) { if miter.IsSeq2(actual) { miter.IterateKV(actual, func(k, v reflect.Value) bool { values = append(values, v.Interface()) return true }) } else { miter.IterateV(actual, func(v reflect.Value) bool { values = append(values, v.Interface()) return true }) } } else if isMap(actual) { keys := value.MapKeys() for i := 0; i < value.Len(); i++ { values = append(values, value.MapIndex(keys[i]).Interface()) } } else { for i := 0; i < value.Len(); i++ { values = append(values, value.Index(i).Interface()) } } return values } func (matcher *ConsistOfMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to consist of", presentable(matcher.Elements)) message = appendMissingElements(message, matcher.missingElements) if len(matcher.extraElements) > 0 { message = fmt.Sprintf("%s\nthe extra elements were\n%s", message, format.Object(presentable(matcher.extraElements), 1)) } return } func appendMissingElements(message string, missingElements []any) string { if len(missingElements) == 0 { return message } return fmt.Sprintf("%s\nthe missing elements were\n%s", message, format.Object(presentable(missingElements), 1)) } func (matcher *ConsistOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to consist of", presentable(matcher.Elements)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go
package matchers import ( "errors" "fmt" "reflect" "github.com/onsi/gomega/format" ) type MatchErrorMatcher struct { Expected any FuncErrDescription []any isFunc bool } func (matcher *MatchErrorMatcher) Match(actual any) (success bool, err error) { matcher.isFunc = false if isNil(actual) { return false, fmt.Errorf("Expected an error, got nil") } if !isError(actual) { return false, fmt.Errorf("Expected an error. Got:\n%s", format.Object(actual, 1)) } actualErr := actual.(error) expected := matcher.Expected if isError(expected) { // first try the built-in errors.Is if errors.Is(actualErr, expected.(error)) { return true, nil } // if not, try DeepEqual along the error chain for unwrapped := actualErr; unwrapped != nil; unwrapped = errors.Unwrap(unwrapped) { if reflect.DeepEqual(unwrapped, expected) { return true, nil } } return false, nil } if isString(expected) { return actualErr.Error() == expected, nil } v := reflect.ValueOf(expected) t := v.Type() errorInterface := reflect.TypeOf((*error)(nil)).Elem() if t.Kind() == reflect.Func && t.NumIn() == 1 && t.In(0).Implements(errorInterface) && t.NumOut() == 1 && t.Out(0).Kind() == reflect.Bool { if len(matcher.FuncErrDescription) == 0 { return false, fmt.Errorf("MatchError requires an additional description when passed a function") } matcher.isFunc = true return v.Call([]reflect.Value{reflect.ValueOf(actualErr)})[0].Bool(), nil } var subMatcher omegaMatcher var hasSubMatcher bool if expected != nil { subMatcher, hasSubMatcher = (expected).(omegaMatcher) if hasSubMatcher { return subMatcher.Match(actualErr.Error()) } } return false, fmt.Errorf( "MatchError must be passed an error, a string, or a Matcher that can match on strings. Got:\n%s", format.Object(expected, 1)) } func (matcher *MatchErrorMatcher) FailureMessage(actual any) (message string) { if matcher.isFunc { return format.Message(actual, fmt.Sprintf("to match error function %s", matcher.FuncErrDescription[0])) } return format.Message(actual, "to match error", matcher.Expected) } func (matcher *MatchErrorMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.isFunc { return format.Message(actual, fmt.Sprintf("not to match error function %s", matcher.FuncErrDescription[0])) } return format.Message(actual, "not to match error", matcher.Expected) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_element_of_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_element_of_matcher.go
// untested sections: 1 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type BeElementOfMatcher struct { Elements []any } func (matcher *BeElementOfMatcher) Match(actual any) (success bool, err error) { if reflect.TypeOf(actual) == nil { return false, fmt.Errorf("BeElement matcher expects actual to be typed") } var lastError error for _, m := range flatten(matcher.Elements) { matcher := &EqualMatcher{Expected: m} success, err := matcher.Match(actual) if err != nil { lastError = err continue } if success { return true, nil } } return false, lastError } func (matcher *BeElementOfMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be an element of", presentable(matcher.Elements)) } func (matcher *BeElementOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be an element of", presentable(matcher.Elements)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go
// untested sections: 2 package matchers import ( "errors" "fmt" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/matchers/internal/miter" ) type ContainElementMatcher struct { Element any Result []any } func (matcher *ContainElementMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ContainElement matcher expects an array/slice/map/iterator. Got:\n%s", format.Object(actual, 1)) } var actualT reflect.Type var result reflect.Value switch numResultArgs := len(matcher.Result); { case numResultArgs > 1: return false, errors.New("ContainElement matcher expects at most a single optional pointer to store its findings at") case numResultArgs == 1: // Check the optional result arg to point to a single value/array/slice/map // of a type compatible with the actual value. if reflect.ValueOf(matcher.Result[0]).Kind() != reflect.Ptr { return false, fmt.Errorf("ContainElement matcher expects a non-nil pointer to store its findings at. Got\n%s", format.Object(matcher.Result[0], 1)) } actualT = reflect.TypeOf(actual) resultReference := matcher.Result[0] result = reflect.ValueOf(resultReference).Elem() // what ResultReference points to, to stash away our findings switch result.Kind() { case reflect.Array: // result arrays are not supported, as they cannot be dynamically sized. if miter.IsIter(actual) { _, actualvT := miter.IterKVTypes(actual) return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", reflect.SliceOf(actualvT), result.Type().String()) } return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", reflect.SliceOf(actualT.Elem()).String(), result.Type().String()) case reflect.Slice: // result slice // can we assign elements in actual to elements in what the result // arg points to? // - ✔ actual is an array or slice // - ✔ actual is an iter.Seq producing "v" elements // - ✔ actual is an iter.Seq2 producing "v" elements, ignoring // the "k" elements. switch { case isArrayOrSlice(actual): if !actualT.Elem().AssignableTo(result.Type().Elem()) { return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", actualT.String(), result.Type().String()) } case miter.IsIter(actual): _, actualvT := miter.IterKVTypes(actual) if !actualvT.AssignableTo(result.Type().Elem()) { return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", actualvT.String(), result.Type().String()) } default: // incompatible result reference return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", reflect.MapOf(actualT.Key(), actualT.Elem()).String(), result.Type().String()) } case reflect.Map: // result map // can we assign elements in actual to elements in what the result // arg points to? // - ✔ actual is a map // - ✔ actual is an iter.Seq2 (iter.Seq doesn't fit though) switch { case isMap(actual): if !actualT.AssignableTo(result.Type()) { return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", actualT.String(), result.Type().String()) } case miter.IsIter(actual): actualkT, actualvT := miter.IterKVTypes(actual) if actualkT == nil { return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", reflect.SliceOf(actualvT).String(), result.Type().String()) } if !reflect.MapOf(actualkT, actualvT).AssignableTo(result.Type()) { return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", reflect.MapOf(actualkT, actualvT), result.Type().String()) } default: // incompatible result reference return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", actualT.String(), result.Type().String()) } default: // can we assign a (single) element in actual to what the result arg // points to? switch { case miter.IsIter(actual): _, actualvT := miter.IterKVTypes(actual) if !actualvT.AssignableTo(result.Type()) { return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", actualvT.String(), result.Type().String()) } default: if !actualT.Elem().AssignableTo(result.Type()) { return false, fmt.Errorf("ContainElement cannot return findings. Need *%s, got *%s", actualT.Elem().String(), result.Type().String()) } } } } // If the supplied matcher isn't an Omega matcher, default to the Equal // matcher. elemMatcher, elementIsMatcher := matcher.Element.(omegaMatcher) if !elementIsMatcher { elemMatcher = &EqualMatcher{Expected: matcher.Element} } value := reflect.ValueOf(actual) var getFindings func() reflect.Value // abstracts how the findings are collected and stored var lastError error if !miter.IsIter(actual) { var valueAt func(int) any var foundAt func(int) // We're dealing with an array/slice/map, so in all cases we can iterate // over the elements in actual using indices (that can be considered // keys in case of maps). if isMap(actual) { keys := value.MapKeys() valueAt = func(i int) any { return value.MapIndex(keys[i]).Interface() } if result.Kind() != reflect.Invalid { fm := reflect.MakeMap(actualT) getFindings = func() reflect.Value { return fm } foundAt = func(i int) { fm.SetMapIndex(keys[i], value.MapIndex(keys[i])) } } } else { valueAt = func(i int) any { return value.Index(i).Interface() } if result.Kind() != reflect.Invalid { var fsl reflect.Value if result.Kind() == reflect.Slice { fsl = reflect.MakeSlice(result.Type(), 0, 0) } else { fsl = reflect.MakeSlice(reflect.SliceOf(result.Type()), 0, 0) } getFindings = func() reflect.Value { return fsl } foundAt = func(i int) { fsl = reflect.Append(fsl, value.Index(i)) } } } for i := 0; i < value.Len(); i++ { elem := valueAt(i) success, err := elemMatcher.Match(elem) if err != nil { lastError = err continue } if success { if result.Kind() == reflect.Invalid { return true, nil } foundAt(i) } } } else { // We're dealing with an iterator as a first-class construct, so things // are slightly different: there is no index defined as in case of // arrays/slices/maps, just "ooooorder" var found func(k, v reflect.Value) if result.Kind() != reflect.Invalid { if result.Kind() == reflect.Map { fm := reflect.MakeMap(result.Type()) getFindings = func() reflect.Value { return fm } found = func(k, v reflect.Value) { fm.SetMapIndex(k, v) } } else { var fsl reflect.Value if result.Kind() == reflect.Slice { fsl = reflect.MakeSlice(result.Type(), 0, 0) } else { fsl = reflect.MakeSlice(reflect.SliceOf(result.Type()), 0, 0) } getFindings = func() reflect.Value { return fsl } found = func(_, v reflect.Value) { fsl = reflect.Append(fsl, v) } } } success := false actualkT, _ := miter.IterKVTypes(actual) if actualkT == nil { miter.IterateV(actual, func(v reflect.Value) bool { var err error success, err = elemMatcher.Match(v.Interface()) if err != nil { lastError = err return true // iterate on... } if success { if result.Kind() == reflect.Invalid { return false // a match and no result needed, so we're done } found(reflect.Value{}, v) } return true // iterate on... }) } else { miter.IterateKV(actual, func(k, v reflect.Value) bool { var err error success, err = elemMatcher.Match(v.Interface()) if err != nil { lastError = err return true // iterate on... } if success { if result.Kind() == reflect.Invalid { return false // a match and no result needed, so we're done } found(k, v) } return true // iterate on... }) } if success && result.Kind() == reflect.Invalid { return true, nil } } // when the expectation isn't interested in the findings except for success // or non-success, then we're done here and return the last matcher error // seen, if any, as well as non-success. if result.Kind() == reflect.Invalid { return false, lastError } // pick up any findings the test is interested in as it specified a non-nil // result reference. However, the expectation always is that there are at // least one or multiple findings. So, if a result is expected, but we had // no findings, then this is an error. findings := getFindings() if findings.Len() == 0 { return false, lastError } // there's just a single finding and the result is neither a slice nor a map // (so it's a scalar): pick the one and only finding and return it in the // place the reference points to. if findings.Len() == 1 && !isArrayOrSlice(result.Interface()) && !isMap(result.Interface()) { if isMap(actual) { miter := findings.MapRange() miter.Next() result.Set(miter.Value()) } else { result.Set(findings.Index(0)) } return true, nil } // at least one or even multiple findings and a the result references a // slice or a map, so all we need to do is to store our findings where the // reference points to. if !findings.Type().AssignableTo(result.Type()) { return false, fmt.Errorf("ContainElement cannot return multiple findings. Need *%s, got *%s", findings.Type().String(), result.Type().String()) } result.Set(findings) return true, nil } func (matcher *ContainElementMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain element matching", matcher.Element) } func (matcher *ContainElementMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain element matching", matcher.Element) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go
// untested sections: 2 package matchers import ( "fmt" "github.com/onsi/gomega/format" ) type HaveCapMatcher struct { Count int } func (matcher *HaveCapMatcher) Match(actual any) (success bool, err error) { length, ok := capOf(actual) if !ok { return false, fmt.Errorf("HaveCap matcher expects a array/channel/slice. Got:\n%s", format.Object(actual, 1)) } return length == matcher.Count, nil } func (matcher *HaveCapMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have capacity %d", format.Object(actual, 1), matcher.Count) } func (matcher *HaveCapMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have capacity %d", format.Object(actual, 1), matcher.Count) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go
package matchers import ( "fmt" "github.com/onsi/gomega/format" ) type HavePrefixMatcher struct { Prefix string Args []any } func (matcher *HavePrefixMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("HavePrefix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) } prefix := matcher.prefix() return len(actualString) >= len(prefix) && actualString[0:len(prefix)] == prefix, nil } func (matcher *HavePrefixMatcher) prefix() string { if len(matcher.Args) > 0 { return fmt.Sprintf(matcher.Prefix, matcher.Args...) } return matcher.Prefix } func (matcher *HavePrefixMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to have prefix", matcher.prefix()) } func (matcher *HavePrefixMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to have prefix", matcher.prefix()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go
// untested sections: 4 package matchers import ( "fmt" "math" "github.com/onsi/gomega/format" ) type BeNumericallyMatcher struct { Comparator string CompareTo []any } func (matcher *BeNumericallyMatcher) FailureMessage(actual any) (message string) { return matcher.FormatFailureMessage(actual, false) } func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual any) (message string) { return matcher.FormatFailureMessage(actual, true) } func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual any, negated bool) (message string) { if len(matcher.CompareTo) == 1 { message = fmt.Sprintf("to be %s", matcher.Comparator) } else { message = fmt.Sprintf("to be within %v of %s", matcher.CompareTo[1], matcher.Comparator) } if negated { message = "not " + message } return format.Message(actual, message, matcher.CompareTo[0]) } func (matcher *BeNumericallyMatcher) Match(actual any) (success bool, err error) { if len(matcher.CompareTo) == 0 || len(matcher.CompareTo) > 2 { return false, fmt.Errorf("BeNumerically requires 1 or 2 CompareTo arguments. Got:\n%s", format.Object(matcher.CompareTo, 1)) } if !isNumber(actual) { return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(actual, 1)) } if !isNumber(matcher.CompareTo[0]) { return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1)) } if len(matcher.CompareTo) == 2 && !isNumber(matcher.CompareTo[1]) { return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[1], 1)) } switch matcher.Comparator { case "==", "~", ">", ">=", "<", "<=": default: return false, fmt.Errorf("Unknown comparator: %s", matcher.Comparator) } if isFloat(actual) || isFloat(matcher.CompareTo[0]) { var secondOperand float64 = 1e-8 if len(matcher.CompareTo) == 2 { secondOperand = toFloat(matcher.CompareTo[1]) } success = matcher.matchFloats(toFloat(actual), toFloat(matcher.CompareTo[0]), secondOperand) } else if isInteger(actual) { var secondOperand int64 = 0 if len(matcher.CompareTo) == 2 { secondOperand = toInteger(matcher.CompareTo[1]) } success = matcher.matchIntegers(toInteger(actual), toInteger(matcher.CompareTo[0]), secondOperand) } else if isUnsignedInteger(actual) { var secondOperand uint64 = 0 if len(matcher.CompareTo) == 2 { secondOperand = toUnsignedInteger(matcher.CompareTo[1]) } success = matcher.matchUnsignedIntegers(toUnsignedInteger(actual), toUnsignedInteger(matcher.CompareTo[0]), secondOperand) } else { return false, fmt.Errorf("Failed to compare:\n%s\n%s:\n%s", format.Object(actual, 1), matcher.Comparator, format.Object(matcher.CompareTo[0], 1)) } return success, nil } func (matcher *BeNumericallyMatcher) matchIntegers(actual, compareTo, threshold int64) (success bool) { switch matcher.Comparator { case "==", "~": diff := actual - compareTo return -threshold <= diff && diff <= threshold case ">": return (actual > compareTo) case ">=": return (actual >= compareTo) case "<": return (actual < compareTo) case "<=": return (actual <= compareTo) } return false } func (matcher *BeNumericallyMatcher) matchUnsignedIntegers(actual, compareTo, threshold uint64) (success bool) { switch matcher.Comparator { case "==", "~": if actual < compareTo { actual, compareTo = compareTo, actual } return actual-compareTo <= threshold case ">": return (actual > compareTo) case ">=": return (actual >= compareTo) case "<": return (actual < compareTo) case "<=": return (actual <= compareTo) } return false } func (matcher *BeNumericallyMatcher) matchFloats(actual, compareTo, threshold float64) (success bool) { switch matcher.Comparator { case "~": return math.Abs(actual-compareTo) <= threshold case "==": return (actual == compareTo) case ">": return (actual > compareTo) case ">=": return (actual >= compareTo) case "<": return (actual < compareTo) case "<=": return (actual <= compareTo) } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/not.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/not.go
package matchers import ( "github.com/onsi/gomega/types" ) type NotMatcher struct { Matcher types.GomegaMatcher } func (m *NotMatcher) Match(actual any) (bool, error) { success, err := m.Matcher.Match(actual) if err != nil { return false, err } return !success, nil } func (m *NotMatcher) FailureMessage(actual any) (message string) { return m.Matcher.NegatedFailureMessage(actual) // works beautifully } func (m *NotMatcher) NegatedFailureMessage(actual any) (message string) { return m.Matcher.FailureMessage(actual) // works beautifully } func (m *NotMatcher) MatchMayChangeInTheFuture(actual any) bool { return types.MatchMayChangeInTheFuture(m.Matcher, actual) // just return m.Matcher's value }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go
// untested sections: 5 package matchers import ( "fmt" "reflect" "strings" ) func formattedMessage(comparisonMessage string, failurePath []any) string { var diffMessage string if len(failurePath) == 0 { diffMessage = "" } else { diffMessage = fmt.Sprintf("\n\nfirst mismatched key: %s", formattedFailurePath(failurePath)) } return fmt.Sprintf("%s%s", comparisonMessage, diffMessage) } func formattedFailurePath(failurePath []any) string { formattedPaths := []string{} for i := len(failurePath) - 1; i >= 0; i-- { switch p := failurePath[i].(type) { case int: formattedPaths = append(formattedPaths, fmt.Sprintf(`[%d]`, p)) default: if i != len(failurePath)-1 { formattedPaths = append(formattedPaths, ".") } formattedPaths = append(formattedPaths, fmt.Sprintf(`"%s"`, p)) } } return strings.Join(formattedPaths, "") } func deepEqual(a any, b any) (bool, []any) { var errorPath []any if reflect.TypeOf(a) != reflect.TypeOf(b) { return false, errorPath } switch a.(type) { case []any: if len(a.([]any)) != len(b.([]any)) { return false, errorPath } for i, v := range a.([]any) { elementEqual, keyPath := deepEqual(v, b.([]any)[i]) if !elementEqual { return false, append(keyPath, i) } } return true, errorPath case map[any]any: if len(a.(map[any]any)) != len(b.(map[any]any)) { return false, errorPath } for k, v1 := range a.(map[any]any) { v2, ok := b.(map[any]any)[k] if !ok { return false, errorPath } elementEqual, keyPath := deepEqual(v1, v2) if !elementEqual { return false, append(keyPath, k) } } return true, errorPath case map[string]any: if len(a.(map[string]any)) != len(b.(map[string]any)) { return false, errorPath } for k, v1 := range a.(map[string]any) { v2, ok := b.(map[string]any)[k] if !ok { return false, errorPath } elementEqual, keyPath := deepEqual(v1, v2) if !elementEqual { return false, append(keyPath, k) } } return true, errorPath default: return a == b, errorPath } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go
// untested sections: 2 package matchers import ( "fmt" "github.com/onsi/gomega/format" ) type BeTrueMatcher struct { Reason string } func (matcher *BeTrueMatcher) Match(actual any) (success bool, err error) { if !isBool(actual) { return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) } return actual.(bool), nil } func (matcher *BeTrueMatcher) FailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "to be true") } else { return matcher.Reason } } func (matcher *BeTrueMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Reason == "" { return format.Message(actual, "not to be true") } else { return fmt.Sprintf(`Expected not true but got true\nNegation of "%s" failed`, matcher.Reason) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_a_directory.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_a_directory.go
// untested sections: 5 package matchers import ( "fmt" "os" "github.com/onsi/gomega/format" ) type notADirectoryError struct { os.FileInfo } func (t notADirectoryError) Error() string { fileInfo := os.FileInfo(t) switch { case fileInfo.Mode().IsRegular(): return "file is a regular file" default: return fmt.Sprintf("file mode is: %s", fileInfo.Mode().String()) } } type BeADirectoryMatcher struct { expected any err error } func (matcher *BeADirectoryMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeADirectoryMatcher matcher expects a file path") } fileInfo, err := os.Stat(actualFilename) if err != nil { matcher.err = err return false, nil } if !fileInfo.Mode().IsDir() { matcher.err = notADirectoryError{fileInfo} return false, nil } return true, nil } func (matcher *BeADirectoryMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be a directory: %s", matcher.err)) } func (matcher *BeADirectoryMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not be a directory") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/contain_elements_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/contain_elements_matcher.go
package matchers import ( "fmt" "github.com/onsi/gomega/format" "github.com/onsi/gomega/matchers/internal/miter" "github.com/onsi/gomega/matchers/support/goraph/bipartitegraph" ) type ContainElementsMatcher struct { Elements []any missingElements []any } func (matcher *ContainElementsMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("ContainElements matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) } matchers := matchers(matcher.Elements) bipartiteGraph, err := bipartitegraph.NewBipartiteGraph(valuesOf(actual), matchers, neighbours) if err != nil { return false, err } edges := bipartiteGraph.LargestMatching() if len(edges) == len(matchers) { return true, nil } _, missingMatchers := bipartiteGraph.FreeLeftRight(edges) matcher.missingElements = equalMatchersToElements(missingMatchers) return false, nil } func (matcher *ContainElementsMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to contain elements", presentable(matcher.Elements)) return appendMissingElements(message, matcher.missingElements) } func (matcher *ContainElementsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain elements", presentable(matcher.Elements)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go
package matchers import ( "fmt" "strings" "github.com/onsi/gomega/format" "go.yaml.in/yaml/v3" ) type MatchYAMLMatcher struct { YAMLToMatch any firstFailurePath []any } func (matcher *MatchYAMLMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.toStrings(actual) if err != nil { return false, err } var aval any var eval any if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil { return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err) } if err := yaml.Unmarshal([]byte(expectedString), &eval); err != nil { return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err) } var equal bool equal, matcher.firstFailurePath = deepEqual(aval, eval) return equal, nil } func (matcher *MatchYAMLMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) return formattedMessage(format.Message(actualString, "to match YAML of", expectedString), matcher.firstFailurePath) } func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) return formattedMessage(format.Message(actualString, "not to match YAML of", expectedString), matcher.firstFailurePath) } func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, expectedString, err := matcher.toStrings(actual) return normalise(actualString), normalise(expectedString), err } func normalise(input string) string { var val any err := yaml.Unmarshal([]byte(input), &val) if err != nil { panic(err) // unreachable since Match already calls Unmarshal } output, err := yaml.Marshal(val) if err != nil { panic(err) // untested section, unreachable since we Unmarshal above } return strings.TrimSpace(string(output)) } func (matcher *MatchYAMLMatcher) toStrings(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, ok := toString(actual) if !ok { return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) } expectedString, ok := toString(matcher.YAMLToMatch) if !ok { return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.YAMLToMatch, 1)) } return actualString, expectedString, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_exact_elements.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_exact_elements.go
package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/matchers/internal/miter" ) type mismatchFailure struct { failure string index int } type HaveExactElementsMatcher struct { Elements []any mismatchFailures []mismatchFailure missingIndex int extraIndex int } func (matcher *HaveExactElementsMatcher) Match(actual any) (success bool, err error) { matcher.resetState() if isMap(actual) || miter.IsSeq2(actual) { return false, fmt.Errorf("HaveExactElements matcher doesn't work on map or iter.Seq2. Got:\n%s", format.Object(actual, 1)) } matchers := matchers(matcher.Elements) lenMatchers := len(matchers) success = true if miter.IsIter(actual) { // In the worst case, we need to see everything before we can give our // verdict. The only exception is fast fail. i := 0 miter.IterateV(actual, func(v reflect.Value) bool { if i >= lenMatchers { // the iterator produces more values than we got matchers: this // is not good. matcher.extraIndex = i success = false return false } elemMatcher := matchers[i].(omegaMatcher) match, err := elemMatcher.Match(v.Interface()) if err != nil { matcher.mismatchFailures = append(matcher.mismatchFailures, mismatchFailure{ index: i, failure: err.Error(), }) success = false } else if !match { matcher.mismatchFailures = append(matcher.mismatchFailures, mismatchFailure{ index: i, failure: elemMatcher.FailureMessage(v.Interface()), }) success = false } i++ return true }) if i < len(matchers) { // the iterator produced less values than we got matchers: this is // no good, no no no. matcher.missingIndex = i success = false } return success, nil } values := valuesOf(actual) lenValues := len(values) for i := 0; i < lenMatchers || i < lenValues; i++ { if i >= lenMatchers { matcher.extraIndex = i success = false continue } if i >= lenValues { matcher.missingIndex = i success = false return } elemMatcher := matchers[i].(omegaMatcher) match, err := elemMatcher.Match(values[i]) if err != nil { matcher.mismatchFailures = append(matcher.mismatchFailures, mismatchFailure{ index: i, failure: err.Error(), }) success = false } else if !match { matcher.mismatchFailures = append(matcher.mismatchFailures, mismatchFailure{ index: i, failure: elemMatcher.FailureMessage(values[i]), }) success = false } } return success, nil } func (matcher *HaveExactElementsMatcher) FailureMessage(actual any) (message string) { message = format.Message(actual, "to have exact elements with", presentable(matcher.Elements)) if matcher.missingIndex > 0 { message = fmt.Sprintf("%s\nthe missing elements start from index %d", message, matcher.missingIndex) } if matcher.extraIndex > 0 { message = fmt.Sprintf("%s\nthe extra elements start from index %d", message, matcher.extraIndex) } if len(matcher.mismatchFailures) != 0 { message = fmt.Sprintf("%s\nthe mismatch indexes were:", message) } for _, mismatch := range matcher.mismatchFailures { message = fmt.Sprintf("%s\n%d: %s", message, mismatch.index, mismatch.failure) } return } func (matcher *HaveExactElementsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain elements", presentable(matcher.Elements)) } func (matcher *HaveExactElementsMatcher) resetState() { matcher.mismatchFailures = nil matcher.missingIndex = 0 matcher.extraIndex = 0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_existing_field_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_existing_field_matcher.go
package matchers import ( "errors" "fmt" "github.com/onsi/gomega/format" ) type HaveExistingFieldMatcher struct { Field string } func (matcher *HaveExistingFieldMatcher) Match(actual any) (success bool, err error) { // we don't care about the field's actual value, just about any error in // trying to find the field (or method). _, err = extractField(actual, matcher.Field, "HaveExistingField") if err == nil { return true, nil } var mferr missingFieldError if errors.As(err, &mferr) { // missing field errors aren't errors in this context, but instead // unsuccessful matches. return false, nil } return false, err } func (matcher *HaveExistingFieldMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have field '%s'", format.Object(actual, 1), matcher.Field) } func (matcher *HaveExistingFieldMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have field '%s'", format.Object(actual, 1), matcher.Field) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go
// untested sections: 2 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type BeEquivalentToMatcher struct { Expected any } func (matcher *BeEquivalentToMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Both actual and expected must not be nil.") } convertedActual := actual if actual != nil && matcher.Expected != nil && reflect.TypeOf(actual).ConvertibleTo(reflect.TypeOf(matcher.Expected)) { convertedActual = reflect.ValueOf(actual).Convert(reflect.TypeOf(matcher.Expected)).Interface() } return reflect.DeepEqual(convertedActual, matcher.Expected), nil } func (matcher *BeEquivalentToMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be equivalent to", matcher.Expected) } func (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be equivalent to", matcher.Expected) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/panic_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/panic_matcher.go
package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type PanicMatcher struct { Expected any object any } func (matcher *PanicMatcher) Match(actual any) (success bool, err error) { if actual == nil { return false, fmt.Errorf("PanicMatcher expects a non-nil actual.") } actualType := reflect.TypeOf(actual) if actualType.Kind() != reflect.Func { return false, fmt.Errorf("PanicMatcher expects a function. Got:\n%s", format.Object(actual, 1)) } if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) { return false, fmt.Errorf("PanicMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1)) } success = false defer func() { if e := recover(); e != nil { matcher.object = e if matcher.Expected == nil { success = true return } valueMatcher, valueIsMatcher := matcher.Expected.(omegaMatcher) if !valueIsMatcher { valueMatcher = &EqualMatcher{Expected: matcher.Expected} } success, err = valueMatcher.Match(e) if err != nil { err = fmt.Errorf("PanicMatcher's value matcher failed with:\n%s%s", format.Indent, err.Error()) } } }() reflect.ValueOf(actual).Call([]reflect.Value{}) return } func (matcher *PanicMatcher) FailureMessage(actual any) (message string) { if matcher.Expected == nil { // We wanted any panic to occur, but none did. return format.Message(actual, "to panic") } if matcher.object == nil { // We wanted a panic with a specific value to occur, but none did. switch matcher.Expected.(type) { case omegaMatcher: return format.Message(actual, "to panic with a value matching", matcher.Expected) default: return format.Message(actual, "to panic with", matcher.Expected) } } // We got a panic, but the value isn't what we expected. switch matcher.Expected.(type) { case omegaMatcher: return format.Message( actual, fmt.Sprintf( "to panic with a value matching\n%s\nbut panicked with\n%s", format.Object(matcher.Expected, 1), format.Object(matcher.object, 1), ), ) default: return format.Message( actual, fmt.Sprintf( "to panic with\n%s\nbut panicked with\n%s", format.Object(matcher.Expected, 1), format.Object(matcher.object, 1), ), ) } } func (matcher *PanicMatcher) NegatedFailureMessage(actual any) (message string) { if matcher.Expected == nil { // We didn't want any panic to occur, but one did. return format.Message(actual, fmt.Sprintf("not to panic, but panicked with\n%s", format.Object(matcher.object, 1))) } // We wanted a to ensure a panic with a specific value did not occur, but it did. switch matcher.Expected.(type) { case omegaMatcher: return format.Message( actual, fmt.Sprintf( "not to panic with a value matching\n%s\nbut panicked with\n%s", format.Object(matcher.Expected, 1), format.Object(matcher.object, 1), ), ) default: return format.Message(actual, "not to panic with", matcher.Expected) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_identical_to.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_identical_to.go
// untested sections: 2 package matchers import ( "fmt" "runtime" "github.com/onsi/gomega/format" ) type BeIdenticalToMatcher struct { Expected any } func (matcher *BeIdenticalToMatcher) Match(actual any) (success bool, matchErr error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } defer func() { if r := recover(); r != nil { if _, ok := r.(runtime.Error); ok { success = false matchErr = nil } } }() return actual == matcher.Expected, nil } func (matcher *BeIdenticalToMatcher) FailureMessage(actual any) string { return format.Message(actual, "to be identical to", matcher.Expected) } func (matcher *BeIdenticalToMatcher) NegatedFailureMessage(actual any) string { return format.Message(actual, "not to be identical to", matcher.Expected) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go
package matchers import ( "fmt" "github.com/onsi/gomega/format" ) type HaveSuffixMatcher struct { Suffix string Args []any } func (matcher *HaveSuffixMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("HaveSuffix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) } suffix := matcher.suffix() return len(actualString) >= len(suffix) && actualString[len(actualString)-len(suffix):] == suffix, nil } func (matcher *HaveSuffixMatcher) suffix() string { if len(matcher.Args) > 0 { return fmt.Sprintf(matcher.Suffix, matcher.Args...) } return matcher.Suffix } func (matcher *HaveSuffixMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to have suffix", matcher.suffix()) } func (matcher *HaveSuffixMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to have suffix", matcher.suffix()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go
package matchers import ( "bytes" "encoding/json" "fmt" "github.com/onsi/gomega/format" ) type MatchJSONMatcher struct { JSONToMatch any firstFailurePath []any } func (matcher *MatchJSONMatcher) Match(actual any) (success bool, err error) { actualString, expectedString, err := matcher.prettyPrint(actual) if err != nil { return false, err } var aval any var eval any // this is guarded by prettyPrint json.Unmarshal([]byte(actualString), &aval) json.Unmarshal([]byte(expectedString), &eval) var equal bool equal, matcher.firstFailurePath = deepEqual(aval, eval) return equal, nil } func (matcher *MatchJSONMatcher) FailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.prettyPrint(actual) return formattedMessage(format.Message(actualString, "to match JSON of", expectedString), matcher.firstFailurePath) } func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual any) (message string) { actualString, expectedString, _ := matcher.prettyPrint(actual) return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath) } func (matcher *MatchJSONMatcher) prettyPrint(actual any) (actualFormatted, expectedFormatted string, err error) { actualString, ok := toString(actual) if !ok { return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) } expectedString, ok := toString(matcher.JSONToMatch) if !ok { return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.JSONToMatch, 1)) } abuf := new(bytes.Buffer) ebuf := new(bytes.Buffer) if err := json.Indent(abuf, []byte(actualString), "", " "); err != nil { return "", "", fmt.Errorf("Actual '%s' should be valid JSON, but it is not.\nUnderlying error:%s", actualString, err) } if err := json.Indent(ebuf, []byte(expectedString), "", " "); err != nil { return "", "", fmt.Errorf("Expected '%s' should be valid JSON, but it is not.\nUnderlying error:%s", expectedString, err) } return abuf.String(), ebuf.String(), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go
// untested sections: 5 package matchers import ( "fmt" "os" "github.com/onsi/gomega/format" ) type notARegularFileError struct { os.FileInfo } func (t notARegularFileError) Error() string { fileInfo := os.FileInfo(t) switch { case fileInfo.IsDir(): return "file is a directory" default: return fmt.Sprintf("file mode is: %s", fileInfo.Mode().String()) } } type BeARegularFileMatcher struct { expected any err error } func (matcher *BeARegularFileMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeARegularFileMatcher matcher expects a file path") } fileInfo, err := os.Stat(actualFilename) if err != nil { matcher.err = err return false, nil } if !fileInfo.Mode().IsRegular() { matcher.err = notARegularFileError{fileInfo} return false, nil } return true, nil } func (matcher *BeARegularFileMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, fmt.Sprintf("to be a regular file: %s", matcher.err)) } func (matcher *BeARegularFileMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not be a regular file") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/satisfy_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/satisfy_matcher.go
package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type SatisfyMatcher struct { Predicate any // cached type predicateArgType reflect.Type } func NewSatisfyMatcher(predicate any) *SatisfyMatcher { if predicate == nil { panic("predicate cannot be nil") } predicateType := reflect.TypeOf(predicate) if predicateType.Kind() != reflect.Func { panic("predicate must be a function") } if predicateType.NumIn() != 1 { panic("predicate must have 1 argument") } if predicateType.NumOut() != 1 || predicateType.Out(0).Kind() != reflect.Bool { panic("predicate must return bool") } return &SatisfyMatcher{ Predicate: predicate, predicateArgType: predicateType.In(0), } } func (m *SatisfyMatcher) Match(actual any) (success bool, err error) { // prepare a parameter to pass to the predicate var param reflect.Value if actual != nil && reflect.TypeOf(actual).AssignableTo(m.predicateArgType) { // The dynamic type of actual is compatible with the predicate argument. param = reflect.ValueOf(actual) } else if actual == nil && m.predicateArgType.Kind() == reflect.Interface { // The dynamic type of actual is unknown, so there's no way to make its // reflect.Value. Create a nil of the predicate argument, which is known. param = reflect.Zero(m.predicateArgType) } else { return false, fmt.Errorf("predicate expects '%s' but we have '%T'", m.predicateArgType, actual) } // call the predicate with `actual` fn := reflect.ValueOf(m.Predicate) result := fn.Call([]reflect.Value{param}) return result[0].Bool(), nil } func (m *SatisfyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to satisfy predicate", m.Predicate) } func (m *SatisfyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "to not satisfy predicate", m.Predicate) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_http_header_with_value_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_http_header_with_value_matcher.go
package matchers import ( "fmt" "net/http" "net/http/httptest" "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" ) type HaveHTTPHeaderWithValueMatcher struct { Header string Value any } func (matcher *HaveHTTPHeaderWithValueMatcher) Match(actual any) (success bool, err error) { headerValue, err := matcher.extractHeader(actual) if err != nil { return false, err } headerMatcher, err := matcher.getSubMatcher() if err != nil { return false, err } return headerMatcher.Match(headerValue) } func (matcher *HaveHTTPHeaderWithValueMatcher) FailureMessage(actual any) string { headerValue, err := matcher.extractHeader(actual) if err != nil { panic(err) // protected by Match() } headerMatcher, err := matcher.getSubMatcher() if err != nil { panic(err) // protected by Match() } diff := format.IndentString(headerMatcher.FailureMessage(headerValue), 1) return fmt.Sprintf("HTTP header %q:\n%s", matcher.Header, diff) } func (matcher *HaveHTTPHeaderWithValueMatcher) NegatedFailureMessage(actual any) (message string) { headerValue, err := matcher.extractHeader(actual) if err != nil { panic(err) // protected by Match() } headerMatcher, err := matcher.getSubMatcher() if err != nil { panic(err) // protected by Match() } diff := format.IndentString(headerMatcher.NegatedFailureMessage(headerValue), 1) return fmt.Sprintf("HTTP header %q:\n%s", matcher.Header, diff) } func (matcher *HaveHTTPHeaderWithValueMatcher) getSubMatcher() (types.GomegaMatcher, error) { switch m := matcher.Value.(type) { case string: return &EqualMatcher{Expected: matcher.Value}, nil case types.GomegaMatcher: return m, nil default: return nil, fmt.Errorf("HaveHTTPHeaderWithValue matcher must be passed a string or a GomegaMatcher. Got:\n%s", format.Object(matcher.Value, 1)) } } func (matcher *HaveHTTPHeaderWithValueMatcher) extractHeader(actual any) (string, error) { switch r := actual.(type) { case *http.Response: return r.Header.Get(matcher.Header), nil case *httptest.ResponseRecorder: return r.Result().Header.Get(matcher.Header), nil default: return "", fmt.Errorf("HaveHTTPHeaderWithValue matcher expects *http.Response or *httptest.ResponseRecorder. Got:\n%s", format.Object(actual, 1)) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/attributes_slice.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/attributes_slice.go
package matchers import ( "encoding/xml" "strings" ) type attributesSlice []xml.Attr func (attrs attributesSlice) Len() int { return len(attrs) } func (attrs attributesSlice) Less(i, j int) bool { return strings.Compare(attrs[i].Name.Local, attrs[j].Name.Local) == -1 } func (attrs attributesSlice) Swap(i, j int) { attrs[i], attrs[j] = attrs[j], attrs[i] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go
// untested sections: 2 package matchers import ( "fmt" "github.com/onsi/gomega/format" ) type HaveOccurredMatcher struct { } func (matcher *HaveOccurredMatcher) Match(actual any) (success bool, err error) { // is purely nil? if actual == nil { return false, nil } // must be an 'error' type if !isError(actual) { return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1)) } // must be non-nil (or a pointer to a non-nil) return !isNil(actual), nil } func (matcher *HaveOccurredMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected an error to have occurred. Got:\n%s", format.Object(actual, 1)) } func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Unexpected error:\n%s\n%s", format.Object(actual, 1), "occurred") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go
// untested sections: 3 package matchers import ( "fmt" "os" "github.com/onsi/gomega/format" ) type BeAnExistingFileMatcher struct { expected any } func (matcher *BeAnExistingFileMatcher) Match(actual any) (success bool, err error) { actualFilename, ok := actual.(string) if !ok { return false, fmt.Errorf("BeAnExistingFileMatcher matcher expects a file path") } if _, err = os.Stat(actualFilename); err != nil { switch { case os.IsNotExist(err): return false, nil default: return false, err } } return true, nil } func (matcher *BeAnExistingFileMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to exist") } func (matcher *BeAnExistingFileMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to exist") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_http_body_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_http_body_matcher.go
package matchers import ( "fmt" "net/http" "net/http/httptest" "github.com/onsi/gomega/format" "github.com/onsi/gomega/internal/gutil" "github.com/onsi/gomega/types" ) type HaveHTTPBodyMatcher struct { Expected any cachedResponse any cachedBody []byte } func (matcher *HaveHTTPBodyMatcher) Match(actual any) (bool, error) { body, err := matcher.body(actual) if err != nil { return false, err } switch e := matcher.Expected.(type) { case string: return (&EqualMatcher{Expected: e}).Match(string(body)) case []byte: return (&EqualMatcher{Expected: e}).Match(body) case types.GomegaMatcher: return e.Match(body) default: return false, fmt.Errorf("HaveHTTPBody matcher expects string, []byte, or GomegaMatcher. Got:\n%s", format.Object(matcher.Expected, 1)) } } func (matcher *HaveHTTPBodyMatcher) FailureMessage(actual any) (message string) { body, err := matcher.body(actual) if err != nil { return fmt.Sprintf("failed to read body: %s", err) } switch e := matcher.Expected.(type) { case string: return (&EqualMatcher{Expected: e}).FailureMessage(string(body)) case []byte: return (&EqualMatcher{Expected: e}).FailureMessage(body) case types.GomegaMatcher: return e.FailureMessage(body) default: return fmt.Sprintf("HaveHTTPBody matcher expects string, []byte, or GomegaMatcher. Got:\n%s", format.Object(matcher.Expected, 1)) } } func (matcher *HaveHTTPBodyMatcher) NegatedFailureMessage(actual any) (message string) { body, err := matcher.body(actual) if err != nil { return fmt.Sprintf("failed to read body: %s", err) } switch e := matcher.Expected.(type) { case string: return (&EqualMatcher{Expected: e}).NegatedFailureMessage(string(body)) case []byte: return (&EqualMatcher{Expected: e}).NegatedFailureMessage(body) case types.GomegaMatcher: return e.NegatedFailureMessage(body) default: return fmt.Sprintf("HaveHTTPBody matcher expects string, []byte, or GomegaMatcher. Got:\n%s", format.Object(matcher.Expected, 1)) } } // body returns the body. It is cached because once we read it in Match() // the Reader is closed and it is not readable again in FailureMessage() // or NegatedFailureMessage() func (matcher *HaveHTTPBodyMatcher) body(actual any) ([]byte, error) { if matcher.cachedResponse == actual && matcher.cachedBody != nil { return matcher.cachedBody, nil } body := func(a *http.Response) ([]byte, error) { if a.Body != nil { defer a.Body.Close() var err error matcher.cachedBody, err = gutil.ReadAll(a.Body) if err != nil { return nil, fmt.Errorf("error reading response body: %w", err) } } return matcher.cachedBody, nil } switch a := actual.(type) { case *http.Response: matcher.cachedResponse = a return body(a) case *httptest.ResponseRecorder: matcher.cachedResponse = a return body(a.Result()) default: return nil, fmt.Errorf("HaveHTTPBody matcher expects *http.Response or *httptest.ResponseRecorder. Got:\n%s", format.Object(actual, 1)) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go
package matchers import ( "fmt" "regexp" "github.com/onsi/gomega/format" ) type MatchRegexpMatcher struct { Regexp string Args []any } func (matcher *MatchRegexpMatcher) Match(actual any) (success bool, err error) { actualString, ok := toString(actual) if !ok { return false, fmt.Errorf("RegExp matcher requires a string or stringer.\nGot:%s", format.Object(actual, 1)) } match, err := regexp.Match(matcher.regexp(), []byte(actualString)) if err != nil { return false, fmt.Errorf("RegExp match failed to compile with error:\n\t%s", err.Error()) } return match, nil } func (matcher *MatchRegexpMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to match regular expression", matcher.regexp()) } func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to match regular expression", matcher.regexp()) } func (matcher *MatchRegexpMatcher) regexp() string { re := matcher.Regexp if len(matcher.Args) > 0 { re = fmt.Sprintf(matcher.Regexp, matcher.Args...) } return re }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go
// untested sections: 2 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type AssignableToTypeOfMatcher struct { Expected any } func (matcher *AssignableToTypeOfMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } else if matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare type to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } else if actual == nil { return false, nil } actualType := reflect.TypeOf(actual) expectedType := reflect.TypeOf(matcher.Expected) return actualType.AssignableTo(expectedType), nil } func (matcher *AssignableToTypeOfMatcher) FailureMessage(actual any) string { return format.Message(actual, fmt.Sprintf("to be assignable to the type: %T", matcher.Expected)) } func (matcher *AssignableToTypeOfMatcher) NegatedFailureMessage(actual any) string { return format.Message(actual, fmt.Sprintf("not to be assignable to the type: %T", matcher.Expected)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/equal_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/equal_matcher.go
package matchers import ( "bytes" "fmt" "reflect" "github.com/onsi/gomega/format" ) type EqualMatcher struct { Expected any } func (matcher *EqualMatcher) Match(actual any) (success bool, err error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } // Shortcut for byte slices. // Comparing long byte slices with reflect.DeepEqual is very slow, // so use bytes.Equal if actual and expected are both byte slices. if actualByteSlice, ok := actual.([]byte); ok { if expectedByteSlice, ok := matcher.Expected.([]byte); ok { return bytes.Equal(actualByteSlice, expectedByteSlice), nil } } return reflect.DeepEqual(actual, matcher.Expected), nil } func (matcher *EqualMatcher) FailureMessage(actual any) (message string) { actualString, actualOK := actual.(string) expectedString, expectedOK := matcher.Expected.(string) if actualOK && expectedOK { return format.MessageWithDiff(actualString, "to equal", expectedString) } return format.Message(actual, "to equal", matcher.Expected) } func (matcher *EqualMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to equal", matcher.Expected) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go
// untested sections:10 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/matchers/internal/miter" ) type HaveKeyWithValueMatcher struct { Key any Value any } func (matcher *HaveKeyWithValueMatcher) Match(actual any) (success bool, err error) { if !isMap(actual) && !miter.IsSeq2(actual) { return false, fmt.Errorf("HaveKeyWithValue matcher expects a map/iter.Seq2. Got:%s", format.Object(actual, 1)) } keyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher) if !keyIsMatcher { keyMatcher = &EqualMatcher{Expected: matcher.Key} } valueMatcher, valueIsMatcher := matcher.Value.(omegaMatcher) if !valueIsMatcher { valueMatcher = &EqualMatcher{Expected: matcher.Value} } if miter.IsSeq2(actual) { var success bool var err error miter.IterateKV(actual, func(k, v reflect.Value) bool { success, err = keyMatcher.Match(k.Interface()) if err != nil { err = fmt.Errorf("HaveKey's key matcher failed with:\n%s%s", format.Indent, err.Error()) return false } if success { success, err = valueMatcher.Match(v.Interface()) if err != nil { err = fmt.Errorf("HaveKeyWithValue's value matcher failed with:\n%s%s", format.Indent, err.Error()) return false } } return !success }) return success, err } keys := reflect.ValueOf(actual).MapKeys() for i := 0; i < len(keys); i++ { success, err := keyMatcher.Match(keys[i].Interface()) if err != nil { return false, fmt.Errorf("HaveKeyWithValue's key matcher failed with:\n%s%s", format.Indent, err.Error()) } if success { actualValue := reflect.ValueOf(actual).MapIndex(keys[i]) success, err := valueMatcher.Match(actualValue.Interface()) if err != nil { return false, fmt.Errorf("HaveKeyWithValue's value matcher failed with:\n%s%s", format.Indent, err.Error()) } return success, nil } } return false, nil } func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual any) (message string) { str := "to have {key: value}" if _, ok := matcher.Key.(omegaMatcher); ok { str += " matching" } else if _, ok := matcher.Value.(omegaMatcher); ok { str += " matching" } expect := make(map[any]any, 1) expect[matcher.Key] = matcher.Value return format.Message(actual, str, expect) } func (matcher *HaveKeyWithValueMatcher) NegatedFailureMessage(actual any) (message string) { kStr := "not to have key" if _, ok := matcher.Key.(omegaMatcher); ok { kStr = "not to have key matching" } vStr := "or that key's value not be" if _, ok := matcher.Value.(omegaMatcher); ok { vStr = "or to have that key's value not matching" } return format.Message(actual, kStr, matcher.Key, vStr, matcher.Value) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_comparable_to_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_comparable_to_matcher.go
package matchers import ( "bytes" "errors" "fmt" "github.com/google/go-cmp/cmp" "github.com/onsi/gomega/format" ) type BeComparableToMatcher struct { Expected any Options cmp.Options } func (matcher *BeComparableToMatcher) Match(actual any) (success bool, matchErr error) { if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare <nil> to <nil>.\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } // Shortcut for byte slices. // Comparing long byte slices with reflect.DeepEqual is very slow, // so use bytes.Equal if actual and expected are both byte slices. if actualByteSlice, ok := actual.([]byte); ok { if expectedByteSlice, ok := matcher.Expected.([]byte); ok { return bytes.Equal(actualByteSlice, expectedByteSlice), nil } } defer func() { if r := recover(); r != nil { success = false if err, ok := r.(error); ok { matchErr = err } else if errMsg, ok := r.(string); ok { matchErr = errors.New(errMsg) } } }() return cmp.Equal(actual, matcher.Expected, matcher.Options...), nil } func (matcher *BeComparableToMatcher) FailureMessage(actual any) (message string) { return fmt.Sprint("Expected object to be comparable, diff: ", cmp.Diff(actual, matcher.Expected, matcher.Options...)) } func (matcher *BeComparableToMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be comparable to", matcher.Expected) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/receive_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/receive_matcher.go
// untested sections: 3 package matchers import ( "errors" "fmt" "reflect" "github.com/onsi/gomega/format" ) type ReceiveMatcher struct { Args []any receivedValue reflect.Value channelClosed bool } func (matcher *ReceiveMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("ReceiveMatcher expects a channel. Got:\n%s", format.Object(actual, 1)) } channelType := reflect.TypeOf(actual) channelValue := reflect.ValueOf(actual) if channelType.ChanDir() == reflect.SendDir { return false, fmt.Errorf("ReceiveMatcher matcher cannot be passed a send-only channel. Got:\n%s", format.Object(actual, 1)) } var subMatcher omegaMatcher var hasSubMatcher bool var resultReference any // Valid arg formats are as follows, always with optional POINTER before // optional MATCHER: // - Receive() // - Receive(POINTER) // - Receive(MATCHER) // - Receive(POINTER, MATCHER) args := matcher.Args if len(args) > 0 { arg := args[0] _, isSubMatcher := arg.(omegaMatcher) if !isSubMatcher && reflect.ValueOf(arg).Kind() == reflect.Ptr { // Consume optional POINTER arg first, if it ain't no matcher ;) resultReference = arg args = args[1:] } } if len(args) > 0 { arg := args[0] subMatcher, hasSubMatcher = arg.(omegaMatcher) if !hasSubMatcher { // At this point we assume the dev user wanted to assign a received // value, so [POINTER,]MATCHER. return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nTo:\n%s\nYou need to pass a pointer!", format.Object(actual, 1), format.Object(arg, 1)) } // Consume optional MATCHER arg. args = args[1:] } if len(args) > 0 { // If there are still args present, reject all. return false, errors.New("Receive matcher expects at most an optional pointer and/or an optional matcher") } winnerIndex, value, open := reflect.Select([]reflect.SelectCase{ {Dir: reflect.SelectRecv, Chan: channelValue}, {Dir: reflect.SelectDefault}, }) var closed bool var didReceive bool if winnerIndex == 0 { closed = !open didReceive = open } matcher.channelClosed = closed if closed { return false, nil } if hasSubMatcher { if !didReceive { return false, nil } matcher.receivedValue = value if match, err := subMatcher.Match(matcher.receivedValue.Interface()); err != nil || !match { return match, err } // if we received a match, then fall through in order to handle an // optional assignment of the received value to the specified reference. } if didReceive { if resultReference != nil { outValue := reflect.ValueOf(resultReference) if value.Type().AssignableTo(outValue.Elem().Type()) { outValue.Elem().Set(value) return true, nil } if value.Type().Kind() == reflect.Interface && value.Elem().Type().AssignableTo(outValue.Elem().Type()) { outValue.Elem().Set(value.Elem()) return true, nil } else { return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nType:\n%s\nTo:\n%s", format.Object(actual, 1), format.Object(value.Interface(), 1), format.Object(resultReference, 1)) } } return true, nil } return false, nil } func (matcher *ReceiveMatcher) FailureMessage(actual any) (message string) { var matcherArg any if len(matcher.Args) > 0 { matcherArg = matcher.Args[len(matcher.Args)-1] } subMatcher, hasSubMatcher := (matcherArg).(omegaMatcher) closedAddendum := "" if matcher.channelClosed { closedAddendum = " The channel is closed." } if hasSubMatcher { if matcher.receivedValue.IsValid() { return subMatcher.FailureMessage(matcher.receivedValue.Interface()) } return "When passed a matcher, ReceiveMatcher's channel *must* receive something." } return format.Message(actual, "to receive something."+closedAddendum) } func (matcher *ReceiveMatcher) NegatedFailureMessage(actual any) (message string) { var matcherArg any if len(matcher.Args) > 0 { matcherArg = matcher.Args[len(matcher.Args)-1] } subMatcher, hasSubMatcher := (matcherArg).(omegaMatcher) closedAddendum := "" if matcher.channelClosed { closedAddendum = " The channel is closed." } if hasSubMatcher { if matcher.receivedValue.IsValid() { return subMatcher.NegatedFailureMessage(matcher.receivedValue.Interface()) } return "When passed a matcher, ReceiveMatcher's channel *must* receive something." } return format.Message(actual, "not to receive anything."+closedAddendum) } func (matcher *ReceiveMatcher) MatchMayChangeInTheFuture(actual any) bool { if !isChan(actual) { return false } return !matcher.channelClosed }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_each_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_each_matcher.go
package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/matchers/internal/miter" ) type HaveEachMatcher struct { Element any } func (matcher *HaveEachMatcher) Match(actual any) (success bool, err error) { if !isArrayOrSlice(actual) && !isMap(actual) && !miter.IsIter(actual) { return false, fmt.Errorf("HaveEach matcher expects an array/slice/map/iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) } elemMatcher, elementIsMatcher := matcher.Element.(omegaMatcher) if !elementIsMatcher { elemMatcher = &EqualMatcher{Expected: matcher.Element} } if miter.IsIter(actual) { // rejecting the non-elements case works different for iterators as we // don't want to fetch all elements into a slice first. count := 0 var success bool var err error if miter.IsSeq2(actual) { miter.IterateKV(actual, func(k, v reflect.Value) bool { count++ success, err = elemMatcher.Match(v.Interface()) if err != nil { return false } return success }) } else { miter.IterateV(actual, func(v reflect.Value) bool { count++ success, err = elemMatcher.Match(v.Interface()) if err != nil { return false } return success }) } if count == 0 { return false, fmt.Errorf("HaveEach matcher expects a non-empty iter.Seq/iter.Seq2. Got:\n%s", format.Object(actual, 1)) } return success, err } value := reflect.ValueOf(actual) if value.Len() == 0 { return false, fmt.Errorf("HaveEach matcher expects a non-empty array/slice/map. Got:\n%s", format.Object(actual, 1)) } var valueAt func(int) any if isMap(actual) { keys := value.MapKeys() valueAt = func(i int) any { return value.MapIndex(keys[i]).Interface() } } else { valueAt = func(i int) any { return value.Index(i).Interface() } } // if we never failed then we succeed; the empty/nil cases have already been // rejected above. for i := 0; i < value.Len(); i++ { success, err := elemMatcher.Match(valueAt(i)) if err != nil { return false, err } if !success { return false, nil } } return true, nil } // FailureMessage returns a suitable failure message. func (matcher *HaveEachMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to contain element matching", matcher.Element) } // NegatedFailureMessage returns a suitable negated failure message. func (matcher *HaveEachMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to contain element matching", matcher.Element) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_value.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_value.go
package matchers import ( "errors" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" ) const maxIndirections = 31 type HaveValueMatcher struct { Matcher types.GomegaMatcher // the matcher to apply to the "resolved" actual value. resolvedActual any // the ("resolved") value. } func (m *HaveValueMatcher) Match(actual any) (bool, error) { val := reflect.ValueOf(actual) for allowedIndirs := maxIndirections; allowedIndirs > 0; allowedIndirs-- { // return an error if value isn't valid. Please note that we cannot // check for nil here, as we might not deal with a pointer or interface // at this point. if !val.IsValid() { return false, errors.New(format.Message( actual, "not to be <nil>")) } switch val.Kind() { case reflect.Ptr, reflect.Interface: // resolve pointers and interfaces to their values, then rinse and // repeat. if val.IsNil() { return false, errors.New(format.Message( actual, "not to be <nil>")) } val = val.Elem() continue default: // forward the final value to the specified matcher. m.resolvedActual = val.Interface() return m.Matcher.Match(m.resolvedActual) } } // too many indirections: extreme star gazing, indeed...? return false, errors.New(format.Message(actual, "too many indirections")) } func (m *HaveValueMatcher) FailureMessage(_ any) (message string) { return m.Matcher.FailureMessage(m.resolvedActual) } func (m *HaveValueMatcher) NegatedFailureMessage(_ any) (message string) { return m.Matcher.NegatedFailureMessage(m.resolvedActual) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/or.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/or.go
package matchers import ( "fmt" "github.com/onsi/gomega/format" "github.com/onsi/gomega/types" ) type OrMatcher struct { Matchers []types.GomegaMatcher // state firstSuccessfulMatcher types.GomegaMatcher } func (m *OrMatcher) Match(actual any) (success bool, err error) { m.firstSuccessfulMatcher = nil for _, matcher := range m.Matchers { success, err := matcher.Match(actual) if err != nil { return false, err } if success { m.firstSuccessfulMatcher = matcher return true, nil } } return false, nil } func (m *OrMatcher) FailureMessage(actual any) (message string) { // not the most beautiful list of matchers, but not bad either... return format.Message(actual, fmt.Sprintf("To satisfy at least one of these matchers: %s", m.Matchers)) } func (m *OrMatcher) NegatedFailureMessage(actual any) (message string) { return m.firstSuccessfulMatcher.NegatedFailureMessage(actual) } func (m *OrMatcher) MatchMayChangeInTheFuture(actual any) bool { /* Example with 3 matchers: A, B, C Match evaluates them: F, T, <?> => T So match is currently T, what should MatchMayChangeInTheFuture() return? Seems like it only depends on B, since currently B MUST change to allow the result to become F Match eval: F, F, F => F So match is currently F, what should MatchMayChangeInTheFuture() return? Seems to depend on ANY of them being able to change to T. */ if m.firstSuccessfulMatcher != nil { // one of the matchers succeeded.. it must be able to change in order to affect the result return types.MatchMayChangeInTheFuture(m.firstSuccessfulMatcher, actual) } else { // so all matchers failed.. Any one of them changing would change the result. for _, matcher := range m.Matchers { if types.MatchMayChangeInTheFuture(matcher, actual) { return true } } return false // none of were going to change } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go
// untested sections: 2 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type BeClosedMatcher struct { } func (matcher *BeClosedMatcher) Match(actual any) (success bool, err error) { if !isChan(actual) { return false, fmt.Errorf("BeClosed matcher expects a channel. Got:\n%s", format.Object(actual, 1)) } channelType := reflect.TypeOf(actual) channelValue := reflect.ValueOf(actual) if channelType.ChanDir() == reflect.SendDir { return false, fmt.Errorf("BeClosed matcher cannot determine if a send-only channel is closed or open. Got:\n%s", format.Object(actual, 1)) } winnerIndex, _, open := reflect.Select([]reflect.SelectCase{ {Dir: reflect.SelectRecv, Chan: channelValue}, {Dir: reflect.SelectDefault}, }) var closed bool if winnerIndex == 0 { closed = !open } else if winnerIndex == 1 { closed = false } return closed, nil } func (matcher *BeClosedMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be closed") } func (matcher *BeClosedMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "to be open") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_field.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_field.go
package matchers import ( "fmt" "reflect" "strings" "github.com/onsi/gomega/format" ) // missingFieldError represents a missing field extraction error that // HaveExistingFieldMatcher can ignore, as opposed to other, sever field // extraction errors, such as nil pointers, et cetera. type missingFieldError string func (e missingFieldError) Error() string { return string(e) } func extractField(actual any, field string, matchername string) (any, error) { fields := strings.SplitN(field, ".", 2) actualValue := reflect.ValueOf(actual) if actualValue.Kind() == reflect.Ptr { actualValue = actualValue.Elem() } if actualValue == (reflect.Value{}) { return nil, fmt.Errorf("%s encountered nil while dereferencing a pointer of type %T.", matchername, actual) } if actualValue.Kind() != reflect.Struct { return nil, fmt.Errorf("%s encountered:\n%s\nWhich is not a struct.", matchername, format.Object(actual, 1)) } var extractedValue reflect.Value if strings.HasSuffix(fields[0], "()") { extractedValue = actualValue.MethodByName(strings.TrimSuffix(fields[0], "()")) if extractedValue == (reflect.Value{}) && actualValue.CanAddr() { extractedValue = actualValue.Addr().MethodByName(strings.TrimSuffix(fields[0], "()")) } if extractedValue == (reflect.Value{}) { ptr := reflect.New(actualValue.Type()) ptr.Elem().Set(actualValue) extractedValue = ptr.MethodByName(strings.TrimSuffix(fields[0], "()")) if extractedValue == (reflect.Value{}) { return nil, missingFieldError(fmt.Sprintf("%s could not find method named '%s' in struct of type %T.", matchername, fields[0], actual)) } } t := extractedValue.Type() if t.NumIn() != 0 || t.NumOut() != 1 { return nil, fmt.Errorf("%s found an invalid method named '%s' in struct of type %T.\nMethods must take no arguments and return exactly one value.", matchername, fields[0], actual) } extractedValue = extractedValue.Call([]reflect.Value{})[0] } else { extractedValue = actualValue.FieldByName(fields[0]) if extractedValue == (reflect.Value{}) { return nil, missingFieldError(fmt.Sprintf("%s could not find field named '%s' in struct:\n%s", matchername, fields[0], format.Object(actual, 1))) } } if len(fields) == 1 { return extractedValue.Interface(), nil } else { return extractField(extractedValue.Interface(), fields[1], matchername) } } type HaveFieldMatcher struct { Field string Expected any } func (matcher *HaveFieldMatcher) expectedMatcher() omegaMatcher { var isMatcher bool expectedMatcher, isMatcher := matcher.Expected.(omegaMatcher) if !isMatcher { expectedMatcher = &EqualMatcher{Expected: matcher.Expected} } return expectedMatcher } func (matcher *HaveFieldMatcher) Match(actual any) (success bool, err error) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { return false, err } return matcher.expectedMatcher().Match(extractedField) } func (matcher *HaveFieldMatcher) FailureMessage(actual any) (message string) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { // this really shouldn't happen return fmt.Sprintf("Failed to extract field '%s': %s", matcher.Field, err) } message = fmt.Sprintf("Value for field '%s' failed to satisfy matcher.\n", matcher.Field) message += matcher.expectedMatcher().FailureMessage(extractedField) return message } func (matcher *HaveFieldMatcher) NegatedFailureMessage(actual any) (message string) { extractedField, err := extractField(actual, matcher.Field, "HaveField") if err != nil { // this really shouldn't happen return fmt.Sprintf("Failed to extract field '%s': %s", matcher.Field, err) } message = fmt.Sprintf("Value for field '%s' satisfied matcher, but should not have.\n", matcher.Field) message += matcher.expectedMatcher().NegatedFailureMessage(extractedField) return message }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go
// untested sections: 2 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/matchers/internal/miter" ) type BeEmptyMatcher struct { } func (matcher *BeEmptyMatcher) Match(actual any) (success bool, err error) { // short-circuit the iterator case, as we only need to see the first // element, if any. if miter.IsIter(actual) { var length int if miter.IsSeq2(actual) { miter.IterateKV(actual, func(k, v reflect.Value) bool { length++; return false }) } else { miter.IterateV(actual, func(v reflect.Value) bool { length++; return false }) } return length == 0, nil } length, ok := lengthOf(actual) if !ok { return false, fmt.Errorf("BeEmpty matcher expects a string/array/map/channel/slice/iterator. Got:\n%s", format.Object(actual, 1)) } return length == 0, nil } func (matcher *BeEmptyMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be empty") } func (matcher *BeEmptyMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be empty") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_http_status_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_http_status_matcher.go
package matchers import ( "fmt" "net/http" "net/http/httptest" "reflect" "strings" "github.com/onsi/gomega/format" "github.com/onsi/gomega/internal/gutil" ) type HaveHTTPStatusMatcher struct { Expected []any } func (matcher *HaveHTTPStatusMatcher) Match(actual any) (success bool, err error) { var resp *http.Response switch a := actual.(type) { case *http.Response: resp = a case *httptest.ResponseRecorder: resp = a.Result() default: return false, fmt.Errorf("HaveHTTPStatus matcher expects *http.Response or *httptest.ResponseRecorder. Got:\n%s", format.Object(actual, 1)) } if len(matcher.Expected) == 0 { return false, fmt.Errorf("HaveHTTPStatus matcher must be passed an int or a string. Got nothing") } for _, expected := range matcher.Expected { switch e := expected.(type) { case int: if resp.StatusCode == e { return true, nil } case string: if resp.Status == e { return true, nil } default: return false, fmt.Errorf("HaveHTTPStatus matcher must be passed int or string types. Got:\n%s", format.Object(expected, 1)) } } return false, nil } func (matcher *HaveHTTPStatusMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\n%s\n%s", formatHttpResponse(actual), "to have HTTP status", matcher.expectedString()) } func (matcher *HaveHTTPStatusMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\n%s\n%s", formatHttpResponse(actual), "not to have HTTP status", matcher.expectedString()) } func (matcher *HaveHTTPStatusMatcher) expectedString() string { var lines []string for _, expected := range matcher.Expected { lines = append(lines, format.Object(expected, 1)) } return strings.Join(lines, "\n") } func formatHttpResponse(input any) string { var resp *http.Response switch r := input.(type) { case *http.Response: resp = r case *httptest.ResponseRecorder: resp = r.Result() default: return "cannot format invalid HTTP response" } body := "<nil>" if resp.Body != nil { defer resp.Body.Close() data, err := gutil.ReadAll(resp.Body) if err != nil { data = []byte("<error reading body>") } body = format.Object(string(data), 0) } var s strings.Builder s.WriteString(fmt.Sprintf("%s<%s>: {\n", format.Indent, reflect.TypeOf(input))) s.WriteString(fmt.Sprintf("%s%sStatus: %s\n", format.Indent, format.Indent, format.Object(resp.Status, 0))) s.WriteString(fmt.Sprintf("%s%sStatusCode: %s\n", format.Indent, format.Indent, format.Object(resp.StatusCode, 0))) s.WriteString(fmt.Sprintf("%s%sBody: %s\n", format.Indent, format.Indent, body)) s.WriteString(fmt.Sprintf("%s}", format.Indent)) return s.String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go
package matchers import ( "fmt" "github.com/onsi/gomega/format" ) type HaveLenMatcher struct { Count int } func (matcher *HaveLenMatcher) Match(actual any) (success bool, err error) { length, ok := lengthOf(actual) if !ok { return false, fmt.Errorf("HaveLen matcher expects a string/array/map/channel/slice/iterator. Got:\n%s", format.Object(actual, 1)) } return length == matcher.Count, nil } func (matcher *HaveLenMatcher) FailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nto have length %d", format.Object(actual, 1), matcher.Count) } func (matcher *HaveLenMatcher) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("Expected\n%s\nnot to have length %d", format.Object(actual, 1), matcher.Count) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_key_of_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/be_key_of_matcher.go
package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" ) type BeKeyOfMatcher struct { Map any } func (matcher *BeKeyOfMatcher) Match(actual any) (success bool, err error) { if !isMap(matcher.Map) { return false, fmt.Errorf("BeKeyOf matcher needs expected to be a map type") } if reflect.TypeOf(actual) == nil { return false, fmt.Errorf("BeKeyOf matcher expects actual to be typed") } var lastError error for _, key := range reflect.ValueOf(matcher.Map).MapKeys() { matcher := &EqualMatcher{Expected: key.Interface()} success, err := matcher.Match(actual) if err != nil { lastError = err continue } if success { return true, nil } } return false, lastError } func (matcher *BeKeyOfMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to be a key of", presentable(valuesOf(matcher.Map))) } func (matcher *BeKeyOfMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to be a key of", presentable(valuesOf(matcher.Map))) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go
// untested sections: 6 package matchers import ( "fmt" "reflect" "github.com/onsi/gomega/format" "github.com/onsi/gomega/matchers/internal/miter" ) type HaveKeyMatcher struct { Key any } func (matcher *HaveKeyMatcher) Match(actual any) (success bool, err error) { if !isMap(actual) && !miter.IsSeq2(actual) { return false, fmt.Errorf("HaveKey matcher expects a map/iter.Seq2. Got:%s", format.Object(actual, 1)) } keyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher) if !keyIsMatcher { keyMatcher = &EqualMatcher{Expected: matcher.Key} } if miter.IsSeq2(actual) { var success bool var err error miter.IterateKV(actual, func(k, v reflect.Value) bool { success, err = keyMatcher.Match(k.Interface()) if err != nil { err = fmt.Errorf("HaveKey's key matcher failed with:\n%s%s", format.Indent, err.Error()) return false } return !success }) return success, err } keys := reflect.ValueOf(actual).MapKeys() for i := 0; i < len(keys); i++ { success, err := keyMatcher.Match(keys[i].Interface()) if err != nil { return false, fmt.Errorf("HaveKey's key matcher failed with:\n%s%s", format.Indent, err.Error()) } if success { return true, nil } } return false, nil } func (matcher *HaveKeyMatcher) FailureMessage(actual any) (message string) { switch matcher.Key.(type) { case omegaMatcher: return format.Message(actual, "to have key matching", matcher.Key) default: return format.Message(actual, "to have key", matcher.Key) } } func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual any) (message string) { switch matcher.Key.(type) { case omegaMatcher: return format.Message(actual, "not to have key matching", matcher.Key) default: return format.Message(actual, "not to have key", matcher.Key) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go
package util import "math" func Odd(n int) bool { return math.Mod(float64(n), 2.0) == 1.0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go
package node type Node struct { ID int Value any } type NodeOrderedSet []Node
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go
package bipartitegraph import ( "slices" . "github.com/onsi/gomega/matchers/support/goraph/edge" . "github.com/onsi/gomega/matchers/support/goraph/node" "github.com/onsi/gomega/matchers/support/goraph/util" ) // LargestMatching implements the Hopcroft–Karp algorithm taking as input a bipartite graph // and outputting a maximum cardinality matching, i.e. a set of as many edges as possible // with the property that no two edges share an endpoint. func (bg *BipartiteGraph) LargestMatching() (matching EdgeSet) { paths := bg.maximalDisjointSLAPCollection(matching) for len(paths) > 0 { for _, path := range paths { matching = matching.SymmetricDifference(path) } paths = bg.maximalDisjointSLAPCollection(matching) } return } func (bg *BipartiteGraph) maximalDisjointSLAPCollection(matching EdgeSet) (result []EdgeSet) { guideLayers := bg.createSLAPGuideLayers(matching) if len(guideLayers) == 0 { return } used := make(map[int]bool) for _, u := range guideLayers[len(guideLayers)-1] { slap, found := bg.findDisjointSLAP(u, matching, guideLayers, used) if found { for _, edge := range slap { used[edge.Node1] = true used[edge.Node2] = true } result = append(result, slap) } } return } func (bg *BipartiteGraph) findDisjointSLAP( start Node, matching EdgeSet, guideLayers []NodeOrderedSet, used map[int]bool, ) ([]Edge, bool) { return bg.findDisjointSLAPHelper(start, EdgeSet{}, len(guideLayers)-1, matching, guideLayers, used) } func (bg *BipartiteGraph) findDisjointSLAPHelper( currentNode Node, currentSLAP EdgeSet, currentLevel int, matching EdgeSet, guideLayers []NodeOrderedSet, used map[int]bool, ) (EdgeSet, bool) { used[currentNode.ID] = true if currentLevel == 0 { return currentSLAP, true } for _, nextNode := range guideLayers[currentLevel-1] { if used[nextNode.ID] { continue } edge, found := bg.Edges.FindByNodes(currentNode, nextNode) if !found { continue } if matching.Contains(edge) == util.Odd(currentLevel) { continue } currentSLAP = append(currentSLAP, edge) slap, found := bg.findDisjointSLAPHelper(nextNode, currentSLAP, currentLevel-1, matching, guideLayers, used) if found { return slap, true } currentSLAP = currentSLAP[:len(currentSLAP)-1] } used[currentNode.ID] = false return nil, false } func (bg *BipartiteGraph) createSLAPGuideLayers(matching EdgeSet) (guideLayers []NodeOrderedSet) { used := make(map[int]bool) currentLayer := NodeOrderedSet{} for _, node := range bg.Left { if matching.Free(node) { used[node.ID] = true currentLayer = append(currentLayer, node) } } if len(currentLayer) == 0 { return []NodeOrderedSet{} } guideLayers = append(guideLayers, currentLayer) done := false for !done { lastLayer := currentLayer currentLayer = NodeOrderedSet{} if util.Odd(len(guideLayers)) { for _, leftNode := range lastLayer { for _, rightNode := range bg.Right { if used[rightNode.ID] { continue } edge, found := bg.Edges.FindByNodes(leftNode, rightNode) if !found || matching.Contains(edge) { continue } currentLayer = append(currentLayer, rightNode) used[rightNode.ID] = true if matching.Free(rightNode) { done = true } } } } else { for _, rightNode := range lastLayer { for _, leftNode := range bg.Left { if used[leftNode.ID] { continue } edge, found := bg.Edges.FindByNodes(leftNode, rightNode) if !found || !matching.Contains(edge) { continue } currentLayer = append(currentLayer, leftNode) used[leftNode.ID] = true } } } if len(currentLayer) == 0 { return []NodeOrderedSet{} } if done { // if last layer - into last layer must be only 'free' nodes currentLayer = slices.DeleteFunc(currentLayer, func(in Node) bool { return !matching.Free(in) }) } guideLayers = append(guideLayers, currentLayer) } return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go
package bipartitegraph import "fmt" import . "github.com/onsi/gomega/matchers/support/goraph/node" import . "github.com/onsi/gomega/matchers/support/goraph/edge" type BipartiteGraph struct { Left NodeOrderedSet Right NodeOrderedSet Edges EdgeSet } func NewBipartiteGraph(leftValues, rightValues []any, neighbours func(any, any) (bool, error)) (*BipartiteGraph, error) { left := NodeOrderedSet{} for i, v := range leftValues { left = append(left, Node{ID: i, Value: v}) } right := NodeOrderedSet{} for j, v := range rightValues { right = append(right, Node{ID: j + len(left), Value: v}) } edges := EdgeSet{} for i, leftValue := range leftValues { for j, rightValue := range rightValues { neighbours, err := neighbours(leftValue, rightValue) if err != nil { return nil, fmt.Errorf("error determining adjacency for %v and %v: %s", leftValue, rightValue, err.Error()) } if neighbours { edges = append(edges, Edge{Node1: left[i].ID, Node2: right[j].ID}) } } } return &BipartiteGraph{left, right, edges}, nil } // FreeLeftRight returns left node values and right node values // of the BipartiteGraph's nodes which are not part of the given edges. func (bg *BipartiteGraph) FreeLeftRight(edges EdgeSet) (leftValues, rightValues []any) { for _, node := range bg.Left { if edges.Free(node) { leftValues = append(leftValues, node.Value) } } for _, node := range bg.Right { if edges.Free(node) { rightValues = append(rightValues, node.Value) } } return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go
package edge import . "github.com/onsi/gomega/matchers/support/goraph/node" type Edge struct { Node1 int Node2 int } type EdgeSet []Edge func (ec EdgeSet) Free(node Node) bool { for _, e := range ec { if e.Node1 == node.ID || e.Node2 == node.ID { return false } } return true } func (ec EdgeSet) Contains(edge Edge) bool { for _, e := range ec { if e == edge { return true } } return false } func (ec EdgeSet) FindByNodes(node1, node2 Node) (Edge, bool) { for _, e := range ec { if (e.Node1 == node1.ID && e.Node2 == node2.ID) || (e.Node1 == node2.ID && e.Node2 == node1.ID) { return e, true } } return Edge{}, false } func (ec EdgeSet) SymmetricDifference(ec2 EdgeSet) EdgeSet { edgesToInclude := make(map[Edge]bool) for _, e := range ec { edgesToInclude[e] = true } for _, e := range ec2 { edgesToInclude[e] = !edgesToInclude[e] } result := EdgeSet{} for e, include := range edgesToInclude { if include { result = append(result, e) } } return result }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/internal/miter/type_support_noiter.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/internal/miter/type_support_noiter.go
//go:build !go1.23 /* Gomega matchers This package implements the Gomega matchers and does not typically need to be imported. See the docs for Gomega for documentation on the matchers http://onsi.github.io/gomega/ */ package miter import "reflect" // HasIterators always returns false for Go versions before 1.23. func HasIterators() bool { return false } // IsIter always returns false for Go versions before 1.23 as there is no // iterator (function) pattern defined yet; see also: // https://tip.golang.org/blog/range-functions. func IsIter(i any) bool { return false } // IsSeq2 always returns false for Go versions before 1.23 as there is no // iterator (function) pattern defined yet; see also: // https://tip.golang.org/blog/range-functions. func IsSeq2(it any) bool { return false } // IterKVTypes always returns nil reflection types for Go versions before 1.23 // as there is no iterator (function) pattern defined yet; see also: // https://tip.golang.org/blog/range-functions. func IterKVTypes(i any) (k, v reflect.Type) { return } // IterateV never loops over what has been passed to it as an iterator for Go // versions before 1.23 as there is no iterator (function) pattern defined yet; // see also: https://tip.golang.org/blog/range-functions. func IterateV(it any, yield func(v reflect.Value) bool) {} // IterateKV never loops over what has been passed to it as an iterator for Go // versions before 1.23 as there is no iterator (function) pattern defined yet; // see also: https://tip.golang.org/blog/range-functions. func IterateKV(it any, yield func(k, v reflect.Value) bool) {}
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/internal/miter/type_support_iter.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/matchers/internal/miter/type_support_iter.go
//go:build go1.23 package miter import ( "reflect" ) // HasIterators always returns false for Go versions before 1.23. func HasIterators() bool { return true } // IsIter returns true if the specified value is a function type that can be // range-d over, otherwise false. // // We don't use reflect's CanSeq and CanSeq2 directly, as these would return // true also for other value types that are range-able, such as integers, // slices, et cetera. Here, we aim only at range-able (iterator) functions. func IsIter(it any) bool { if it == nil { // on purpose we only test for untyped nil. return false } // reject all non-iterator-func values, even if they're range-able. t := reflect.TypeOf(it) if t.Kind() != reflect.Func { return false } return t.CanSeq() || t.CanSeq2() } // IterKVTypes returns the reflection types of an iterator's yield function's K // and optional V arguments, otherwise nil K and V reflection types. func IterKVTypes(it any) (k, v reflect.Type) { if it == nil { return } // reject all non-iterator-func values, even if they're range-able. t := reflect.TypeOf(it) if t.Kind() != reflect.Func { return } // get the reflection types for V, and where applicable, K. switch { case t.CanSeq(): v = t. /*iterator fn*/ In(0). /*yield fn*/ In(0) case t.CanSeq2(): yieldfn := t. /*iterator fn*/ In(0) k = yieldfn.In(0) v = yieldfn.In(1) } return } // IsSeq2 returns true if the passed iterator function is compatible with // iter.Seq2, otherwise false. // // IsSeq2 hides the Go 1.23+ specific reflect.Type.CanSeq2 behind a facade which // is empty for Go versions before 1.23. func IsSeq2(it any) bool { if it == nil { return false } t := reflect.TypeOf(it) return t.Kind() == reflect.Func && t.CanSeq2() } // isNilly returns true if v is either an untyped nil, or is a nil function (not // necessarily an iterator function). func isNilly(v any) bool { if v == nil { return true } rv := reflect.ValueOf(v) return rv.Kind() == reflect.Func && rv.IsNil() } // IterateV loops over the elements produced by an iterator function, passing // the elements to the specified yield function individually and stopping only // when either the iterator function runs out of elements or the yield function // tell us to stop it. // // IterateV works very much like reflect.Value.Seq but hides the Go 1.23+ // specific parts behind a facade which is empty for Go versions before 1.23, in // order to simplify code maintenance for matchers when using older Go versions. func IterateV(it any, yield func(v reflect.Value) bool) { if isNilly(it) { return } // reject all non-iterator-func values, even if they're range-able. t := reflect.TypeOf(it) if t.Kind() != reflect.Func || !t.CanSeq() { return } // Call the specified iterator function, handing it our adaptor to call the // specified generic reflection yield function. reflectedYield := reflect.MakeFunc( t. /*iterator fn*/ In(0), func(args []reflect.Value) []reflect.Value { return []reflect.Value{reflect.ValueOf(yield(args[0]))} }) reflect.ValueOf(it).Call([]reflect.Value{reflectedYield}) } // IterateKV loops over the key-value elements produced by an iterator function, // passing the elements to the specified yield function individually and // stopping only when either the iterator function runs out of elements or the // yield function tell us to stop it. // // IterateKV works very much like reflect.Value.Seq2 but hides the Go 1.23+ // specific parts behind a facade which is empty for Go versions before 1.23, in // order to simplify code maintenance for matchers when using older Go versions. func IterateKV(it any, yield func(k, v reflect.Value) bool) { if isNilly(it) { return } // reject all non-iterator-func values, even if they're range-able. t := reflect.TypeOf(it) if t.Kind() != reflect.Func || !t.CanSeq2() { return } // Call the specified iterator function, handing it our adaptor to call the // specified generic reflection yield function. reflectedYield := reflect.MakeFunc( t. /*iterator fn*/ In(0), func(args []reflect.Value) []reflect.Value { return []reflect.Value{reflect.ValueOf(yield(args[0], args[1]))} }) reflect.ValueOf(it).Call([]reflect.Value{reflectedYield}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/format/format.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/gomega/format/format.go
/* Gomega's format package pretty-prints objects. It explores input objects recursively and generates formatted, indented output with type information. */ // untested sections: 4 package format import ( "context" "fmt" "reflect" "strconv" "strings" "time" ) // Use MaxDepth to set the maximum recursion depth when printing deeply nested objects var MaxDepth = uint(10) // MaxLength of the string representation of an object. // If MaxLength is set to 0, the Object will not be truncated. var MaxLength = 4000 /* By default, all objects (even those that implement fmt.Stringer and fmt.GoStringer) are recursively inspected to generate output. Set UseStringerRepresentation = true to use GoString (for fmt.GoStringers) or String (for fmt.Stringer) instead. Note that GoString and String don't always have all the information you need to understand why a test failed! */ var UseStringerRepresentation = false /* Print the content of context objects. By default it will be suppressed. Set PrintContextObjects = true to enable printing of the context internals. */ var PrintContextObjects = false // TruncatedDiff choose if we should display a truncated pretty diff or not var TruncatedDiff = true // TruncateThreshold (default 50) specifies the maximum length string to print in string comparison assertion error // messages. var TruncateThreshold uint = 50 // CharactersAroundMismatchToInclude (default 5) specifies how many contextual characters should be printed before and // after the first diff location in a truncated string assertion error message. var CharactersAroundMismatchToInclude uint = 5 var contextType = reflect.TypeOf((*context.Context)(nil)).Elem() var timeType = reflect.TypeOf(time.Time{}) // The default indentation string emitted by the format package var Indent = " " var longFormThreshold = 20 // GomegaStringer allows for custom formatting of objects for gomega. type GomegaStringer interface { // GomegaString will be used to custom format an object. // It does not follow UseStringerRepresentation value and will always be called regardless. // It also ignores the MaxLength value. GomegaString() string } /* CustomFormatters can be registered with Gomega via RegisterCustomFormatter() Any value to be rendered by Gomega is passed to each registered CustomFormatters. The CustomFormatter signals that it will handle formatting the value by returning (formatted-string, true) If the CustomFormatter does not want to handle the object it should return ("", false) Strings returned by CustomFormatters are not truncated */ type CustomFormatter func(value any) (string, bool) type CustomFormatterKey uint var customFormatterKey CustomFormatterKey = 1 type customFormatterKeyPair struct { CustomFormatter CustomFormatterKey } /* RegisterCustomFormatter registers a CustomFormatter and returns a CustomFormatterKey You can call UnregisterCustomFormatter with the returned key to unregister the associated CustomFormatter */ func RegisterCustomFormatter(customFormatter CustomFormatter) CustomFormatterKey { key := customFormatterKey customFormatterKey += 1 customFormatters = append(customFormatters, customFormatterKeyPair{customFormatter, key}) return key } /* UnregisterCustomFormatter unregisters a previously registered CustomFormatter. You should pass in the key returned by RegisterCustomFormatter */ func UnregisterCustomFormatter(key CustomFormatterKey) { formatters := []customFormatterKeyPair{} for _, f := range customFormatters { if f.CustomFormatterKey == key { continue } formatters = append(formatters, f) } customFormatters = formatters } var customFormatters = []customFormatterKeyPair{} /* Generates a formatted matcher success/failure message of the form: Expected <pretty printed actual> <message> <pretty printed expected> If expected is omitted, then the message looks like: Expected <pretty printed actual> <message> */ func Message(actual any, message string, expected ...any) string { if len(expected) == 0 { return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message) } return fmt.Sprintf("Expected\n%s\n%s\n%s", Object(actual, 1), message, Object(expected[0], 1)) } /* Generates a nicely formatted matcher success / failure message Much like Message(...), but it attempts to pretty print diffs in strings Expected <string>: "...aaaaabaaaaa..." to equal | <string>: "...aaaaazaaaaa..." */ func MessageWithDiff(actual, message, expected string) string { if TruncatedDiff && len(actual) >= int(TruncateThreshold) && len(expected) >= int(TruncateThreshold) { diffPoint := findFirstMismatch(actual, expected) formattedActual := truncateAndFormat(actual, diffPoint) formattedExpected := truncateAndFormat(expected, diffPoint) spacesBeforeFormattedMismatch := findFirstMismatch(formattedActual, formattedExpected) tabLength := 4 spaceFromMessageToActual := tabLength + len("<string>: ") - len(message) paddingCount := spaceFromMessageToActual + spacesBeforeFormattedMismatch if paddingCount < 0 { return Message(formattedActual, message, formattedExpected) } padding := strings.Repeat(" ", paddingCount) + "|" return Message(formattedActual, message+padding, formattedExpected) } actual = escapedWithGoSyntax(actual) expected = escapedWithGoSyntax(expected) return Message(actual, message, expected) } func escapedWithGoSyntax(str string) string { withQuotes := fmt.Sprintf("%q", str) return withQuotes[1 : len(withQuotes)-1] } func truncateAndFormat(str string, index int) string { leftPadding := `...` rightPadding := `...` start := index - int(CharactersAroundMismatchToInclude) if start < 0 { start = 0 leftPadding = "" } // slice index must include the mis-matched character lengthOfMismatchedCharacter := 1 end := index + int(CharactersAroundMismatchToInclude) + lengthOfMismatchedCharacter if end > len(str) { end = len(str) rightPadding = "" } return fmt.Sprintf("\"%s\"", leftPadding+str[start:end]+rightPadding) } func findFirstMismatch(a, b string) int { aSlice := strings.Split(a, "") bSlice := strings.Split(b, "") for index, str := range aSlice { if index > len(bSlice)-1 { return index } if str != bSlice[index] { return index } } if len(b) > len(a) { return len(a) + 1 } return 0 } const truncateHelpText = ` Gomega truncated this representation as it exceeds 'format.MaxLength'. Consider having the object provide a custom 'GomegaStringer' representation or adjust the parameters in Gomega's 'format' package. Learn more here: https://onsi.github.io/gomega/#adjusting-output ` func truncateLongStrings(s string) string { if MaxLength > 0 && len(s) > MaxLength { var sb strings.Builder for i, r := range s { if i < MaxLength { sb.WriteRune(r) continue } break } sb.WriteString("...\n") sb.WriteString(truncateHelpText) return sb.String() } return s } /* Pretty prints the passed in object at the passed in indentation level. Object recurses into deeply nested objects emitting pretty-printed representations of their components. Modify format.MaxDepth to control how deep the recursion is allowed to go Set format.UseStringerRepresentation to true to return object.GoString() or object.String() when available instead of recursing into the object. Set PrintContextObjects to true to print the content of objects implementing context.Context */ func Object(object any, indentation uint) string { indent := strings.Repeat(Indent, int(indentation)) value := reflect.ValueOf(object) commonRepresentation := "" if err, ok := object.(error); ok && !isNilValue(value) { // isNilValue check needed here to avoid nil deref due to boxed nil commonRepresentation += "\n" + IndentString(err.Error(), indentation) + "\n" + indent } return fmt.Sprintf("%s<%s>: %s%s", indent, formatType(value), commonRepresentation, formatValue(value, indentation)) } /* IndentString takes a string and indents each line by the specified amount. */ func IndentString(s string, indentation uint) string { return indentString(s, indentation, true) } func indentString(s string, indentation uint, indentFirstLine bool) string { result := &strings.Builder{} components := strings.Split(s, "\n") indent := strings.Repeat(Indent, int(indentation)) for i, component := range components { if i > 0 || indentFirstLine { result.WriteString(indent) } result.WriteString(component) if i < len(components)-1 { result.WriteString("\n") } } return result.String() } func formatType(v reflect.Value) string { switch v.Kind() { case reflect.Invalid: return "nil" case reflect.Chan: return fmt.Sprintf("%s | len:%d, cap:%d", v.Type(), v.Len(), v.Cap()) case reflect.Ptr: return fmt.Sprintf("%s | 0x%x", v.Type(), v.Pointer()) case reflect.Slice: return fmt.Sprintf("%s | len:%d, cap:%d", v.Type(), v.Len(), v.Cap()) case reflect.Map: return fmt.Sprintf("%s | len:%d", v.Type(), v.Len()) default: return v.Type().String() } } func formatValue(value reflect.Value, indentation uint) string { if indentation > MaxDepth { return "..." } if isNilValue(value) { return "nil" } if value.CanInterface() { obj := value.Interface() // if a CustomFormatter handles this values, we'll go with that for _, customFormatter := range customFormatters { formatted, handled := customFormatter.CustomFormatter(obj) // do not truncate a user-provided CustomFormatter() if handled { return indentString(formatted, indentation+1, false) } } // GomegaStringer will take precedence to other representations and disregards UseStringerRepresentation if x, ok := obj.(GomegaStringer); ok { // do not truncate a user-defined GomegaString() value return indentString(x.GomegaString(), indentation+1, false) } if UseStringerRepresentation { switch x := obj.(type) { case fmt.GoStringer: return indentString(truncateLongStrings(x.GoString()), indentation+1, false) case fmt.Stringer: return indentString(truncateLongStrings(x.String()), indentation+1, false) } } } if !PrintContextObjects { if value.Type().Implements(contextType) && indentation > 1 { return "<suppressed context>" } } switch value.Kind() { case reflect.Bool: return fmt.Sprintf("%v", value.Bool()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return fmt.Sprintf("%v", value.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return fmt.Sprintf("%v", value.Uint()) case reflect.Uintptr: return fmt.Sprintf("0x%x", value.Uint()) case reflect.Float32, reflect.Float64: return fmt.Sprintf("%v", value.Float()) case reflect.Complex64, reflect.Complex128: return fmt.Sprintf("%v", value.Complex()) case reflect.Chan: return fmt.Sprintf("0x%x", value.Pointer()) case reflect.Func: return fmt.Sprintf("0x%x", value.Pointer()) case reflect.Ptr: return formatValue(value.Elem(), indentation) case reflect.Slice: return truncateLongStrings(formatSlice(value, indentation)) case reflect.String: return truncateLongStrings(formatString(value.String(), indentation)) case reflect.Array: return truncateLongStrings(formatSlice(value, indentation)) case reflect.Map: return truncateLongStrings(formatMap(value, indentation)) case reflect.Struct: if value.Type() == timeType && value.CanInterface() { t, _ := value.Interface().(time.Time) return t.Format(time.RFC3339Nano) } return truncateLongStrings(formatStruct(value, indentation)) case reflect.Interface: return formatInterface(value, indentation) default: if value.CanInterface() { return truncateLongStrings(fmt.Sprintf("%#v", value.Interface())) } return truncateLongStrings(fmt.Sprintf("%#v", value)) } } func formatString(object any, indentation uint) string { if indentation == 1 { s := fmt.Sprintf("%s", object) components := strings.Split(s, "\n") result := "" for i, component := range components { if i == 0 { result += component } else { result += Indent + component } if i < len(components)-1 { result += "\n" } } return result } else { return fmt.Sprintf("%q", object) } } func formatSlice(v reflect.Value, indentation uint) string { if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 && isPrintableString(string(v.Bytes())) { return formatString(v.Bytes(), indentation) } l := v.Len() result := make([]string, l) longest := 0 for i := 0; i < l; i++ { result[i] = formatValue(v.Index(i), indentation+1) if len(result[i]) > longest { longest = len(result[i]) } } if longest > longFormThreshold { indenter := strings.Repeat(Indent, int(indentation)) return fmt.Sprintf("[\n%s%s,\n%s]", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) } return fmt.Sprintf("[%s]", strings.Join(result, ", ")) } func formatMap(v reflect.Value, indentation uint) string { l := v.Len() result := make([]string, l) longest := 0 for i, key := range v.MapKeys() { value := v.MapIndex(key) result[i] = fmt.Sprintf("%s: %s", formatValue(key, indentation+1), formatValue(value, indentation+1)) if len(result[i]) > longest { longest = len(result[i]) } } if longest > longFormThreshold { indenter := strings.Repeat(Indent, int(indentation)) return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) } return fmt.Sprintf("{%s}", strings.Join(result, ", ")) } func formatStruct(v reflect.Value, indentation uint) string { t := v.Type() l := v.NumField() result := []string{} longest := 0 for i := 0; i < l; i++ { structField := t.Field(i) fieldEntry := v.Field(i) representation := fmt.Sprintf("%s: %s", structField.Name, formatValue(fieldEntry, indentation+1)) result = append(result, representation) if len(representation) > longest { longest = len(representation) } } if longest > longFormThreshold { indenter := strings.Repeat(Indent, int(indentation)) return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) } return fmt.Sprintf("{%s}", strings.Join(result, ", ")) } func formatInterface(v reflect.Value, indentation uint) string { return fmt.Sprintf("<%s>%s", formatType(v.Elem()), formatValue(v.Elem(), indentation)) } func isNilValue(a reflect.Value) bool { switch a.Kind() { case reflect.Invalid: return true case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return a.IsNil() } return false } /* Returns true when the string is entirely made of printable runes, false otherwise. */ func isPrintableString(str string) bool { for _, runeValue := range str { if !strconv.IsPrint(runeValue) { return false } } return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/ginkgo_t_dsl.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/ginkgo_t_dsl.go
package ginkgo import ( "context" "io" "testing" "github.com/onsi/ginkgo/v2/internal/testingtproxy" "github.com/onsi/ginkgo/v2/types" ) /* GinkgoT() implements an interface that allows third party libraries to integrate with and build on top of Ginkgo. GinkgoT() is analogous to *testing.T and implements the majority of *testing.T's methods. It can be typically be used a a drop-in replacement with third-party libraries that accept *testing.T through an interface. GinkgoT() takes an optional offset argument that can be used to get the correct line number associated with the failure - though you do not need to use this if you call GinkgoHelper() or GinkgoT().Helper() appropriately GinkgoT() attempts to mimic the behavior of `testing.T` with the exception of the following: - Error/Errorf: failures in Ginkgo always immediately stop execution and there is no mechanism to log a failure without aborting the test. As such Error/Errorf are equivalent to Fatal/Fatalf. - Parallel() is a no-op as Ginkgo's multi-process parallelism model is substantially different from go test's in-process model. You can learn more here: https://onsi.github.io/ginkgo/#using-third-party-libraries */ func GinkgoT(optionalOffset ...int) FullGinkgoTInterface { offset := 1 if len(optionalOffset) > 0 { offset = optionalOffset[0] } return testingtproxy.New( GinkgoWriter, Fail, Skip, DeferCleanup, CurrentSpecReport, AddReportEntry, GinkgoRecover, AttachProgressReporter, suiteConfig.RandomSeed, suiteConfig.ParallelProcess, suiteConfig.ParallelTotal, reporterConfig.NoColor, offset) } /* The portion of the interface returned by GinkgoT() that maps onto methods in the testing package's T. */ type GinkgoTInterface interface { Cleanup(func()) Chdir(dir string) Context() context.Context Setenv(kev, value string) Error(args ...any) Errorf(format string, args ...any) Fail() FailNow() Failed() bool Fatal(args ...any) Fatalf(format string, args ...any) Helper() Log(args ...any) Logf(format string, args ...any) Name() string Parallel() Skip(args ...any) SkipNow() Skipf(format string, args ...any) Skipped() bool TempDir() string Attr(key, value string) Output() io.Writer } /* Additional methods returned by GinkgoT() that provide deeper integration points into Ginkgo */ type FullGinkgoTInterface interface { GinkgoTInterface AddReportEntryVisibilityAlways(name string, args ...any) AddReportEntryVisibilityFailureOrVerbose(name string, args ...any) AddReportEntryVisibilityNever(name string, args ...any) //Prints to the GinkgoWriter Print(a ...any) Printf(format string, a ...any) Println(a ...any) //Provides access to Ginkgo's color formatting, correctly configured to match the color settings specified in the invocation of ginkgo F(format string, args ...any) string Fi(indentation uint, format string, args ...any) string Fiw(indentation uint, maxWidth uint, format string, args ...any) string //Generates a formatted string version of the current spec's timeline RenderTimeline() string GinkgoRecover() DeferCleanup(args ...any) RandomSeed() int64 ParallelProcess() int ParallelTotal() int AttachProgressReporter(func() string) func() } /* GinkgoTB() implements a wrapper that exactly matches the testing.TB interface. In go 1.18 a new private() function was added to the testing.TB interface. Any function which accepts testing.TB as input needs to be passed in something that directly implements testing.TB. This wrapper satisfies the testing.TB interface and intended to be used as a drop-in replacement with third party libraries that accept testing.TB. Similar to GinkgoT(), GinkgoTB() takes an optional offset argument that can be used to get the correct line number associated with the failure - though you do not need to use this if you call GinkgoHelper() or GinkgoT().Helper() appropriately */ func GinkgoTB(optionalOffset ...int) *GinkgoTBWrapper { offset := 2 if len(optionalOffset) > 0 { offset = optionalOffset[0] } return &GinkgoTBWrapper{GinkgoT: GinkgoT(offset)} } type GinkgoTBWrapper struct { testing.TB GinkgoT FullGinkgoTInterface } func (g *GinkgoTBWrapper) Cleanup(f func()) { g.GinkgoT.Cleanup(f) } func (g *GinkgoTBWrapper) Chdir(dir string) { g.GinkgoT.Chdir(dir) } func (g *GinkgoTBWrapper) Context() context.Context { return g.GinkgoT.Context() } func (g *GinkgoTBWrapper) Error(args ...any) { g.GinkgoT.Error(args...) } func (g *GinkgoTBWrapper) Errorf(format string, args ...any) { g.GinkgoT.Errorf(format, args...) } func (g *GinkgoTBWrapper) Fail() { g.GinkgoT.Fail() } func (g *GinkgoTBWrapper) FailNow() { g.GinkgoT.FailNow() } func (g *GinkgoTBWrapper) Failed() bool { return g.GinkgoT.Failed() } func (g *GinkgoTBWrapper) Fatal(args ...any) { g.GinkgoT.Fatal(args...) } func (g *GinkgoTBWrapper) Fatalf(format string, args ...any) { g.GinkgoT.Fatalf(format, args...) } func (g *GinkgoTBWrapper) Helper() { types.MarkAsHelper(1) } func (g *GinkgoTBWrapper) Log(args ...any) { g.GinkgoT.Log(args...) } func (g *GinkgoTBWrapper) Logf(format string, args ...any) { g.GinkgoT.Logf(format, args...) } func (g *GinkgoTBWrapper) Name() string { return g.GinkgoT.Name() } func (g *GinkgoTBWrapper) Setenv(key, value string) { g.GinkgoT.Setenv(key, value) } func (g *GinkgoTBWrapper) Skip(args ...any) { g.GinkgoT.Skip(args...) } func (g *GinkgoTBWrapper) SkipNow() { g.GinkgoT.SkipNow() } func (g *GinkgoTBWrapper) Skipf(format string, args ...any) { g.GinkgoT.Skipf(format, args...) } func (g *GinkgoTBWrapper) Skipped() bool { return g.GinkgoT.Skipped() } func (g *GinkgoTBWrapper) TempDir() string { return g.GinkgoT.TempDir() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/deprecated_dsl.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/deprecated_dsl.go
package ginkgo import ( "time" "github.com/onsi/ginkgo/v2/internal" "github.com/onsi/ginkgo/v2/internal/global" "github.com/onsi/ginkgo/v2/reporters" "github.com/onsi/ginkgo/v2/types" ) /* Deprecated: Done Channel for asynchronous testing The Done channel pattern is no longer supported in Ginkgo 2.0. See here for better patterns for asynchronous testing: https://onsi.github.io/ginkgo/#patterns-for-asynchronous-testing For a migration guide see: https://onsi.github.io/ginkgo/MIGRATING_TO_V2#removed-async-testing */ type Done = internal.Done /* Deprecated: Custom Ginkgo test reporters are deprecated in Ginkgo 2.0. Use Ginkgo's reporting nodes instead and 2.0 reporting infrastructure instead. You can learn more here: https://onsi.github.io/ginkgo/#reporting-infrastructure For a migration guide see: https://onsi.github.io/ginkgo/MIGRATING_TO_V2#removed-custom-reporters */ type Reporter = reporters.DeprecatedReporter /* Deprecated: Custom Reporters have been removed in Ginkgo 2.0. RunSpecsWithDefaultAndCustomReporters will simply call RunSpecs() Use Ginkgo's reporting nodes instead and 2.0 reporting infrastructure instead. You can learn more here: https://onsi.github.io/ginkgo/#reporting-infrastructure For a migration guide see: https://onsi.github.io/ginkgo/MIGRATING_TO_V2#removed-custom-reporters */ func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, _ []Reporter) bool { deprecationTracker.TrackDeprecation(types.Deprecations.CustomReporter()) return RunSpecs(t, description) } /* Deprecated: Custom Reporters have been removed in Ginkgo 2.0. RunSpecsWithCustomReporters will simply call RunSpecs() Use Ginkgo's reporting nodes instead and 2.0 reporting infrastructure instead. You can learn more here: https://onsi.github.io/ginkgo/#reporting-infrastructure For a migration guide see: https://onsi.github.io/ginkgo/MIGRATING_TO_V2#removed-custom-reporters */ func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, _ []Reporter) bool { deprecationTracker.TrackDeprecation(types.Deprecations.CustomReporter()) return RunSpecs(t, description) } /* Deprecated: GinkgoTestDescription has been replaced with SpecReport. Use CurrentSpecReport() instead. You can learn more here: https://onsi.github.io/ginkgo/#getting-a-report-for-the-current-spec The SpecReport type is documented here: https://pkg.go.dev/github.com/onsi/ginkgo/v2/types#SpecReport */ type DeprecatedGinkgoTestDescription struct { FullTestText string ComponentTexts []string TestText string FileName string LineNumber int Failed bool Duration time.Duration } type GinkgoTestDescription = DeprecatedGinkgoTestDescription /* Deprecated: CurrentGinkgoTestDescription has been replaced with CurrentSpecReport. Use CurrentSpecReport() instead. You can learn more here: https://onsi.github.io/ginkgo/#getting-a-report-for-the-current-spec The SpecReport type is documented here: https://pkg.go.dev/github.com/onsi/ginkgo/v2/types#SpecReport */ func CurrentGinkgoTestDescription() DeprecatedGinkgoTestDescription { deprecationTracker.TrackDeprecation( types.Deprecations.CurrentGinkgoTestDescription(), types.NewCodeLocation(1), ) report := global.Suite.CurrentSpecReport() if report.State == types.SpecStateInvalid { return GinkgoTestDescription{} } componentTexts := []string{} componentTexts = append(componentTexts, report.ContainerHierarchyTexts...) componentTexts = append(componentTexts, report.LeafNodeText) return DeprecatedGinkgoTestDescription{ ComponentTexts: componentTexts, FullTestText: report.FullText(), TestText: report.LeafNodeText, FileName: report.LeafNodeLocation.FileName, LineNumber: report.LeafNodeLocation.LineNumber, Failed: report.State.Is(types.SpecStateFailureStates), Duration: report.RunTime, } } /* Deprecated: GinkgoParallelNode() has been renamed to GinkgoParallelProcess() */ func GinkgoParallelNode() int { deprecationTracker.TrackDeprecation( types.Deprecations.ParallelNode(), types.NewCodeLocation(1), ) return GinkgoParallelProcess() } /* Deprecated: Benchmarker has been removed from Ginkgo 2.0 Use Gomega's gmeasure package instead. You can learn more here: https://onsi.github.io/ginkgo/#benchmarking-code */ type Benchmarker interface { Time(name string, body func(), info ...any) (elapsedTime time.Duration) RecordValue(name string, value float64, info ...any) RecordValueWithPrecision(name string, value float64, units string, precision int, info ...any) } /* Deprecated: Measure() has been removed from Ginkgo 2.0 Use Gomega's gmeasure package instead. You can learn more here: https://onsi.github.io/ginkgo/#benchmarking-code */ func Measure(_ ...any) bool { deprecationTracker.TrackDeprecation(types.Deprecations.Measure(), types.NewCodeLocation(1)) return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/decorator_dsl.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/decorator_dsl.go
package ginkgo import ( "github.com/onsi/ginkgo/v2/internal" "github.com/onsi/ginkgo/v2/types" ) /* Offset(uint) is a decorator that allows you to change the stack-frame offset used when computing the line number of the node in question. You can learn more here: https://onsi.github.io/ginkgo/#the-offset-decorator You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ type Offset = internal.Offset /* FlakeAttempts(uint N) is a decorator that allows you to mark individual specs or spec containers as flaky. Ginkgo will run them up to `N` times until they pass. You can learn more here: https://onsi.github.io/ginkgo/#the-flakeattempts-decorator You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ type FlakeAttempts = internal.FlakeAttempts /* MustPassRepeatedly(uint N) is a decorator that allows you to repeat the execution of individual specs or spec containers. Ginkgo will run them up to `N` times until they fail. You can learn more here: https://onsi.github.io/ginkgo/#the-mustpassrepeatedly-decorator You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ type MustPassRepeatedly = internal.MustPassRepeatedly /* Focus is a decorator that allows you to mark a spec or container as focused. Identical to FIt and FDescribe. You can learn more here: https://onsi.github.io/ginkgo/#filtering-specs You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ const Focus = internal.Focus /* Pending is a decorator that allows you to mark a spec or container as pending. Identical to PIt and PDescribe. You can learn more here: https://onsi.github.io/ginkgo/#filtering-specs You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ const Pending = internal.Pending /* Serial is a decorator that allows you to mark a spec or container as serial. These specs will never run in parallel with other specs. Specs in ordered containers cannot be marked as serial - mark the ordered container instead. You can learn more here: https://onsi.github.io/ginkgo/#serial-specs You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ const Serial = internal.Serial /* Ordered is a decorator that allows you to mark a container as ordered. Specs in the container will always run in the order they appear. They will never be randomized and they will never run in parallel with one another, though they may run in parallel with other specs. You can learn more here: https://onsi.github.io/ginkgo/#ordered-containers You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ const Ordered = internal.Ordered /* ContinueOnFailure is a decorator that allows you to mark an Ordered container to continue running specs even if failures occur. Ordinarily an ordered container will stop running specs after the first failure occurs. Note that if a BeforeAll or a BeforeEach/JustBeforeEach annotated with OncePerOrdered fails then no specs will run as the precondition for the Ordered container will consider to be failed. ContinueOnFailure only applies to the outermost Ordered container. Attempting to place ContinueOnFailure in a nested container will result in an error. You can learn more here: https://onsi.github.io/ginkgo/#ordered-containers You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ const ContinueOnFailure = internal.ContinueOnFailure /* OncePerOrdered is a decorator that allows you to mark outer BeforeEach, AfterEach, JustBeforeEach, and JustAfterEach setup nodes to run once per ordered context. Normally these setup nodes run around each individual spec, with OncePerOrdered they will run once around the set of specs in an ordered container. The behavior for non-Ordered containers/specs is unchanged. You can learn more here: https://onsi.github.io/ginkgo/#setup-around-ordered-containers-the-onceperordered-decorator You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ const OncePerOrdered = internal.OncePerOrdered /* Label decorates specs with Labels. Multiple labels can be passed to Label and these can be arbitrary strings but must not include the following characters: "&|!,()/". Labels can be applied to container and subject nodes, but not setup nodes. You can provide multiple Labels to a given node and a spec's labels is the union of all labels in its node hierarchy. You can learn more here: https://onsi.github.io/ginkgo/#spec-labels You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ func Label(labels ...string) Labels { return Labels(labels) } /* Labels are the type for spec Label decorators. Use Label(...) to construct Labels. You can learn more here: https://onsi.github.io/ginkgo/#spec-labels */ type Labels = internal.Labels /* SemVerConstraint decorates specs with SemVerConstraints. Multiple semantic version constraints can be passed to SemVerConstraint and these strings must follow the semantic version constraint rules. SemVerConstraints can be applied to container and subject nodes, but not setup nodes. You can provide multiple SemVerConstraints to a given node and a spec's semantic version constraints is the union of all semantic version constraints in its node hierarchy. You can learn more here: https://onsi.github.io/ginkgo/#spec-semantic-version-filtering You can learn more about decorators here: https://onsi.github.io/ginkgo/#decorator-reference */ func SemVerConstraint(semVerConstraints ...string) SemVerConstraints { return SemVerConstraints(semVerConstraints) } /* SemVerConstraints are the type for spec SemVerConstraint decorators. Use SemVerConstraint(...) to construct SemVerConstraints. You can learn more here: https://onsi.github.io/ginkgo/#spec-semantic-version-filtering */ type SemVerConstraints = internal.SemVerConstraints /* PollProgressAfter allows you to override the configured value for --poll-progress-after for a particular node. Ginkgo will start emitting node progress if the node is still running after a duration of PollProgressAfter. This allows you to get quicker feedback about the state of a long-running spec. */ type PollProgressAfter = internal.PollProgressAfter /* PollProgressInterval allows you to override the configured value for --poll-progress-interval for a particular node. Once a node has been running for longer than PollProgressAfter Ginkgo will emit node progress periodically at an interval of PollProgresInterval. */ type PollProgressInterval = internal.PollProgressInterval /* NodeTimeout allows you to specify a timeout for an indivdiual node. The node cannot be a container and must be interruptible (i.e. it must be passed a function that accepts a SpecContext or context.Context). If the node does not exit within the specified NodeTimeout its context will be cancelled. The node wil then have a period of time controlled by the GracePeriod decorator (or global --grace-period command-line argument) to exit. If the node does not exit within GracePeriod Ginkgo will leak the node and proceed to any clean-up nodes associated with the current spec. */ type NodeTimeout = internal.NodeTimeout /* SpecTimeout allows you to specify a timeout for an indivdiual spec. SpecTimeout can only decorate interruptible It nodes. All nodes associated with the It node will need to complete before the SpecTimeout has elapsed. Individual nodes (e.g. BeforeEach) may be decorated with different NodeTimeouts - but these can only serve to provide a more stringent deadline for the node in question; they cannot extend the deadline past the SpecTimeout. If the spec does not complete within the specified SpecTimeout the currently running node will have its context cancelled. The node wil then have a period of time controlled by that node's GracePeriod decorator (or global --grace-period command-line argument) to exit. If the node does not exit within GracePeriod Ginkgo will leak the node and proceed to any clean-up nodes associated with the current spec. */ type SpecTimeout = internal.SpecTimeout /* GracePeriod denotes the period of time Ginkgo will wait for an interruptible node to exit once an interruption (whether due to a timeout or a user-invoked signal) has occurred. If both the global --grace-period cli flag and a GracePeriod decorator are specified the value in the decorator will take precedence. Nodes that do not finish within a GracePeriod will be leaked and Ginkgo will proceed to run subsequent nodes. In the event of a timeout, such leaks will be reported to the user. */ type GracePeriod = internal.GracePeriod /* SuppressProgressReporting is a decorator that allows you to disable progress reporting of a particular node. This is useful if `ginkgo -v -progress` is generating too much noise; particularly if you have a `ReportAfterEach` node that is running for every skipped spec and is generating lots of progress reports. */ const SuppressProgressReporting = internal.SuppressProgressReporting /* AroundNode registers a function that runs before each individual node. This is considered a more advanced decorator. Please read the [docs](https://onsi.github.io/ginkgo/#advanced-around-node) for more information. Allowed signatures: - AroundNode(func()) - func will be called before the node is run. - AroundNode(func(ctx context.Context) context.Context) - func can wrap the passed in context and return a new one which will be passed on to the node. - AroundNode(func(ctx context.Context, body func(ctx context.Context))) - ctx is the context for the node and body is a function that must be called to run the node. This gives you complete control over what runs before and after the node. Multiple AroundNode decorators can be applied to a single node and they will run in the order they are applied. Unlike setup nodes like BeforeEach and DeferCleanup, AroundNode is guaranteed to run in the same goroutine as the decorated node. This is necessary when working with lower-level libraries that must run on a single thread (you can call runtime.LockOSThread() in the AroundNode to ensure that the node runs on a single thread). Since AroundNode allows you to modify the context you can also use AroundNode to implement shared setup that attaches values to the context. You must return a context that inherits from the passed in context. If applied to a container, AroundNode will run before every node in the container. Including setup nodes like BeforeEach and DeferCleanup. AroundNode can also be applied to RunSpecs to run before every node in the suite. */ func AroundNode[F types.AroundNodeAllowedFuncs](f F) types.AroundNodeDecorator { return types.AroundNode(f, types.NewCodeLocation(1)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/core_dsl.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/core_dsl.go
/* Ginkgo is a testing framework for Go designed to help you write expressive tests. https://github.com/onsi/ginkgo MIT-Licensed The godoc documentation outlines Ginkgo's API. Since Ginkgo is a Domain-Specific Language it is important to build a mental model for Ginkgo - the narrative documentation at https://onsi.github.io/ginkgo/ is designed to help you do that. You should start there - even a brief skim will be helpful. At minimum you should skim through the https://onsi.github.io/ginkgo/#getting-started chapter. Ginkgo's is best paired with the Gomega matcher library: https://github.com/onsi/gomega You can run Ginkgo specs with go test - however we recommend using the ginkgo cli. It enables functionality that go test does not (especially running suites in parallel). You can learn more at https://onsi.github.io/ginkgo/#ginkgo-cli-overview or by running 'ginkgo help'. */ package ginkgo import ( "fmt" "io" "os" "path/filepath" "strings" "github.com/go-logr/logr" "github.com/onsi/ginkgo/v2/formatter" "github.com/onsi/ginkgo/v2/internal" "github.com/onsi/ginkgo/v2/internal/global" "github.com/onsi/ginkgo/v2/internal/interrupt_handler" "github.com/onsi/ginkgo/v2/internal/parallel_support" "github.com/onsi/ginkgo/v2/reporters" "github.com/onsi/ginkgo/v2/types" ) const GINKGO_VERSION = types.VERSION var flagSet types.GinkgoFlagSet var deprecationTracker = types.NewDeprecationTracker() var suiteConfig = types.NewDefaultSuiteConfig() var reporterConfig = types.NewDefaultReporterConfig() var suiteDidRun = false var outputInterceptor internal.OutputInterceptor var client parallel_support.Client func init() { var err error flagSet, err = types.BuildTestSuiteFlagSet(&suiteConfig, &reporterConfig) exitIfErr(err) writer := internal.NewWriter(os.Stdout) GinkgoWriter = writer GinkgoLogr = internal.GinkgoLogrFunc(writer) } func exitIfErr(err error) { if err != nil { if outputInterceptor != nil { outputInterceptor.Shutdown() } if client != nil { client.Close() } fmt.Fprintln(formatter.ColorableStdErr, err.Error()) os.Exit(1) } } func exitIfErrors(errors []error) { if len(errors) > 0 { if outputInterceptor != nil { outputInterceptor.Shutdown() } if client != nil { client.Close() } for _, err := range errors { fmt.Fprintln(formatter.ColorableStdErr, err.Error()) } os.Exit(1) } } // The interface implemented by GinkgoWriter type GinkgoWriterInterface interface { io.Writer Print(a ...any) Printf(format string, a ...any) Println(a ...any) TeeTo(writer io.Writer) ClearTeeWriters() } /* SpecContext is the context object passed into nodes that are subject to a timeout or need to be notified of an interrupt. It implements the standard context.Context interface but also contains additional helpers to provide an extensibility point for Ginkgo. (As an example, Gomega's Eventually can use the methods defined on SpecContext to provide deeper integration with Ginkgo). You can do anything with SpecContext that you do with a typical context.Context including wrapping it with any of the context.With* methods. Ginkgo will cancel the SpecContext when a node is interrupted (e.g. by the user sending an interrupt signal) or when a node has exceeded its allowed run-time. Note, however, that even in cases where a node has a deadline, SpecContext will not return a deadline via .Deadline(). This is because Ginkgo does not use a WithDeadline() context to model node deadlines as Ginkgo needs control over the precise timing of the context cancellation to ensure it can provide an accurate progress report at the moment of cancellation. */ type SpecContext = internal.SpecContext /* GinkgoWriter implements a GinkgoWriterInterface and io.Writer When running in verbose mode (ginkgo -v) any writes to GinkgoWriter will be immediately printed to stdout. Otherwise, GinkgoWriter will buffer any writes produced during the current test and flush them to screen only if the current test fails. GinkgoWriter also provides convenience Print, Printf and Println methods and allows you to tee to a custom writer via GinkgoWriter.TeeTo(writer). Writes to GinkgoWriter are immediately sent to any registered TeeTo() writers. You can unregister all TeeTo() Writers with GinkgoWriter.ClearTeeWriters() You can learn more at https://onsi.github.io/ginkgo/#logging-output */ var GinkgoWriter GinkgoWriterInterface /* GinkgoLogr is a logr.Logger that writes to GinkgoWriter */ var GinkgoLogr logr.Logger // The interface by which Ginkgo receives *testing.T type GinkgoTestingT interface { Fail() } /* GinkgoConfiguration returns the configuration of the current suite. The first return value is the SuiteConfig which controls aspects of how the suite runs, the second return value is the ReporterConfig which controls aspects of how Ginkgo's default reporter emits output. Mutating the returned configurations has no effect. To reconfigure Ginkgo programmatically you need to pass in your mutated copies into RunSpecs(). You can learn more at https://onsi.github.io/ginkgo/#overriding-ginkgos-command-line-configuration-in-the-suite */ func GinkgoConfiguration() (types.SuiteConfig, types.ReporterConfig) { return suiteConfig, reporterConfig } /* GinkgoRandomSeed returns the seed used to randomize spec execution order. It is useful for seeding your own pseudorandom number generators to ensure consistent executions from run to run, where your tests contain variability (for example, when selecting random spec data). You can learn more at https://onsi.github.io/ginkgo/#spec-randomization */ func GinkgoRandomSeed() int64 { return suiteConfig.RandomSeed } /* GinkgoParallelProcess returns the parallel process number for the current ginkgo process The process number is 1-indexed. You can use GinkgoParallelProcess() to shard access to shared resources across your suites. You can learn more about patterns for sharding at https://onsi.github.io/ginkgo/#patterns-for-parallel-integration-specs For more on how specs are parallelized in Ginkgo, see http://onsi.github.io/ginkgo/#spec-parallelization */ func GinkgoParallelProcess() int { return suiteConfig.ParallelProcess } /* GinkgoHelper marks the function it's called in as a test helper. When a failure occurs inside a helper function, Ginkgo will skip the helper when analyzing the stack trace to identify where the failure occurred. This is an alternative, simpler, mechanism to passing in a skip offset when calling Fail or using Gomega. */ func GinkgoHelper() { types.MarkAsHelper(1) } /* GinkgoLabelFilter() returns the label filter configured for this suite via `--label-filter`. You can use this to manually check if a set of labels would satisfy the filter via: if (Label("cat", "dog").MatchesLabelFilter(GinkgoLabelFilter())) { //... } */ func GinkgoLabelFilter() string { suiteConfig, _ := GinkgoConfiguration() return suiteConfig.LabelFilter } /* GinkgoSemVerFilter() returns the semantic version filter configured for this suite via `--sem-ver-filter`. You can use this to manually check if a set of semantic version constraints would satisfy the filter via: if (SemVerConstraint("> 2.6.0", "< 2.8.0").MatchesSemVerFilter(GinkgoSemVerFilter())) { //... } */ func GinkgoSemVerFilter() string { suiteConfig, _ := GinkgoConfiguration() return suiteConfig.SemVerFilter } /* PauseOutputInterception() pauses Ginkgo's output interception. This is only relevant when running in parallel and output to stdout/stderr is being intercepted. You generally don't need to call this function - however there are cases when Ginkgo's output interception mechanisms can interfere with external processes launched by the test process. In particular, if an external process is launched that has cmd.Stdout/cmd.Stderr set to os.Stdout/os.Stderr then Ginkgo's output interceptor will hang. To circumvent this, set cmd.Stdout/cmd.Stderr to GinkgoWriter. If, for some reason, you aren't able to do that, you can PauseOutputInterception() before starting the process then ResumeOutputInterception() after starting it. Note that PauseOutputInterception() does not cause stdout writes to print to the console - this simply stops intercepting and storing stdout writes to an internal buffer. */ func PauseOutputInterception() { if outputInterceptor == nil { return } outputInterceptor.PauseIntercepting() } // ResumeOutputInterception() - see docs for PauseOutputInterception() func ResumeOutputInterception() { if outputInterceptor == nil { return } outputInterceptor.ResumeIntercepting() } /* RunSpecs is the entry point for the Ginkgo spec runner. You must call this within a Golang testing TestX(t *testing.T) function. If you bootstrapped your suite with "ginkgo bootstrap" this is already done for you. Ginkgo is typically configured via command-line flags. This configuration can be overridden, however, and passed into RunSpecs as optional arguments: func TestMySuite(t *testing.T) { RegisterFailHandler(gomega.Fail) // fetch the current config suiteConfig, reporterConfig := GinkgoConfiguration() // adjust it suiteConfig.SkipStrings = []string{"NEVER-RUN"} reporterConfig.FullTrace = true // pass it in to RunSpecs RunSpecs(t, "My Suite", suiteConfig, reporterConfig) } Note that some configuration changes can lead to undefined behavior. For example, you should not change ParallelProcess or ParallelTotal as the Ginkgo CLI is responsible for setting these and orchestrating parallel specs across the parallel processes. See http://onsi.github.io/ginkgo/#spec-parallelization for more on how specs are parallelized in Ginkgo. You can also pass suite-level Label() decorators to RunSpecs. The passed-in labels will apply to all specs in the suite. */ func RunSpecs(t GinkgoTestingT, description string, args ...any) bool { if suiteDidRun { exitIfErr(types.GinkgoErrors.RerunningSuite()) } suiteDidRun = true err := global.PushClone() if err != nil { exitIfErr(err) } defer global.PopClone() suiteLabels, suiteSemVerConstraints, suiteAroundNodes := extractSuiteConfiguration(args) var reporter reporters.Reporter if suiteConfig.ParallelTotal == 1 { reporter = reporters.NewDefaultReporter(reporterConfig, formatter.ColorableStdOut) outputInterceptor = internal.NoopOutputInterceptor{} client = nil } else { reporter = reporters.NoopReporter{} switch strings.ToLower(suiteConfig.OutputInterceptorMode) { case "swap": outputInterceptor = internal.NewOSGlobalReassigningOutputInterceptor() case "none": outputInterceptor = internal.NoopOutputInterceptor{} default: outputInterceptor = internal.NewOutputInterceptor() } client = parallel_support.NewClient(suiteConfig.ParallelHost) if !client.Connect() { client = nil exitIfErr(types.GinkgoErrors.UnreachableParallelHost(suiteConfig.ParallelHost)) } defer client.Close() } writer := GinkgoWriter.(*internal.Writer) if reporterConfig.Verbosity().GTE(types.VerbosityLevelVerbose) && suiteConfig.ParallelTotal == 1 { writer.SetMode(internal.WriterModeStreamAndBuffer) } else { writer.SetMode(internal.WriterModeBufferOnly) } if reporterConfig.WillGenerateReport() { registerReportAfterSuiteNodeForAutogeneratedReports(reporterConfig) } err = global.Suite.BuildTree() exitIfErr(err) suitePath, err := getwd() exitIfErr(err) suitePath, err = filepath.Abs(suitePath) exitIfErr(err) passed, hasFocusedTests := global.Suite.Run(description, suiteLabels, suiteSemVerConstraints, suiteAroundNodes, suitePath, global.Failer, reporter, writer, outputInterceptor, interrupt_handler.NewInterruptHandler(client), client, internal.RegisterForProgressSignal, suiteConfig) outputInterceptor.Shutdown() flagSet.ValidateDeprecations(deprecationTracker) if deprecationTracker.DidTrackDeprecations() { fmt.Fprintln(formatter.ColorableStdErr, deprecationTracker.DeprecationsReport()) } if !passed { t.Fail() } if passed && hasFocusedTests && strings.TrimSpace(os.Getenv("GINKGO_EDITOR_INTEGRATION")) == "" { fmt.Println("PASS | FOCUSED") os.Exit(types.GINKGO_FOCUS_EXIT_CODE) } return passed } func extractSuiteConfiguration(args []any) (Labels, SemVerConstraints, types.AroundNodes) { suiteLabels := Labels{} suiteSemVerConstraints := SemVerConstraints{} aroundNodes := types.AroundNodes{} configErrors := []error{} for _, arg := range args { switch arg := arg.(type) { case types.SuiteConfig: suiteConfig = arg case types.ReporterConfig: reporterConfig = arg case Labels: suiteLabels = append(suiteLabels, arg...) case SemVerConstraints: suiteSemVerConstraints = append(suiteSemVerConstraints, arg...) case types.AroundNodeDecorator: aroundNodes = append(aroundNodes, arg) default: configErrors = append(configErrors, types.GinkgoErrors.UnknownTypePassedToRunSpecs(arg)) } } exitIfErrors(configErrors) configErrors = types.VetConfig(flagSet, suiteConfig, reporterConfig) if len(configErrors) > 0 { fmt.Fprintf(formatter.ColorableStdErr, formatter.F("{{red}}Ginkgo detected configuration issues:{{/}}\n")) for _, err := range configErrors { fmt.Fprintf(formatter.ColorableStdErr, err.Error()) } os.Exit(1) } return suiteLabels, suiteSemVerConstraints, aroundNodes } func getwd() (string, error) { if !strings.EqualFold(os.Getenv("GINKGO_PRESERVE_CACHE"), "true") { // Getwd calls os.Getenv("PWD"), which breaks test caching if the cache // is shared between two different directories with the same test code. return os.Getwd() } return "", nil } /* PreviewSpecs walks the testing tree and produces a report without actually invoking the specs. See http://onsi.github.io/ginkgo/#previewing-specs for more information. */ func PreviewSpecs(description string, args ...any) Report { err := global.PushClone() if err != nil { exitIfErr(err) } defer global.PopClone() suiteLabels, suiteSemVerConstraints, suiteAroundNodes := extractSuiteConfiguration(args) priorDryRun, priorParallelTotal, priorParallelProcess := suiteConfig.DryRun, suiteConfig.ParallelTotal, suiteConfig.ParallelProcess suiteConfig.DryRun, suiteConfig.ParallelTotal, suiteConfig.ParallelProcess = true, 1, 1 defer func() { suiteConfig.DryRun, suiteConfig.ParallelTotal, suiteConfig.ParallelProcess = priorDryRun, priorParallelTotal, priorParallelProcess }() reporter := reporters.NoopReporter{} outputInterceptor = internal.NoopOutputInterceptor{} client = nil writer := GinkgoWriter.(*internal.Writer) err = global.Suite.BuildTree() exitIfErr(err) suitePath, err := getwd() exitIfErr(err) suitePath, err = filepath.Abs(suitePath) exitIfErr(err) global.Suite.Run(description, suiteLabels, suiteSemVerConstraints, suiteAroundNodes, suitePath, global.Failer, reporter, writer, outputInterceptor, interrupt_handler.NewInterruptHandler(client), client, internal.RegisterForProgressSignal, suiteConfig) return global.Suite.GetPreviewReport() } /* Skip instructs Ginkgo to skip the current spec You can call Skip in any Setup or Subject node closure. For more on how to filter specs in Ginkgo see https://onsi.github.io/ginkgo/#filtering-specs */ func Skip(message string, callerSkip ...int) { skip := 0 if len(callerSkip) > 0 { skip = callerSkip[0] } cl := types.NewCodeLocationWithStackTrace(skip + 1) global.Failer.Skip(message, cl) panic(types.GinkgoErrors.UncaughtGinkgoPanic(cl)) } /* Fail notifies Ginkgo that the current spec has failed. (Gomega will call Fail for you automatically when an assertion fails.) Under the hood, Fail panics to end execution of the current spec. Ginkgo will catch this panic and proceed with the subsequent spec. If you call Fail, or make an assertion, within a goroutine launched by your spec you must add defer GinkgoRecover() to the goroutine to catch the panic emitted by Fail. You can call Fail in any Setup or Subject node closure. You can learn more about how Ginkgo manages failures here: https://onsi.github.io/ginkgo/#mental-model-how-ginkgo-handles-failure */ func Fail(message string, callerSkip ...int) { skip := 0 if len(callerSkip) > 0 { skip = callerSkip[0] } cl := types.NewCodeLocationWithStackTrace(skip + 1) global.Failer.Fail(message, cl) panic(types.GinkgoErrors.UncaughtGinkgoPanic(cl)) } /* AbortSuite instructs Ginkgo to fail the current spec and skip all subsequent specs, thereby aborting the suite. You can call AbortSuite in any Setup or Subject node closure. You can learn more about how Ginkgo handles suite interruptions here: https://onsi.github.io/ginkgo/#interrupting-aborting-and-timing-out-suites */ func AbortSuite(message string, callerSkip ...int) { skip := 0 if len(callerSkip) > 0 { skip = callerSkip[0] } cl := types.NewCodeLocationWithStackTrace(skip + 1) global.Failer.AbortSuite(message, cl) panic(types.GinkgoErrors.UncaughtGinkgoPanic(cl)) } /* ignorablePanic is used by Gomega to signal to GinkgoRecover that Goemga is handling the error associated with this panic. It i used when Eventually/Consistently are passed a func(g Gomega) and the resulting function launches a goroutines that makes a failed assertion. That failed assertion is registered by Gomega and then panics. Ordinarily the panic is captured by Gomega. In the case of a goroutine Gomega can't capture the panic - so we piggy back on GinkgoRecover so users have a single defer GinkgoRecover() pattern to follow. To do that we need to tell Ginkgo to ignore this panic and not register it as a panic on the global Failer. */ type ignorablePanic interface{ GinkgoRecoverShouldIgnoreThisPanic() } /* GinkgoRecover should be deferred at the top of any spawned goroutine that (may) call `Fail` Since Gomega assertions call fail, you should throw a `defer GinkgoRecover()` at the top of any goroutine that calls out to Gomega Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent further assertions from running. This panic must be recovered. Normally, Ginkgo recovers the panic for you, however if a panic originates on a goroutine *launched* from one of your specs there's no way for Ginkgo to rescue the panic. To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine. You can learn more about how Ginkgo manages failures here: https://onsi.github.io/ginkgo/#mental-model-how-ginkgo-handles-failure */ func GinkgoRecover() { e := recover() if e != nil { if _, ok := e.(ignorablePanic); ok { return } global.Failer.Panic(types.NewCodeLocationWithStackTrace(1), e) } } // pushNode is used by the various test construction DSL methods to push nodes onto the suite // it handles returned errors, emits a detailed error message to help the user learn what they may have done wrong, then exits func pushNode(node internal.Node, errors []error) bool { exitIfErrors(errors) exitIfErr(global.Suite.PushNode(node)) return true } /* Describe nodes are Container nodes that allow you to organize your specs. A Describe node's closure can contain any number of Setup nodes (e.g. BeforeEach, AfterEach, JustBeforeEach), and Subject nodes (i.e. It). Context and When nodes are aliases for Describe - use whichever gives your suite a better narrative flow. It is idomatic to Describe the behavior of an object or function and, within that Describe, outline a number of Contexts and Whens. You can learn more at https://onsi.github.io/ginkgo/#organizing-specs-with-container-nodes In addition, container nodes can be decorated with a variety of decorators. You can learn more here: https://onsi.github.io/ginkgo/#decorator-reference */ func Describe(text string, args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...)) } /* FDescribe focuses specs within the Describe block. */ func FDescribe(text string, args ...any) bool { args = append(args, internal.Focus) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...)) } /* PDescribe marks specs within the Describe block as pending. */ func PDescribe(text string, args ...any) bool { args = append(args, internal.Pending) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, text, args...)) } /* XDescribe marks specs within the Describe block as pending. XDescribe is an alias for PDescribe */ var XDescribe = PDescribe /* Context is an alias for Describe - it generates the exact same kind of Container node */ var Context, FContext, PContext, XContext = Describe, FDescribe, PDescribe, XDescribe /* When is an alias for Describe - it generates the exact same kind of Container node */ func When(text string, args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...)) } /* When is an alias for Describe - it generates the exact same kind of Container node */ func FWhen(text string, args ...any) bool { args = append(args, internal.Focus) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...)) } /* When is an alias for Describe - it generates the exact same kind of Container node */ func PWhen(text string, args ...any) bool { args = append(args, internal.Pending) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, "when "+text, args...)) } var XWhen = PWhen /* It nodes are Subject nodes that contain your spec code and assertions. Each It node corresponds to an individual Ginkgo spec. You cannot nest any other Ginkgo nodes within an It node's closure. You can pass It nodes bare functions (func() {}) or functions that receive a SpecContext or context.Context: func(ctx SpecContext) {} and func (ctx context.Context) {}. If the function takes a context then the It is deemed interruptible and Ginkgo will cancel the context in the event of a timeout (configured via the SpecTimeout() or NodeTimeout() decorators) or of an interrupt signal. You can learn more at https://onsi.github.io/ginkgo/#spec-subjects-it In addition, subject nodes can be decorated with a variety of decorators. You can learn more here: https://onsi.github.io/ginkgo/#decorator-reference */ func It(text string, args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...)) } /* FIt allows you to focus an individual It. */ func FIt(text string, args ...any) bool { args = append(args, internal.Focus) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...)) } /* PIt allows you to mark an individual It as pending. */ func PIt(text string, args ...any) bool { args = append(args, internal.Pending) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeIt, text, args...)) } /* XIt allows you to mark an individual It as pending. XIt is an alias for PIt */ var XIt = PIt /* Specify is an alias for It - it can allow for more natural wording in some context. */ var Specify, FSpecify, PSpecify, XSpecify = It, FIt, PIt, XIt /* By allows you to better document complex Specs. Generally you should try to keep your Its short and to the point. This is not always possible, however, especially in the context of integration tests that capture complex or lengthy workflows. By allows you to document such flows. By may be called within a Setup or Subject node (It, BeforeEach, etc...) and will simply log the passed in text to the GinkgoWriter. If By is handed a function it will immediately run the function. By will also generate and attach a ReportEntry to the spec. This will ensure that By annotations appear in Ginkgo's machine-readable reports. Note that By does not generate a new Ginkgo node - rather it is simply syntactic sugar around GinkgoWriter and AddReportEntry You can learn more about By here: https://onsi.github.io/ginkgo/#documenting-complex-specs-by */ func By(text string, callback ...func()) { exitIfErr(global.Suite.By(text, callback...)) } /* BeforeSuite nodes are suite-level Setup nodes that run just once before any specs are run. When running in parallel, each parallel process will call BeforeSuite. You may only register *one* BeforeSuite handler per test suite. You typically do so in your bootstrap file at the top level. BeforeSuite can take a func() body, or an interruptible func(SpecContext)/func(context.Context) body. You cannot nest any other Ginkgo nodes within a BeforeSuite node's closure. You can learn more here: https://onsi.github.io/ginkgo/#suite-setup-and-cleanup-beforesuite-and-aftersuite */ func BeforeSuite(body any, args ...any) bool { combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeBeforeSuite, "", combinedArgs...)) } /* AfterSuite nodes are suite-level Setup nodes run after all specs have finished - regardless of whether specs have passed or failed. AfterSuite node closures always run, even if Ginkgo receives an interrupt signal (^C), in order to ensure cleanup occurs. When running in parallel, each parallel process will call AfterSuite. You may only register *one* AfterSuite handler per test suite. You typically do so in your bootstrap file at the top level. AfterSuite can take a func() body, or an interruptible func(SpecContext)/func(context.Context) body. You cannot nest any other Ginkgo nodes within an AfterSuite node's closure. You can learn more here: https://onsi.github.io/ginkgo/#suite-setup-and-cleanup-beforesuite-and-aftersuite */ func AfterSuite(body any, args ...any) bool { combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeAfterSuite, "", combinedArgs...)) } /* SynchronizedBeforeSuite nodes allow you to perform some of the suite setup just once - on parallel process #1 - and then pass information from that setup to the rest of the suite setup on all processes. This is useful for performing expensive or singleton setup once, then passing information from that setup to all parallel processes. SynchronizedBeforeSuite accomplishes this by taking *two* function arguments and passing data between them. The first function is only run on parallel process #1. The second is run on all processes, but *only* after the first function completes successfully. The functions have the following signatures: The first function (which only runs on process #1) can have any of the following the signatures: func() func(ctx context.Context) func(ctx SpecContext) func() []byte func(ctx context.Context) []byte func(ctx SpecContext) []byte The byte array returned by the first function (if present) is then passed to the second function, which can have any of the following signature: func() func(ctx context.Context) func(ctx SpecContext) func(data []byte) func(ctx context.Context, data []byte) func(ctx SpecContext, data []byte) If either function receives a context.Context/SpecContext it is considered interruptible. You cannot nest any other Ginkgo nodes within an SynchronizedBeforeSuite node's closure. You can learn more, and see some examples, here: https://onsi.github.io/ginkgo/#parallel-suite-setup-and-cleanup-synchronizedbeforesuite-and-synchronizedaftersuite */ func SynchronizedBeforeSuite(process1Body any, allProcessBody any, args ...any) bool { combinedArgs := []any{process1Body, allProcessBody} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeSynchronizedBeforeSuite, "", combinedArgs...)) } /* SynchronizedAfterSuite nodes complement the SynchronizedBeforeSuite nodes in solving the problem of splitting clean up into a piece that runs on all processes and a piece that must only run once - on process #1. SynchronizedAfterSuite accomplishes this by taking *two* function arguments. The first runs on all processes. The second runs only on parallel process #1 and *only* after all other processes have finished and exited. This ensures that process #1, and any resources it is managing, remain alive until all other processes are finished. These two functions can be bare functions (func()) or interruptible (func(context.Context)/func(SpecContext)) Note that you can also use DeferCleanup() in SynchronizedBeforeSuite to accomplish similar results. You cannot nest any other Ginkgo nodes within an SynchronizedAfterSuite node's closure. You can learn more, and see some examples, here: https://onsi.github.io/ginkgo/#parallel-suite-setup-and-cleanup-synchronizedbeforesuite-and-synchronizedaftersuite */ func SynchronizedAfterSuite(allProcessBody any, process1Body any, args ...any) bool { combinedArgs := []any{allProcessBody, process1Body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeSynchronizedAfterSuite, "", combinedArgs...)) } /* BeforeEach nodes are Setup nodes whose closures run before It node closures. When multiple BeforeEach nodes are defined in nested Container nodes the outermost BeforeEach node closures are run first. BeforeEach can take a func() body, or an interruptible func(SpecContext)/func(context.Context) body. You cannot nest any other Ginkgo nodes within a BeforeEach node's closure. You can learn more here: https://onsi.github.io/ginkgo/#extracting-common-setup-beforeeach */ func BeforeEach(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeBeforeEach, "", args...)) } /* JustBeforeEach nodes are similar to BeforeEach nodes, however they are guaranteed to run *after* all BeforeEach node closures - just before the It node closure. This can allow you to separate configuration from creation of resources for a spec. JustBeforeEach can take a func() body, or an interruptible func(SpecContext)/func(context.Context) body. You cannot nest any other Ginkgo nodes within a JustBeforeEach node's closure. You can learn more and see some examples here: https://onsi.github.io/ginkgo/#separating-creation-and-configuration-justbeforeeach */ func JustBeforeEach(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeJustBeforeEach, "", args...)) } /* AfterEach nodes are Setup nodes whose closures run after It node closures. When multiple AfterEach nodes are defined in nested Container nodes the innermost AfterEach node closures are run first. Note that you can also use DeferCleanup() in other Setup or Subject nodes to accomplish similar results. AfterEach can take a func() body, or an interruptible func(SpecContext)/func(context.Context) body. You cannot nest any other Ginkgo nodes within an AfterEach node's closure. You can learn more here: https://onsi.github.io/ginkgo/#spec-cleanup-aftereach-and-defercleanup */ func AfterEach(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeAfterEach, "", args...)) } /* JustAfterEach nodes are similar to AfterEach nodes, however they are guaranteed to run *before* all AfterEach node closures - just after the It node closure. This can allow you to separate diagnostics collection from teardown for a spec. JustAfterEach can take a func() body, or an interruptible func(SpecContext)/func(context.Context) body. You cannot nest any other Ginkgo nodes within a JustAfterEach node's closure. You can learn more and see some examples here: https://onsi.github.io/ginkgo/#separating-diagnostics-collection-and-teardown-justaftereach */ func JustAfterEach(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeJustAfterEach, "", args...)) } /* BeforeAll nodes are Setup nodes that can occur inside Ordered containers. They run just once before any specs in the Ordered container run. Multiple BeforeAll nodes can be defined in a given Ordered container however they cannot be nested inside any other container. BeforeAll can take a func() body, or an interruptible func(SpecContext)/func(context.Context) body. You cannot nest any other Ginkgo nodes within a BeforeAll node's closure. You can learn more about Ordered Containers at: https://onsi.github.io/ginkgo/#ordered-containers And you can learn more about BeforeAll at: https://onsi.github.io/ginkgo/#setup-in-ordered-containers-beforeall-and-afterall */ func BeforeAll(args ...any) bool { return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeBeforeAll, "", args...)) } /* AfterAll nodes are Setup nodes that can occur inside Ordered containers. They run just once after all specs in the Ordered container have run. Multiple AfterAll nodes can be defined in a given Ordered container however they cannot be nested inside any other container.
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/table_dsl.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/table_dsl.go
package ginkgo import ( "context" "fmt" "reflect" "strings" "github.com/onsi/ginkgo/v2/internal" "github.com/onsi/ginkgo/v2/types" ) /* The EntryDescription decorator allows you to pass a format string to DescribeTable() and Entry(). This format string is used to generate entry names via: fmt.Sprintf(formatString, parameters...) where parameters are the parameters passed into the entry. When passed into an Entry the EntryDescription is used to generate the name or that entry. When passed to DescribeTable, the EntryDescription is used to generate the names for any entries that have `nil` descriptions. You can learn more about generating EntryDescriptions here: https://onsi.github.io/ginkgo/#generating-entry-descriptions */ type EntryDescription string func (ed EntryDescription) render(args ...any) string { return fmt.Sprintf(string(ed), args...) } /* DescribeTable describes a table-driven spec. For example: DescribeTable("a simple table", func(x int, y int, expected bool) { Ω(x > y).Should(Equal(expected)) }, Entry("x > y", 1, 0, true), Entry("x == y", 0, 0, false), Entry("x < y", 0, 1, false), ) You can learn more about DescribeTable here: https://onsi.github.io/ginkgo/#table-specs And can explore some Table patterns here: https://onsi.github.io/ginkgo/#table-specs-patterns */ func DescribeTable(description string, args ...any) bool { GinkgoHelper() generateTable(description, false, args...) return true } /* You can focus a table with `FDescribeTable`. This is equivalent to `FDescribe`. */ func FDescribeTable(description string, args ...any) bool { GinkgoHelper() args = append(args, internal.Focus) generateTable(description, false, args...) return true } /* You can mark a table as pending with `PDescribeTable`. This is equivalent to `PDescribe`. */ func PDescribeTable(description string, args ...any) bool { GinkgoHelper() args = append(args, internal.Pending) generateTable(description, false, args...) return true } /* You can mark a table as pending with `XDescribeTable`. This is equivalent to `XDescribe`. */ var XDescribeTable = PDescribeTable /* DescribeTableSubtree describes a table-driven spec that generates a set of tests for each entry. For example: DescribeTableSubtree("a subtree table", func(url string, code int, message string) { var resp *http.Response BeforeEach(func() { var err error resp, err = http.Get(url) Expect(err).NotTo(HaveOccurred()) DeferCleanup(resp.Body.Close) }) It("should return the expected status code", func() { Expect(resp.StatusCode).To(Equal(code)) }) It("should return the expected message", func() { body, err := io.ReadAll(resp.Body) Expect(err).NotTo(HaveOccurred()) Expect(string(body)).To(Equal(message)) }) }, Entry("default response", "example.com/response", http.StatusOK, "hello world"), Entry("missing response", "example.com/missing", http.StatusNotFound, "wat?"), ) Note that you **must** place define an It inside the body function. You can learn more about DescribeTableSubtree here: https://onsi.github.io/ginkgo/#table-specs And can explore some Table patterns here: https://onsi.github.io/ginkgo/#table-specs-patterns */ func DescribeTableSubtree(description string, args ...any) bool { GinkgoHelper() generateTable(description, true, args...) return true } /* You can focus a table with `FDescribeTableSubtree`. This is equivalent to `FDescribe`. */ func FDescribeTableSubtree(description string, args ...any) bool { GinkgoHelper() args = append(args, internal.Focus) generateTable(description, true, args...) return true } /* You can mark a table as pending with `PDescribeTableSubtree`. This is equivalent to `PDescribe`. */ func PDescribeTableSubtree(description string, args ...any) bool { GinkgoHelper() args = append(args, internal.Pending) generateTable(description, true, args...) return true } /* You can mark a table as pending with `XDescribeTableSubtree`. This is equivalent to `XDescribe`. */ var XDescribeTableSubtree = PDescribeTableSubtree /* TableEntry represents an entry in a table test. You generally use the `Entry` constructor. */ type TableEntry struct { description any decorations []any parameters []any codeLocation types.CodeLocation } /* Entry constructs a TableEntry. The first argument is a description. This can be a string, a function that accepts the parameters passed to the TableEntry and returns a string, an EntryDescription format string, or nil. If nil is provided then the name of the Entry is derived using the table-level entry description. Subsequent arguments accept any Ginkgo decorators. These are filtered out and the remaining arguments are passed into the Spec function associated with the table. Each Entry ends up generating an individual Ginkgo It. The body of the it is the Table Body function with the Entry parameters passed in. If you want to generate interruptible specs simply write a Table function that accepts a SpecContext as its first argument. You can then decorate individual Entrys with the NodeTimeout and SpecTimeout decorators. You can learn more about Entry here: https://onsi.github.io/ginkgo/#table-specs */ func Entry(description any, args ...any) TableEntry { GinkgoHelper() decorations, parameters := internal.PartitionDecorations(args...) return TableEntry{description: description, decorations: decorations, parameters: parameters, codeLocation: types.NewCodeLocation(0)} } /* You can focus a particular entry with FEntry. This is equivalent to FIt. */ func FEntry(description any, args ...any) TableEntry { GinkgoHelper() decorations, parameters := internal.PartitionDecorations(args...) decorations = append(decorations, internal.Focus) return TableEntry{description: description, decorations: decorations, parameters: parameters, codeLocation: types.NewCodeLocation(0)} } /* You can mark a particular entry as pending with PEntry. This is equivalent to PIt. */ func PEntry(description any, args ...any) TableEntry { GinkgoHelper() decorations, parameters := internal.PartitionDecorations(args...) decorations = append(decorations, internal.Pending) return TableEntry{description: description, decorations: decorations, parameters: parameters, codeLocation: types.NewCodeLocation(0)} } /* You can mark a particular entry as pending with XEntry. This is equivalent to XIt. */ var XEntry = PEntry var contextType = reflect.TypeOf(new(context.Context)).Elem() var specContextType = reflect.TypeOf(new(SpecContext)).Elem() func generateTable(description string, isSubtree bool, args ...any) { GinkgoHelper() cl := types.NewCodeLocation(0) containerNodeArgs := []any{cl} entries := []TableEntry{} var internalBody any var internalBodyType reflect.Type var tableLevelEntryDescription any tableLevelEntryDescription = func(args ...any) string { out := []string{} for _, arg := range args { out = append(out, fmt.Sprint(arg)) } return "Entry: " + strings.Join(out, ", ") } if len(args) == 1 { exitIfErr(types.GinkgoErrors.MissingParametersForTableFunction(cl)) } for i, arg := range args { switch t := reflect.TypeOf(arg); { case t == nil: exitIfErr(types.GinkgoErrors.IncorrectParameterTypeForTable(i, "nil", cl)) case t == reflect.TypeOf(TableEntry{}): entries = append(entries, arg.(TableEntry)) case t == reflect.TypeOf([]TableEntry{}): entries = append(entries, arg.([]TableEntry)...) case t == reflect.TypeOf(EntryDescription("")): tableLevelEntryDescription = arg.(EntryDescription).render case t.Kind() == reflect.Func && t.NumOut() == 1 && t.Out(0) == reflect.TypeOf(""): tableLevelEntryDescription = arg case t.Kind() == reflect.Func: if internalBody != nil { exitIfErr(types.GinkgoErrors.MultipleEntryBodyFunctionsForTable(cl)) } internalBody = arg internalBodyType = reflect.TypeOf(internalBody) default: containerNodeArgs = append(containerNodeArgs, arg) } } containerNodeArgs = append(containerNodeArgs, func() { for _, entry := range entries { var err error entry := entry var description string switch t := reflect.TypeOf(entry.description); { case t == nil: err = validateParameters(tableLevelEntryDescription, entry.parameters, "Entry Description function", entry.codeLocation, false) if err == nil { description = invokeFunction(tableLevelEntryDescription, entry.parameters)[0].String() } case t == reflect.TypeOf(EntryDescription("")): description = entry.description.(EntryDescription).render(entry.parameters...) case t == reflect.TypeOf(""): description = entry.description.(string) case t.Kind() == reflect.Func && t.NumOut() == 1 && t.Out(0) == reflect.TypeOf(""): err = validateParameters(entry.description, entry.parameters, "Entry Description function", entry.codeLocation, false) if err == nil { description = invokeFunction(entry.description, entry.parameters)[0].String() } default: err = types.GinkgoErrors.InvalidEntryDescription(entry.codeLocation) } internalNodeArgs := []any{entry.codeLocation} internalNodeArgs = append(internalNodeArgs, entry.decorations...) hasContext := false if internalBodyType.NumIn() > 0 { if internalBodyType.In(0).Implements(specContextType) { hasContext = true } else if internalBodyType.In(0).Implements(contextType) { hasContext = true if len(entry.parameters) > 0 && reflect.TypeOf(entry.parameters[0]) != nil && reflect.TypeOf(entry.parameters[0]).Implements(contextType) { // we allow you to pass in a non-nil context hasContext = false } } } if err == nil { err = validateParameters(internalBody, entry.parameters, "Table Body function", entry.codeLocation, hasContext) } if hasContext { internalNodeArgs = append(internalNodeArgs, func(c SpecContext) { if err != nil { panic(err) } invokeFunction(internalBody, append([]any{c}, entry.parameters...)) }) if isSubtree { exitIfErr(types.GinkgoErrors.ContextsCannotBeUsedInSubtreeTables(cl)) } } else { internalNodeArgs = append(internalNodeArgs, func() { if err != nil { panic(err) } invokeFunction(internalBody, entry.parameters) }) } internalNodeType := types.NodeTypeIt if isSubtree { internalNodeType = types.NodeTypeContainer } pushNode(internal.NewNode(deprecationTracker, internalNodeType, description, internalNodeArgs...)) } }) pushNode(internal.NewNode(deprecationTracker, types.NodeTypeContainer, description, containerNodeArgs...)) } func invokeFunction(function any, parameters []any) []reflect.Value { inValues := make([]reflect.Value, len(parameters)) funcType := reflect.TypeOf(function) limit := funcType.NumIn() if funcType.IsVariadic() { limit = limit - 1 } for i := 0; i < limit && i < len(parameters); i++ { inValues[i] = computeValue(parameters[i], funcType.In(i)) } if funcType.IsVariadic() { variadicType := funcType.In(limit).Elem() for i := limit; i < len(parameters); i++ { inValues[i] = computeValue(parameters[i], variadicType) } } return reflect.ValueOf(function).Call(inValues) } func validateParameters(function any, parameters []any, kind string, cl types.CodeLocation, hasContext bool) error { funcType := reflect.TypeOf(function) limit := funcType.NumIn() offset := 0 if hasContext { limit = limit - 1 offset = 1 } if funcType.IsVariadic() { limit = limit - 1 } if len(parameters) < limit { return types.GinkgoErrors.TooFewParametersToTableFunction(limit, len(parameters), kind, cl) } if len(parameters) > limit && !funcType.IsVariadic() { return types.GinkgoErrors.TooManyParametersToTableFunction(limit, len(parameters), kind, cl) } var i = 0 for ; i < limit; i++ { actual := reflect.TypeOf(parameters[i]) expected := funcType.In(i + offset) if !(actual == nil) && !actual.AssignableTo(expected) { return types.GinkgoErrors.IncorrectParameterTypeToTableFunction(i+1, expected, actual, kind, cl) } } if funcType.IsVariadic() { expected := funcType.In(limit + offset).Elem() for ; i < len(parameters); i++ { actual := reflect.TypeOf(parameters[i]) if !(actual == nil) && !actual.AssignableTo(expected) { return types.GinkgoErrors.IncorrectVariadicParameterTypeToTableFunction(expected, actual, kind, cl) } } } return nil } func computeValue(parameter any, t reflect.Type) reflect.Value { if parameter == nil { return reflect.Zero(t) } else { return reflect.ValueOf(parameter) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/reporting_dsl.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/reporting_dsl.go
package ginkgo import ( "fmt" "strings" "github.com/onsi/ginkgo/v2/internal" "github.com/onsi/ginkgo/v2/internal/global" "github.com/onsi/ginkgo/v2/reporters" "github.com/onsi/ginkgo/v2/types" ) /* Report represents the report for a Suite. It is documented here: https://pkg.go.dev/github.com/onsi/ginkgo/v2/types#Report */ type Report = types.Report /* Report represents the report for a Spec. It is documented here: https://pkg.go.dev/github.com/onsi/ginkgo/v2/types#SpecReport */ type SpecReport = types.SpecReport /* CurrentSpecReport returns information about the current running spec. The returned object is a types.SpecReport which includes helper methods to make extracting information about the spec easier. You can learn more about SpecReport here: https://pkg.go.dev/github.com/onsi/ginkgo/types#SpecReport You can learn more about CurrentSpecReport() here: https://onsi.github.io/ginkgo/#getting-a-report-for-the-current-spec */ func CurrentSpecReport() SpecReport { return global.Suite.CurrentSpecReport() } /* ReportEntryVisibility governs the visibility of ReportEntries in Ginkgo's console reporter - ReportEntryVisibilityAlways: the default behavior - the ReportEntry is always emitted. - ReportEntryVisibilityFailureOrVerbose: the ReportEntry is only emitted if the spec fails or if the tests are run with -v (similar to GinkgoWriters behavior). - ReportEntryVisibilityNever: the ReportEntry is never emitted though it appears in any generated machine-readable reports (e.g. by setting `--json-report`). You can learn more about Report Entries here: https://onsi.github.io/ginkgo/#attaching-data-to-reports */ type ReportEntryVisibility = types.ReportEntryVisibility const ReportEntryVisibilityAlways, ReportEntryVisibilityFailureOrVerbose, ReportEntryVisibilityNever = types.ReportEntryVisibilityAlways, types.ReportEntryVisibilityFailureOrVerbose, types.ReportEntryVisibilityNever /* AddReportEntry generates and adds a new ReportEntry to the current spec's SpecReport. It can take any of the following arguments: - A single arbitrary object to attach as the Value of the ReportEntry. This object will be included in any generated reports and will be emitted to the console when the report is emitted. - A ReportEntryVisibility enum to control the visibility of the ReportEntry - An Offset or CodeLocation decoration to control the reported location of the ReportEntry If the Value object implements `fmt.Stringer`, it's `String()` representation is used when emitting to the console. AddReportEntry() must be called within a Subject or Setup node - not in a Container node. You can learn more about Report Entries here: https://onsi.github.io/ginkgo/#attaching-data-to-reports */ func AddReportEntry(name string, args ...any) { cl := types.NewCodeLocation(1) reportEntry, err := internal.NewReportEntry(name, cl, args...) if err != nil { Fail(fmt.Sprintf("Failed to generate Report Entry:\n%s", err.Error()), 1) } err = global.Suite.AddReportEntry(reportEntry) if err != nil { Fail(fmt.Sprintf("Failed to add Report Entry:\n%s", err.Error()), 1) } } /* ReportBeforeEach nodes are run for each spec, even if the spec is skipped or pending. ReportBeforeEach nodes take a function that receives a SpecReport or both SpecContext and Report for interruptible behavior. They are called before the spec starts. Example: ReportBeforeEach(func(report SpecReport) { // process report }) ReportBeforeEach(func(ctx SpecContext, report SpecReport) { // process report }), NodeTimeout(1 * time.Minute)) You cannot nest any other Ginkgo nodes within a ReportBeforeEach node's closure. You can learn more about ReportBeforeEach here: https://onsi.github.io/ginkgo/#generating-reports-programmatically You can learn about interruptible nodes here: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes */ func ReportBeforeEach(body any, args ...any) bool { combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeReportBeforeEach, "", combinedArgs...)) } /* ReportAfterEach nodes are run for each spec, even if the spec is skipped or pending. ReportAfterEach nodes take a function that receives a SpecReport or both SpecContext and Report for interruptible behavior. They are called after the spec has completed and receive the final report for the spec. Example: ReportAfterEach(func(report SpecReport) { // process report }) ReportAfterEach(func(ctx SpecContext, report SpecReport) { // process report }), NodeTimeout(1 * time.Minute)) You cannot nest any other Ginkgo nodes within a ReportAfterEach node's closure. You can learn more about ReportAfterEach here: https://onsi.github.io/ginkgo/#generating-reports-programmatically You can learn about interruptible nodes here: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes */ func ReportAfterEach(body any, args ...any) bool { combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeReportAfterEach, "", combinedArgs...)) } /* ReportBeforeSuite nodes are run at the beginning of the suite. ReportBeforeSuite nodes take a function that can either receive Report or both SpecContext and Report for interruptible behavior. Example Usage: ReportBeforeSuite(func(r Report) { // process report }) ReportBeforeSuite(func(ctx SpecContext, r Report) { // process report }, NodeTimeout(1 * time.Minute)) They are called at the beginning of the suite, before any specs have run and any BeforeSuite or SynchronizedBeforeSuite nodes, and are passed in the initial report for the suite. ReportBeforeSuite nodes must be created at the top-level (i.e. not nested in a Context/Describe/When node) # When running in parallel, Ginkgo ensures that only one of the parallel nodes runs the ReportBeforeSuite You cannot nest any other Ginkgo nodes within a ReportAfterSuite node's closure. You can learn more about ReportAfterSuite here: https://onsi.github.io/ginkgo/#generating-reports-programmatically You can learn more about Ginkgo's reporting infrastructure, including generating reports with the CLI here: https://onsi.github.io/ginkgo/#generating-machine-readable-reports You can learn about interruptible nodes here: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes */ func ReportBeforeSuite(body any, args ...any) bool { combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeReportBeforeSuite, "", combinedArgs...)) } /* ReportAfterSuite nodes are run at the end of the suite. ReportAfterSuite nodes execute at the suite's conclusion, and accept a function that can either receive Report or both SpecContext and Report for interruptible behavior. Example Usage: ReportAfterSuite("Non-interruptible ReportAfterSuite", func(r Report) { // process report }) ReportAfterSuite("Interruptible ReportAfterSuite", func(ctx SpecContext, r Report) { // process report }, NodeTimeout(1 * time.Minute)) They are called at the end of the suite, after all specs have run and any AfterSuite or SynchronizedAfterSuite nodes, and are passed in the final report for the suite. ReportAfterSuite nodes must be created at the top-level (i.e. not nested in a Context/Describe/When node) When running in parallel, Ginkgo ensures that only one of the parallel nodes runs the ReportAfterSuite and that it is passed a report that is aggregated across all parallel nodes In addition to using ReportAfterSuite to programmatically generate suite reports, you can also generate JSON, JUnit, and Teamcity formatted reports using the --json-report, --junit-report, and --teamcity-report ginkgo CLI flags. You cannot nest any other Ginkgo nodes within a ReportAfterSuite node's closure. You can learn more about ReportAfterSuite here: https://onsi.github.io/ginkgo/#generating-reports-programmatically You can learn more about Ginkgo's reporting infrastructure, including generating reports with the CLI here: https://onsi.github.io/ginkgo/#generating-machine-readable-reports You can learn about interruptible nodes here: https://onsi.github.io/ginkgo/#spec-timeouts-and-interruptible-nodes */ func ReportAfterSuite(text string, body any, args ...any) bool { combinedArgs := []any{body} combinedArgs = append(combinedArgs, args...) return pushNode(internal.NewNode(deprecationTracker, types.NodeTypeReportAfterSuite, text, combinedArgs...)) } func registerReportAfterSuiteNodeForAutogeneratedReports(reporterConfig types.ReporterConfig) { body := func(report Report) { if reporterConfig.JSONReport != "" { err := reporters.GenerateJSONReport(report, reporterConfig.JSONReport) if err != nil { Fail(fmt.Sprintf("Failed to generate JSON report:\n%s", err.Error())) } } if reporterConfig.JUnitReport != "" { err := reporters.GenerateJUnitReport(report, reporterConfig.JUnitReport) if err != nil { Fail(fmt.Sprintf("Failed to generate JUnit report:\n%s", err.Error())) } } if reporterConfig.TeamcityReport != "" { err := reporters.GenerateTeamcityReport(report, reporterConfig.TeamcityReport) if err != nil { Fail(fmt.Sprintf("Failed to generate Teamcity report:\n%s", err.Error())) } } } flags := []string{} if reporterConfig.JSONReport != "" { flags = append(flags, "--json-report") } if reporterConfig.JUnitReport != "" { flags = append(flags, "--junit-report") } if reporterConfig.TeamcityReport != "" { flags = append(flags, "--teamcity-report") } pushNode(internal.NewNode( deprecationTracker, types.NodeTypeReportAfterSuite, fmt.Sprintf("Autogenerated ReportAfterSuite for %s", strings.Join(flags, " ")), body, types.NewCustomCodeLocation("autogenerated by Ginkgo"), )) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/ginkgo_cli_dependencies.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/ginkgo_cli_dependencies.go
//go:build ginkgoclidependencies // +build ginkgoclidependencies package ginkgo import ( _ "github.com/onsi/ginkgo/v2/ginkgo" )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/formatter/colorable_windows.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/onsi/ginkgo/v2/formatter/colorable_windows.go
/* These packages are used for colorize on Windows and contributed by mattn.jp@gmail.com * go-colorable: <https://github.com/mattn/go-colorable> * go-isatty: <https://github.com/mattn/go-isatty> The MIT License (MIT) Copyright (c) 2016 Yasuhiro Matsumoto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package formatter import ( "bytes" "fmt" "io" "math" "os" "strconv" "strings" "syscall" "unsafe" ) var ( kernel32 = syscall.NewLazyDLL("kernel32.dll") procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") procGetConsoleMode = kernel32.NewProc("GetConsoleMode") ) func isTerminal(fd uintptr) bool { var st uint32 r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) return r != 0 && e == 0 } const ( foregroundBlue = 0x1 foregroundGreen = 0x2 foregroundRed = 0x4 foregroundIntensity = 0x8 foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) backgroundBlue = 0x10 backgroundGreen = 0x20 backgroundRed = 0x40 backgroundIntensity = 0x80 backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) ) type wchar uint16 type short int16 type dword uint32 type word uint16 type coord struct { x short y short } type smallRect struct { left short top short right short bottom short } type consoleScreenBufferInfo struct { size coord cursorPosition coord attributes word window smallRect maximumWindowSize coord } type writer struct { out io.Writer handle syscall.Handle lastbuf bytes.Buffer oldattr word } func newColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") } if isTerminal(file.Fd()) { var csbi consoleScreenBufferInfo handle := syscall.Handle(file.Fd()) procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) return &writer{out: file, handle: handle, oldattr: csbi.attributes} } else { return file } } var color256 = map[int]int{ 0: 0x000000, 1: 0x800000, 2: 0x008000, 3: 0x808000, 4: 0x000080, 5: 0x800080, 6: 0x008080, 7: 0xc0c0c0, 8: 0x808080, 9: 0xff0000, 10: 0x00ff00, 11: 0xffff00, 12: 0x0000ff, 13: 0xff00ff, 14: 0x00ffff, 15: 0xffffff, 16: 0x000000, 17: 0x00005f, 18: 0x000087, 19: 0x0000af, 20: 0x0000d7, 21: 0x0000ff, 22: 0x005f00, 23: 0x005f5f, 24: 0x005f87, 25: 0x005faf, 26: 0x005fd7, 27: 0x005fff, 28: 0x008700, 29: 0x00875f, 30: 0x008787, 31: 0x0087af, 32: 0x0087d7, 33: 0x0087ff, 34: 0x00af00, 35: 0x00af5f, 36: 0x00af87, 37: 0x00afaf, 38: 0x00afd7, 39: 0x00afff, 40: 0x00d700, 41: 0x00d75f, 42: 0x00d787, 43: 0x00d7af, 44: 0x00d7d7, 45: 0x00d7ff, 46: 0x00ff00, 47: 0x00ff5f, 48: 0x00ff87, 49: 0x00ffaf, 50: 0x00ffd7, 51: 0x00ffff, 52: 0x5f0000, 53: 0x5f005f, 54: 0x5f0087, 55: 0x5f00af, 56: 0x5f00d7, 57: 0x5f00ff, 58: 0x5f5f00, 59: 0x5f5f5f, 60: 0x5f5f87, 61: 0x5f5faf, 62: 0x5f5fd7, 63: 0x5f5fff, 64: 0x5f8700, 65: 0x5f875f, 66: 0x5f8787, 67: 0x5f87af, 68: 0x5f87d7, 69: 0x5f87ff, 70: 0x5faf00, 71: 0x5faf5f, 72: 0x5faf87, 73: 0x5fafaf, 74: 0x5fafd7, 75: 0x5fafff, 76: 0x5fd700, 77: 0x5fd75f, 78: 0x5fd787, 79: 0x5fd7af, 80: 0x5fd7d7, 81: 0x5fd7ff, 82: 0x5fff00, 83: 0x5fff5f, 84: 0x5fff87, 85: 0x5fffaf, 86: 0x5fffd7, 87: 0x5fffff, 88: 0x870000, 89: 0x87005f, 90: 0x870087, 91: 0x8700af, 92: 0x8700d7, 93: 0x8700ff, 94: 0x875f00, 95: 0x875f5f, 96: 0x875f87, 97: 0x875faf, 98: 0x875fd7, 99: 0x875fff, 100: 0x878700, 101: 0x87875f, 102: 0x878787, 103: 0x8787af, 104: 0x8787d7, 105: 0x8787ff, 106: 0x87af00, 107: 0x87af5f, 108: 0x87af87, 109: 0x87afaf, 110: 0x87afd7, 111: 0x87afff, 112: 0x87d700, 113: 0x87d75f, 114: 0x87d787, 115: 0x87d7af, 116: 0x87d7d7, 117: 0x87d7ff, 118: 0x87ff00, 119: 0x87ff5f, 120: 0x87ff87, 121: 0x87ffaf, 122: 0x87ffd7, 123: 0x87ffff, 124: 0xaf0000, 125: 0xaf005f, 126: 0xaf0087, 127: 0xaf00af, 128: 0xaf00d7, 129: 0xaf00ff, 130: 0xaf5f00, 131: 0xaf5f5f, 132: 0xaf5f87, 133: 0xaf5faf, 134: 0xaf5fd7, 135: 0xaf5fff, 136: 0xaf8700, 137: 0xaf875f, 138: 0xaf8787, 139: 0xaf87af, 140: 0xaf87d7, 141: 0xaf87ff, 142: 0xafaf00, 143: 0xafaf5f, 144: 0xafaf87, 145: 0xafafaf, 146: 0xafafd7, 147: 0xafafff, 148: 0xafd700, 149: 0xafd75f, 150: 0xafd787, 151: 0xafd7af, 152: 0xafd7d7, 153: 0xafd7ff, 154: 0xafff00, 155: 0xafff5f, 156: 0xafff87, 157: 0xafffaf, 158: 0xafffd7, 159: 0xafffff, 160: 0xd70000, 161: 0xd7005f, 162: 0xd70087, 163: 0xd700af, 164: 0xd700d7, 165: 0xd700ff, 166: 0xd75f00, 167: 0xd75f5f, 168: 0xd75f87, 169: 0xd75faf, 170: 0xd75fd7, 171: 0xd75fff, 172: 0xd78700, 173: 0xd7875f, 174: 0xd78787, 175: 0xd787af, 176: 0xd787d7, 177: 0xd787ff, 178: 0xd7af00, 179: 0xd7af5f, 180: 0xd7af87, 181: 0xd7afaf, 182: 0xd7afd7, 183: 0xd7afff, 184: 0xd7d700, 185: 0xd7d75f, 186: 0xd7d787, 187: 0xd7d7af, 188: 0xd7d7d7, 189: 0xd7d7ff, 190: 0xd7ff00, 191: 0xd7ff5f, 192: 0xd7ff87, 193: 0xd7ffaf, 194: 0xd7ffd7, 195: 0xd7ffff, 196: 0xff0000, 197: 0xff005f, 198: 0xff0087, 199: 0xff00af, 200: 0xff00d7, 201: 0xff00ff, 202: 0xff5f00, 203: 0xff5f5f, 204: 0xff5f87, 205: 0xff5faf, 206: 0xff5fd7, 207: 0xff5fff, 208: 0xff8700, 209: 0xff875f, 210: 0xff8787, 211: 0xff87af, 212: 0xff87d7, 213: 0xff87ff, 214: 0xffaf00, 215: 0xffaf5f, 216: 0xffaf87, 217: 0xffafaf, 218: 0xffafd7, 219: 0xffafff, 220: 0xffd700, 221: 0xffd75f, 222: 0xffd787, 223: 0xffd7af, 224: 0xffd7d7, 225: 0xffd7ff, 226: 0xffff00, 227: 0xffff5f, 228: 0xffff87, 229: 0xffffaf, 230: 0xffffd7, 231: 0xffffff, 232: 0x080808, 233: 0x121212, 234: 0x1c1c1c, 235: 0x262626, 236: 0x303030, 237: 0x3a3a3a, 238: 0x444444, 239: 0x4e4e4e, 240: 0x585858, 241: 0x626262, 242: 0x6c6c6c, 243: 0x767676, 244: 0x808080, 245: 0x8a8a8a, 246: 0x949494, 247: 0x9e9e9e, 248: 0xa8a8a8, 249: 0xb2b2b2, 250: 0xbcbcbc, 251: 0xc6c6c6, 252: 0xd0d0d0, 253: 0xdadada, 254: 0xe4e4e4, 255: 0xeeeeee, } func (w *writer) Write(data []byte) (n int, err error) { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) er := bytes.NewBuffer(data) loop: for { r1, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) if r1 == 0 { break loop } c1, _, err := er.ReadRune() if err != nil { break loop } if c1 != 0x1b { fmt.Fprint(w.out, string(c1)) continue } c2, _, err := er.ReadRune() if err != nil { w.lastbuf.WriteRune(c1) break loop } if c2 != 0x5b { w.lastbuf.WriteRune(c1) w.lastbuf.WriteRune(c2) continue } var buf bytes.Buffer var m rune for { c, _, err := er.ReadRune() if err != nil { w.lastbuf.WriteRune(c1) w.lastbuf.WriteRune(c2) w.lastbuf.Write(buf.Bytes()) break loop } if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { m = c break } buf.Write([]byte(string(c))) } var csbi consoleScreenBufferInfo switch m { case 'A': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y -= short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'B': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y += short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'C': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x -= short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'D': n, err = strconv.Atoi(buf.String()) if err != nil { continue } if n, err = strconv.Atoi(buf.String()); err == nil { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x += short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) } case 'E': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y += short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'F': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y -= short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'G': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'H': token := strings.Split(buf.String(), ";") if len(token) != 2 { continue } n1, err := strconv.Atoi(token[0]) if err != nil { continue } n2, err := strconv.Atoi(token[1]) if err != nil { continue } csbi.cursorPosition.x = short(n2) csbi.cursorPosition.x = short(n1) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'J': n, err := strconv.Atoi(buf.String()) if err != nil { continue } var cursor coord switch n { case 0: cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} case 1: cursor = coord{x: csbi.window.left, y: csbi.window.top} case 2: cursor = coord{x: csbi.window.left, y: csbi.window.top} } var count, written dword count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'K': n, err := strconv.Atoi(buf.String()) if err != nil { continue } var cursor coord switch n { case 0: cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} case 1: cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} case 2: cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} } var count, written dword count = dword(csbi.size.x - csbi.cursorPosition.x) procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'm': attr := csbi.attributes cs := buf.String() if cs == "" { procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) continue } token := strings.Split(cs, ";") for i := 0; i < len(token); i += 1 { ns := token[i] if n, err = strconv.Atoi(ns); err == nil { switch { case n == 0 || n == 100: attr = w.oldattr case 1 <= n && n <= 5: attr |= foregroundIntensity case n == 7: attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) case 22 == n || n == 25 || n == 25: attr |= foregroundIntensity case n == 27: attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) case 30 <= n && n <= 37: attr = (attr & backgroundMask) if (n-30)&1 != 0 { attr |= foregroundRed } if (n-30)&2 != 0 { attr |= foregroundGreen } if (n-30)&4 != 0 { attr |= foregroundBlue } case n == 38: // set foreground color. if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { if n256, err := strconv.Atoi(token[i+2]); err == nil { if n256foreAttr == nil { n256setup() } attr &= backgroundMask attr |= n256foreAttr[n256] i += 2 } } else { attr = attr & (w.oldattr & backgroundMask) } case n == 39: // reset foreground color. attr &= backgroundMask attr |= w.oldattr & foregroundMask case 40 <= n && n <= 47: attr = (attr & foregroundMask) if (n-40)&1 != 0 { attr |= backgroundRed } if (n-40)&2 != 0 { attr |= backgroundGreen } if (n-40)&4 != 0 { attr |= backgroundBlue } case n == 48: // set background color. if i < len(token)-2 && token[i+1] == "5" { if n256, err := strconv.Atoi(token[i+2]); err == nil { if n256backAttr == nil { n256setup() } attr &= foregroundMask attr |= n256backAttr[n256] i += 2 } } else { attr = attr & (w.oldattr & foregroundMask) } case n == 49: // reset foreground color. attr &= foregroundMask attr |= w.oldattr & backgroundMask case 90 <= n && n <= 97: attr = (attr & backgroundMask) attr |= foregroundIntensity if (n-90)&1 != 0 { attr |= foregroundRed } if (n-90)&2 != 0 { attr |= foregroundGreen } if (n-90)&4 != 0 { attr |= foregroundBlue } case 100 <= n && n <= 107: attr = (attr & foregroundMask) attr |= backgroundIntensity if (n-100)&1 != 0 { attr |= backgroundRed } if (n-100)&2 != 0 { attr |= backgroundGreen } if (n-100)&4 != 0 { attr |= backgroundBlue } } procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) } } } } return len(data) - w.lastbuf.Len(), nil } type consoleColor struct { rgb int red bool green bool blue bool intensity bool } func (c consoleColor) foregroundAttr() (attr word) { if c.red { attr |= foregroundRed } if c.green { attr |= foregroundGreen } if c.blue { attr |= foregroundBlue } if c.intensity { attr |= foregroundIntensity } return } func (c consoleColor) backgroundAttr() (attr word) { if c.red { attr |= backgroundRed } if c.green { attr |= backgroundGreen } if c.blue { attr |= backgroundBlue } if c.intensity { attr |= backgroundIntensity } return } var color16 = []consoleColor{ consoleColor{0x000000, false, false, false, false}, consoleColor{0x000080, false, false, true, false}, consoleColor{0x008000, false, true, false, false}, consoleColor{0x008080, false, true, true, false}, consoleColor{0x800000, true, false, false, false}, consoleColor{0x800080, true, false, true, false}, consoleColor{0x808000, true, true, false, false}, consoleColor{0xc0c0c0, true, true, true, false}, consoleColor{0x808080, false, false, false, true}, consoleColor{0x0000ff, false, false, true, true}, consoleColor{0x00ff00, false, true, false, true}, consoleColor{0x00ffff, false, true, true, true}, consoleColor{0xff0000, true, false, false, true}, consoleColor{0xff00ff, true, false, true, true}, consoleColor{0xffff00, true, true, false, true}, consoleColor{0xffffff, true, true, true, true}, } type hsv struct { h, s, v float32 } func (a hsv) dist(b hsv) float32 { dh := a.h - b.h switch { case dh > 0.5: dh = 1 - dh case dh < -0.5: dh = -1 - dh } ds := a.s - b.s dv := a.v - b.v return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) } func toHSV(rgb int) hsv { r, g, b := float32((rgb&0xFF0000)>>16)/256.0, float32((rgb&0x00FF00)>>8)/256.0, float32(rgb&0x0000FF)/256.0 min, max := minmax3f(r, g, b) h := max - min if h > 0 { if max == r { h = (g - b) / h if h < 0 { h += 6 } } else if max == g { h = 2 + (b-r)/h } else { h = 4 + (r-g)/h } } h /= 6.0 s := max - min if max != 0 { s /= max } v := max return hsv{h: h, s: s, v: v} } type hsvTable []hsv func toHSVTable(rgbTable []consoleColor) hsvTable { t := make(hsvTable, len(rgbTable)) for i, c := range rgbTable { t[i] = toHSV(c.rgb) } return t } func (t hsvTable) find(rgb int) consoleColor { hsv := toHSV(rgb) n := 7 l := float32(5.0) for i, p := range t { d := hsv.dist(p) if d < l { l, n = d, i } } return color16[n] } func minmax3f(a, b, c float32) (min, max float32) { if a < b { if b < c { return a, c } else if a < c { return a, b } else { return c, b } } else { if a < c { return b, c } else if b < c { return b, a } else { return c, a } } } var n256foreAttr []word var n256backAttr []word func n256setup() { n256foreAttr = make([]word, 256) n256backAttr = make([]word, 256) t := toHSVTable(color16) for i, rgb := range color256 { c := t.find(rgb) n256foreAttr[i] = c.foregroundAttr() n256backAttr[i] = c.backgroundAttr() } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false