Documentation
¶
Overview ¶
Package utils provides utility functions for the Keploy application.
Index ¶
- Variables
- func AddToGitIgnore(logger *zap.Logger, path string, ignoreString string) error
- func AreSudoCredentialsCached() bool
- func AskForConfirmation(ctx context.Context, s string) (bool, error)
- func BindFlagsToViper(logger *zap.Logger, cmd *cobra.Command, viperKeyPrefix string) error
- func CacheSudoCredentials(ctx context.Context, logger *zap.Logger) error
- func CheckFileExists(path string) bool
- func CheckRequiredPermissions() error
- func CommandContext(ctx context.Context, cmdStr string) (*exec.Cmd, error)
- func ContainerNameFromDockerRun(cmd string) string
- func DeleteFileIfExists(logger *zap.Logger, name string) (err error)
- func DetectLanguage(logger *zap.Logger, cmd string) (models.Language, string)
- func DrainErrGroup(logger *zap.Logger, name string, g *errgroup.Group, timeout time.Duration) error
- func EnsureAvailablePorts(port uint32) (uint32, error)
- func EnsureKeployFolderPermissions(ctx context.Context, logger *zap.Logger, keployPath string) error
- func EnsureRmBeforeName(cmd string) string
- func ExecCancel()
- func ExpandPath(path string) (string, error)
- func ExtractCmdTypeFromArgs(args []string) string
- func ExtractCommandFromArgs(args []string) string
- func FileExists(path string) (bool, error)
- func FixFilePermission(ctx context.Context, logger *zap.Logger, filePath string) error
- func FixKeployFolderPermissions(ctx context.Context, logger *zap.Logger, keployPath string, ...) error
- func GenerateGithubActions(logger *zap.Logger, appCmd string)
- func GetAbsPath(path string) (string, error)
- func GetAvailablePort() (uint32, error)
- func GetContainerIPv4() (string, error)
- func GetCurrentBinaryPath() (string, error)
- func GetFullCommandUsed() string
- func GetLastDirectory() (string, error)
- func GetPermissionFixCommand(keployPath string) string
- func GetProtoMessageDescriptor(ctx context.Context, logger *zap.Logger, pc models.ProtoConfig) (protoreflect.MessageDescriptor, []protoreflect.FileDescriptor, error)
- func GetReqMeta(req *http.Request) map[string]string
- func GetVersionAsComment() string
- func HandleRecovery(logger *zap.Logger, r interface{}, errMsg string)
- func Hash(data []byte) string
- func InterruptProcessTree(logger *zap.Logger, ppid int, sig syscall.Signal) error
- func IsDockerCmd(kind CmdType) bool
- func IsFileEmpty(filePath string) (bool, error)
- func IsPassThrough(logger *zap.Logger, req *http.Request, destPort uint, ...) bool
- func IsShutdownError(err error) bool
- func IsXMLResponse(resp *models.HTTPResp) bool
- func Keys(m map[string][]string) []string
- func LogError(logger *zap.Logger, err error, msg string, fields ...zap.Field)
- func NetworkToHostShort(net uint16) uint16
- func NewCtx() context.Context
- func ParseGRPCPath(p string) (serviceFull, method string, err error)
- func ParseMetadata(metadataStr string) (map[string]interface{}, error)
- func ProtoTextToJSON(md protoreflect.MessageDescriptor, files []protoreflect.FileDescriptor, ...) ([]byte, bool)
- func ProtoTextToWire(text string) ([]byte, error)
- func ProtoWireToJSON(md protoreflect.MessageDescriptor, files []protoreflect.FileDescriptor, ...) ([]byte, error)
- func Recover(logger *zap.Logger)
- func ReexecWithSudo(logger *zap.Logger)
- func RegisterPreCancelHook(fn func())
- func RemoveDoubleQuotes(tempMap map[string]interface{})
- func RenderTemplatesInString(logger *zap.Logger, input string, templateData map[string]interface{}) (string, error)
- func ReplaceBaseURL(currentURL string, baseURL string) (string, error)
- func ReplaceGrpcHost(authority string, ipAddress string) (string, error)
- func ReplaceGrpcPort(authority string, port string) (string, error)
- func ReplaceHost(currentURL string, ipAddress string) (string, error)
- func ReplacePort(currentURL string, port string) (string, error)
- func RestoreKeployFolderOwnership(logger *zap.Logger, keployPath string)
- func RestoreUmask(oldMask int)
- func SendSignal(logger *zap.Logger, pid int, sig syscall.Signal) error
- func SentryInit(logger *zap.Logger, dsn string)
- func SetCancel(c context.CancelFunc)
- func SetCoveragePath(logger *zap.Logger, goCovPath string) (string, error)
- func SetUmask() int
- func ShouldReexecWithSudo() bool
- func Stop(logger *zap.Logger, reason string) error
- func ToAbsPath(logger *zap.Logger, originalPath string) string
- func ToFloat(value interface{}) float64
- func ToInt(value interface{}) int
- func ToString(val interface{}) string
- func TrimSpaces(input string) string
- type AutoInc
- type CmdError
- type CmdType
- type ErrType
- type GitHubRelease
- type JSONWriter
- type PermissionError
Constants ¶
This section is empty.
Variables ¶
var ConfigGuide = `
# Visit [https://keploy.io/docs/running-keploy/configuration-file/] to learn about using keploy through configration file.
`
var Emoji = "\U0001F430" + " Keploy:"
var ErrCode = 0
var ErrGitHubAPIUnresponsive = errors.New("GitHub API is unresponsive")
var LogFile *os.File
var SecretValues = map[string]interface{}{}
var TemplatizedValues = map[string]interface{}{}
var Version string
var VersionIdentifier string
var WarningSign = "\U000026A0"
Functions ¶
func AddToGitIgnore ¶
AddToGitIgnore adds an entry to the .gitignore file if it doesn't already exist.
func AreSudoCredentialsCached ¶ added in v3.3.9
func AreSudoCredentialsCached() bool
AreSudoCredentialsCached checks if sudo credentials are currently cached. Returns true if already root or if sudo -n -v succeeds (credentials cached).
func AskForConfirmation ¶
AskForConfirmation asks the user for confirmation. A user must type in "yes" or "no" and then press enter. It has fuzzy matching, so "y", "Y", "yes", "YES", and "Yes" all count as confirmations. If the input is not recognized or interrupted, exit gracefully as "no".
func BindFlagsToViper ¶
func CacheSudoCredentials ¶ added in v3.3.9
CacheSudoCredentials prompts for sudo password and caches the credentials. This uses sudo -v which validates and caches credentials without running a command. The cached credentials will be used by subsequent sudo calls (including the agent). If already root or credentials are already cached, this is a no-op.
func CheckFileExists ¶
func CheckRequiredPermissions ¶ added in v3.3.29
func CheckRequiredPermissions() error
CheckRequiredPermissions verifies if the current process has the specific capabilities required for Keploy to function correctly in Docker mode. On non-Linux systems, this check remains a no-op as capabilities are Linux-specific.
func CommandContext ¶ added in v3.5.90
CommandContext builds an *exec.Cmd that runs cmdStr on Unix-like systems.
When sh is on PATH (the normal case — local dev, standard CI, any image with a shell) it returns `sh -c <cmdStr>`, identical to the previous exec.Command("sh", "-c", cmdStr). LookPath is used only to probe for sh; the bare "sh" name is kept so cmd.Args is byte-for-byte the previous behaviour.
When no shell is present — e.g. a distroless runtime image that ships only the application's own binaries — it falls back to tokenizing cmdStr and exec'ing the binary directly, which needs no shell. That fallback cannot run commands that rely on shell control operators (see shellOperators), so it returns an explanatory error for those instead of mis-executing an operator as a literal argument.
The fallback only ever runs when sh is genuinely missing, so it cannot change the behaviour of any environment that works today: it can only turn the current hard "sh: executable file not found" failure into a working direct exec for shell-free commands (e.g. `docker compose -f - up ...`).
func ContainerNameFromDockerRun ¶ added in v3.5.75
ContainerNameFromDockerRun extracts the value of the --name flag from a `docker run` command, supporting both "--name foo" and "--name=foo". It returns "" when no --name is present. Used to free a leftover container name before a re-run when the --container-name flag wasn't supplied.
func DeleteFileIfExists ¶ added in v3.6.21
func DetectLanguage ¶
DetectLanguage detects the language of the test command and returns the executable
func DrainErrGroup ¶ added in v3.5.67
DrainErrGroup waits for g.Wait() to return, but gives up after `timeout`.
Why this exists: keploy's record/replay teardown runs in a deferred function that is also the path SIGINT/SIGTERM takes (the signal cancels the root context, which triggers the defer). The teardown calls g.Wait() to drain the run/setup goroutines after cancel(). If any one of those goroutines does not observe context cancellation — e.g. an agent-in-docker bring-up or proxy setup that wedges while the host is under heavy CPU/IO contention — an unbounded g.Wait() blocks the teardown forever. Because that same teardown is what SIGINT triggers, the process then ignores SIGINT entirely and only dies when an outer `timeout`/CI sends SIGKILL minutes later (observed: a CI lane hung ~50 min despite a 15-min `timeout -s INT`).
Bounding the drain guarantees the process exits promptly after cancellation. On timeout it logs (so the offending goroutine is discoverable) and returns nil; the leaked goroutine is reaped when the process exits. In the normal case the goroutines drain in well under the timeout, so this is a no-op.
func EnsureAvailablePorts ¶
EnsureAvailablePorts checks if the proxy and DNS ports are available. If they are available, it returns them unchanged. If not, it allocates new available ports for them.
func EnsureKeployFolderPermissions ¶ added in v3.3.9
func EnsureKeployFolderPermissions(ctx context.Context, logger *zap.Logger, keployPath string) error
EnsureKeployFolderPermissions checks and fixes permission issues (both read and write) on the keploy folder. This should be called once at startup before any file operations to ensure all files are accessible by the current user. This prevents permission errors during test execution. This function is only called for native mode - Docker commands use sudo re-exec instead.
func EnsureRmBeforeName ¶
func ExecCancel ¶
func ExecCancel()
func ExpandPath ¶
ExpandPath expands a given path, replacing the tilde with the user's home directory
func ExtractCmdTypeFromArgs ¶ added in v3.6.17
ExtractCmdTypeFromArgs pulls an explicit --cmd-type out of raw argv.
ShouldReexecWithSudo has to decide whether keploy needs root before cobra has parsed anything and before any config file is read, so it cannot ask the resolved config what the command type is. Returns "" when the flag is absent; the caller decides what an unrecognised value means.
func ExtractCommandFromArgs ¶ added in v3.3.9
ExtractCommandFromArgs parses os.Args to find the value of -c or --command flag. Returns empty string if not found.
func FileExists ¶
FileExists checks if a file exists and is not a directory at the given path.
func FixFilePermission ¶ added in v3.3.9
FixFilePermission attempts to fix permission issues on a specific file by changing ownership. This is called when a file operation (read or write) fails due to permission issues, typically because the file is owned by root from an older sudo-based keploy version.
func FixKeployFolderPermissions ¶ added in v3.3.9
func FixKeployFolderPermissions(ctx context.Context, logger *zap.Logger, keployPath string, permErrors []PermissionError) error
FixKeployFolderPermissions attempts to fix permission issues on the keploy folder by changing ownership to the current user using sudo chown. It shows which files have issues and provides a timeout for the sudo password prompt. If timeout is reached, it continues without fixing (with a warning).
func GenerateGithubActions ¶
GenerateGithubActions generates a GitHub Actions workflow file for Keploy
func GetAbsPath ¶
func GetAvailablePort ¶
GetAvailablePort finds and returns an available port on the system
func GetContainerIPv4 ¶
func GetCurrentBinaryPath ¶
func GetFullCommandUsed ¶ added in v3.1.3
func GetFullCommandUsed() string
GetFullCommandUsed returns the full command-line used to run the current process. It reconstructs the command from os.Args, adding quoting for arguments with spaces or quotes.
func GetLastDirectory ¶
func GetPermissionFixCommand ¶ added in v3.3.9
GetPermissionFixCommand returns the sudo command to fix keploy folder permissions. This is used to prepend the fix command to docker commands so they run in the same PTY session. Returns empty string if the current user cannot be determined.
func GetProtoMessageDescriptor ¶
func GetProtoMessageDescriptor(ctx context.Context, logger *zap.Logger, pc models.ProtoConfig) (protoreflect.MessageDescriptor, []protoreflect.FileDescriptor, error)
func GetReqMeta ¶
GetReqMeta returns the metadata of the request
func GetVersionAsComment ¶
func GetVersionAsComment() string
func HandleRecovery ¶
HandleRecovery handles the common logic for recovering from a panic.
func InterruptProcessTree ¶
InterruptProcessTree interrupts an entire process tree using the given signal
func IsDockerCmd ¶
func IsFileEmpty ¶
func IsPassThrough ¶
func IsShutdownError ¶ added in v3.3.1
IsShutdownError checks if the error is related to shutdown (EOF, connection closed, etc.) This is useful for gracefully handling errors during application shutdown.
func IsXMLResponse ¶
func LogError ¶
LogError logs the error with the provided fields if the error is not context.Canceled.
func NetworkToHostShort ¶
func ParseGRPCPath ¶
func ParseMetadata ¶
func ProtoTextToJSON ¶
func ProtoTextToJSON(md protoreflect.MessageDescriptor, files []protoreflect.FileDescriptor, text string, logger *zap.Logger) ([]byte, bool)
ProtoTextToJSON converts a Protoscope text payload to JSON via:
Protoscope text -> wire bytes (ProtoTextToWire) -> JSON (WireToJSON).
It preserves your logging style and returns (jsonBytes, ok).
func ProtoTextToWire ¶
ProtoTextToWire turns Protoscope text into wire bytes using the library (no exec).
func ProtoWireToJSON ¶
func ProtoWireToJSON(md protoreflect.MessageDescriptor, files []protoreflect.FileDescriptor, wire []byte) ([]byte, error)
ProtoWireToJSON takes a MessageDescriptor, compiled files, and a wire-format []byte, and returns the JSON encoding ([]byte). The files parameter is crucial for resolving google.protobuf.Any types which require access to all message types in the compiled schema.
func Recover ¶
Recover recovers from a panic and logs the stack trace to Sentry. It also stops the global context.
func ReexecWithSudo ¶ added in v3.3.9
ReexecWithSudo re-executes the current keploy command with sudo. This is used when a Docker/Docker Compose command is detected and keploy is not running as root. Uses syscall.Exec to replace the current process entirely - no parent process remains. This function never returns on success.
func RegisterPreCancelHook ¶ added in v3.5.73
func RegisterPreCancelHook(fn func())
RegisterPreCancelHook appends fn to the list of callbacks NewCtx's signal handler runs synchronously before cancel(). Safe to call from any goroutine at any time after NewCtx; hooks registered after the signal has fired will not run.
func RemoveDoubleQuotes ¶
func RemoveDoubleQuotes(tempMap map[string]interface{})
RemoveDoubleQuotes removes all double quotes from the values in the provided template map. This function handles cases where the templating engine fails to parse values containing both single and double quotes. For example: Input: '"Not/A)Brand";v="8", "Chromium";v="126", "Brave";v="126"' Output: Not/A)Brand;v=8, Chromium;v=126, Brave;v=126
func RenderTemplatesInString ¶
func RenderTemplatesInString(logger *zap.Logger, input string, templateData map[string]interface{}) (string, error)
RenderTemplatesInString finds all template placeholders (e.g., {{.name}} or {{string .name}}) in a string, executes them with the provided data, and replaces them with the result. It is robust against strings that contain non-template curly braces by using a strict regex.
func ReplaceBaseURL ¶
ReplaceBaseURL replaces the base URL (scheme + host) of the given URL with the provided baseURL. It returns the updated URL as a string or an error if the operation fails.
func RestoreKeployFolderOwnership ¶ added in v3.3.9
RestoreKeployFolderOwnership restores ownership of the keploy folder to the original user after running with sudo. This is called at the end of Docker mode execution. If SUDO_USER is set, it means we're running under sudo and should restore ownership.
func RestoreUmask ¶
func RestoreUmask(oldMask int)
func SentryInit ¶
func SetCancel ¶
func SetCancel(c context.CancelFunc)
func SetCoveragePath ¶
SetCoveragePath takes a goCovPath and sets the coverage path accordingly. It returns an error if the path is a file or if the path does not exist.
func ShouldReexecWithSudo ¶ added in v3.3.9
func ShouldReexecWithSudo() bool
ShouldReexecWithSudo checks if keploy should re-execute itself with sudo. Returns true if: 1. A Docker/Docker Compose command is detected in the -c/--command flag, OR 2. The "cloud replay" subcommand is being used (it generates a docker-compose internally) AND Keploy is NOT currently running as root.
func Stop ¶
Stop requires a reason to stop the server. this is to ensure that the server is not stopped accidentally. and to trace back the stopper
func ToString ¶
func ToString(val interface{}) string
ToString remove all types of value to strings for comparison.
func TrimSpaces ¶
TrimSpaces removes unwanted spaces around unescaped ',' and '='
Types ¶
type AutoInc ¶
type CmdType ¶
type CmdType string
const ( DockerRun CmdType = "docker-run" DockerStart CmdType = "docker-start" DockerCompose CmdType = "docker-compose" Native CmdType = "native" Empty CmdType = "" )
CmdType constants
func FindDockerCmd ¶
FindDockerCmd checks if the cli is related to docker or not, it also returns if it is a docker compose file
type GitHubRelease ¶
func GetLatestGitHubRelease ¶
GetLatestGitHubRelease fetches the latest version and release body from GitHub releases with a timeout.
type JSONWriter ¶ added in v3.4.5
type JSONWriter struct {
// contains filtered or unexported fields
}
func NewJSONWriter ¶ added in v3.4.5
func NewJSONWriter(enabled bool) *JSONWriter
func (*JSONWriter) IsEnabled ¶ added in v3.4.5
func (w *JSONWriter) IsEnabled() bool
func (*JSONWriter) Write ¶ added in v3.4.5
func (w *JSONWriter) Write(v interface{}) error
type PermissionError ¶ added in v3.3.9
type PermissionError struct {
Path string
OwnerUID uint32
IsRead bool // true if it's a read permission issue, false if write
}
PermissionError holds information about files/directories with permission issues
func CheckKeployFolderPermissions ¶ added in v3.3.9
func CheckKeployFolderPermissions(logger *zap.Logger, keployPath string) ([]PermissionError, error)
CheckKeployFolderPermissions checks if the keploy folder and its contents are readable and writable by the current user. Returns a list of paths with permission issues.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package log provides utility functions for logging.
|
Package log provides utility functions for logging. |
|
Package pathsafe holds the small path-safety predicates that are shared by every place a caller-supplied identifier (today: the test-set ID) is interpolated into a filesystem path.
|
Package pathsafe holds the small path-safety predicates that are shared by every place a caller-supplied identifier (today: the test-set ID) is interpolated into a filesystem path. |