utils

package
v3.6.24 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: Apache-2.0 Imports: 49 Imported by: 0

Documentation

Overview

Package utils provides utility functions for the Keploy application.

Index

Constants

This section is empty.

Variables

View Source
var ConfigGuide = `
# Visit [https://keploy.io/docs/running-keploy/configuration-file/] to learn about using keploy through configration file.
`
View Source
var Emoji = "\U0001F430" + " Keploy:"
View Source
var ErrCode = 0
View Source
var ErrGitHubAPIUnresponsive = errors.New("GitHub API is unresponsive")
View Source
var LogFile *os.File
View Source
var SecretValues = map[string]interface{}{}
View Source
var TemplatizedValues = map[string]interface{}{}
View Source
var Version string
View Source
var VersionIdentifier string
View Source
var WarningSign = "\U000026A0"

Functions

func AddToGitIgnore

func AddToGitIgnore(logger *zap.Logger, path string, ignoreString string) error

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

func AskForConfirmation(ctx context.Context, s string) (bool, error)

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 BindFlagsToViper(logger *zap.Logger, cmd *cobra.Command, viperKeyPrefix string) error

func CacheSudoCredentials added in v3.3.9

func CacheSudoCredentials(ctx context.Context, logger *zap.Logger) error

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 CheckFileExists(path string) bool

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

func CommandContext(ctx context.Context, cmdStr string) (*exec.Cmd, error)

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

func ContainerNameFromDockerRun(cmd string) string

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 DeleteFileIfExists(logger *zap.Logger, name string) (err error)

func DetectLanguage

func DetectLanguage(logger *zap.Logger, cmd string) (models.Language, string)

DetectLanguage detects the language of the test command and returns the executable

func DrainErrGroup added in v3.5.67

func DrainErrGroup(logger *zap.Logger, name string, g *errgroup.Group, timeout time.Duration) error

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

func EnsureAvailablePorts(port uint32) (uint32, error)

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 EnsureRmBeforeName(cmd string) string

func ExecCancel

func ExecCancel()

func ExpandPath

func ExpandPath(path string) (string, error)

ExpandPath expands a given path, replacing the tilde with the user's home directory

func ExtractCmdTypeFromArgs added in v3.6.17

func ExtractCmdTypeFromArgs(args []string) string

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

func ExtractCommandFromArgs(args []string) string

ExtractCommandFromArgs parses os.Args to find the value of -c or --command flag. Returns empty string if not found.

func FileExists

func FileExists(path string) (bool, error)

FileExists checks if a file exists and is not a directory at the given path.

func FixFilePermission added in v3.3.9

func FixFilePermission(ctx context.Context, logger *zap.Logger, filePath string) error

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

func GenerateGithubActions(logger *zap.Logger, appCmd string)

GenerateGithubActions generates a GitHub Actions workflow file for Keploy

func GetAbsPath

func GetAbsPath(path string) (string, error)

func GetAvailablePort

func GetAvailablePort() (uint32, error)

GetAvailablePort finds and returns an available port on the system

func GetContainerIPv4

func GetContainerIPv4() (string, error)

func GetCurrentBinaryPath

func GetCurrentBinaryPath() (string, error)

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 GetLastDirectory() (string, error)

func GetPermissionFixCommand added in v3.3.9

func GetPermissionFixCommand(keployPath string) string

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 GetReqMeta

func GetReqMeta(req *http.Request) map[string]string

GetReqMeta returns the metadata of the request

func GetVersionAsComment

func GetVersionAsComment() string

func HandleRecovery

func HandleRecovery(logger *zap.Logger, r interface{}, errMsg string)

HandleRecovery handles the common logic for recovering from a panic.

func Hash

func Hash(data []byte) string

func InterruptProcessTree

func InterruptProcessTree(logger *zap.Logger, ppid int, sig syscall.Signal) error

InterruptProcessTree interrupts an entire process tree using the given signal

func IsDockerCmd

