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 DeleteFileIfNotExists(logger *zap.Logger, name string) (err error)
- func DetectLanguage(logger *zap.Logger, cmd string) (models.Language, string)
- 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 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 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 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 DeleteFileIfNotExists ¶
func DetectLanguage ¶
DetectLanguage detects the language of the test command and returns the executable
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 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 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 2. 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 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.