func IsDockerCmd(kind CmdType) bool

func IsFileEmpty

func IsFileEmpty(filePath string) (bool, error)

func IsPassThrough

func IsPassThrough(logger *zap.Logger, req *http.Request, destPort uint, opts models.OutgoingOptions) bool

func IsShutdownError added in v3.3.1

func IsShutdownError(err error) bool

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 IsXMLResponse(resp *models.HTTPResp) bool

func Keys

func Keys(m map[string][]string) []string

Keys returns an array containing the keys of the given map.

func LogError

func LogError(logger *zap.Logger, err error, msg string, fields ...zap.Field)

LogError logs the error with the provided fields if the error is not context.Canceled.

func NetworkToHostShort

func NetworkToHostShort(net uint16) uint16

func NewCtx

func NewCtx() context.Context

func ParseGRPCPath

func ParseGRPCPath(p string) (serviceFull, method string, err error)

func ParseMetadata

func ParseMetadata(metadataStr string) (map[string]interface{}, error)

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

func ProtoTextToWire(text string) ([]byte, error)

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

func Recover(logger *zap.Logger)

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

func ReexecWithSudo(logger *zap.Logger)

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

func ReplaceBaseURL(currentURL string, baseURL string) (string, error)

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 ReplaceGrpcHost

func ReplaceGrpcHost(authority string, ipAddress string) (string, error)

func ReplaceGrpcPort

func ReplaceGrpcPort(authority string, port string) (string, error)

func ReplaceHost

func ReplaceHost(currentURL string, ipAddress string) (string, error)

func ReplacePort

func ReplacePort(currentURL string, port string) (string, error)

func RestoreKeployFolderOwnership added in v3.3.9

func RestoreKeployFolderOwnership(logger *zap.Logger, keployPath string)

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 SendSignal

func SendSignal(logger *zap.Logger, pid int, sig syscall.Signal) error

func SentryInit

func SentryInit(logger *zap.Logger, dsn string)

func SetCancel

func SetCancel(c context.CancelFunc)

func SetCoveragePath

func SetCoveragePath(logger *zap.Logger, goCovPath string) (string, error)

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 SetUmask

func SetUmask() int

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

func Stop(logger *zap.Logger, reason string) error

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 ToAbsPath

func ToAbsPath(logger *zap.Logger, originalPath string) string

func ToFloat

func ToFloat(value interface{}) float64

func ToInt

func ToInt(value interface{}) int

func ToString

func ToString(val interface{}) string

ToString remove all types of value to strings for comparison.

func TrimSpaces

func TrimSpaces(input string) string

TrimSpaces removes unwanted spaces around unescaped ',' and '='

Types

type AutoInc

type AutoInc struct {
	sync.Mutex // ensures autoInc is goroutine-safe
	// contains filtered or unexported fields
}

func (*AutoInc) Next

func (a *AutoInc) Next() (id int)

func (*AutoInc) Reset

func (a *AutoInc) Reset()

type CmdError

type CmdError struct {
	Type ErrType
	Err  error
}

func ExecuteCommand

func ExecuteCommand(ctx context.Context, logger *zap.Logger, userCmd string, kind CmdType, cancel func(cmd *exec.Cmd) func() error, waitDelay time.Duration, stdin []byte) CmdError

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

func FindDockerCmd(cmd string) CmdType

FindDockerCmd checks if the cli is related to docker or not, it also returns if it is a docker compose file

type ErrType

type ErrType string
const (
	Init    ErrType = "init"
	Runtime ErrType = "runtime"
)

ErrType constants to get the type of error, during init or runtime

type GitHubRelease

type GitHubRelease struct {
	TagName string `json:"tag_name"`
	Body    string `json:"body"`
}

func GetLatestGitHubRelease

func GetLatestGitHubRelease(ctx context.Context, logger *zap.Logger) (GitHubRelease, error)

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.

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.

Jump to

Keyboard shortcuts

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