Documentation ¶
Index ¶
- func Cd(path string) error
- func CheckRoot() error
- func CmdExists(cmd string) bool
- func Cp(src string, dst string) error
- func EnvVarSet(key string) error
- func ExpandHomeDir(path string) string
- func GetFutureTime(years int, months int, days int) time.Time
- func GetHomeDir() (string, error)
- func GetOSAndArch(provider RuntimeInfoProvider) (string, string, error)
- func GetSSHPubKey(keyName string, password string) (*ssh.PublicKeys, error)
- func GetTempPath() string
- func Gwd() string
- func IsDirEmpty(name string) (bool, error)
- func KillProcess(pid int, signal Signal) error
- func RmRf(file fileutils.File) error
- func RunCommand(cmd string, args ...string) (string, error)
- func RunCommandWithTimeout(to int, cmd string, args ...string) (string, error)
- type Cmd
- type DefaultRuntimeInfoProvider
- type RuntimeInfoProvider
- type Signal
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Cd ¶
Cd changes the current working directory to the specified path.
**Parameters:**
dst: A string specifying the path to the directory to switch to.
**Returns:**
error: An error if the current directory cannot be changed.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { dir := "/tmp" // choose a directory that should exist on the testing machine err := sys.Cd(dir) if err != nil { log.L().Errorf("Failed to change directory to %s: %v\n", dir, err) } else { log.L().Println("Directory changed successfully!") } }
Output: Directory changed successfully!
func CheckRoot ¶
func CheckRoot() error
CheckRoot checks if the current process is being run with root permissions.
**Returns:**
error: An error if the process is not being run as root.
func CmdExists ¶
CmdExists checks if a given command is available in the $PATH.
**Parameters:**
cmd: A string specifying the name of the command to look for.
**Returns:**
bool: True if the command exists in the $PATH, otherwise False.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { if !sys.CmdExists("ls") { log.L().Printf("the input command %s is not available on this system", "ls") } }
Output:
func Cp ¶
Cp copies a file from the source path to the destination path.
**Parameters:**
src: A string specifying the path of the file to be copied. dst: A string specifying the path to where the file should be copied.
**Returns:**
error: An error if the file cannot be copied.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { err := sys.Cp("/path/to/src", "/path/to/dst") if err != nil { log.L().Errorf("Failed to copy %s to %s: %v", "/path/to/src", "/path/to/dst", err) } }
Output:
func EnvVarSet ¶
EnvVarSet checks whether a given environment variable is set.
**Parameters:**
key: String specifying the name of the environment variable.
**Returns:**
error: Error if the environment variable is not set.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { if err := sys.EnvVarSet("HOME"); err != nil { log.L().Println("the HOME environment variable is not set") } }
Output:
func ExpandHomeDir ¶
ExpandHomeDir expands the tilde (~) in a path to the home directory of the current user.
**Parameters:**
path: String representing the path to be expanded.
**Returns:**
string: The expanded path.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { path := "~/Documents/project" expandedPath := sys.ExpandHomeDir(path) log.L().Println("Expanded path:", expandedPath) }
Output:
func GetFutureTime ¶
GetFutureTime calculates the date and time after the input years, months, and days from the current time.
**Parameters:**
years: The number of years to add. months: The number of months to add. days: The number of days to add.
**Returns:**
time.Time: The future date and time calculated from the current time.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { futureTime := sys.GetFutureTime(1, 2, 3) log.L().Println("Future date and time:", futureTime) }
Output:
func GetHomeDir ¶
GetHomeDir fetches the home directory of the current user.
**Returns:**
string: The home directory of the current user. error: Error if there is an issue fetching the home directory.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { homeDir, err := sys.GetHomeDir() if err != nil { log.L().Errorf("Failed to get home dir: %v", err) } log.L().Println("Home directory:", homeDir) }
Output:
func GetOSAndArch ¶
func GetOSAndArch(provider RuntimeInfoProvider) (string, string, error)
GetOSAndArch identifies the current system's OS and architecture, and returns them as strings. The function returns an error if the OS or architecture is not supported.
**Returns:**
string: Detected operating system name (e.g., "linux", "darwin", "windows"). string: Detected architecture name (e.g., "amd64", "arm64", "armv"). error: An error if the OS or architecture is not supported or cannot be detected.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { osName, archName, err := sys.GetOSAndArch(&sys.DefaultRuntimeInfoProvider{}) if err != nil { log.L().Errorf("Error detecting OS and architecture: %v", err) } else { log.L().Printf("Detected OS: %s, Architecture: %s\n", osName, archName) } }
Output:
func GetSSHPubKey ¶
func GetSSHPubKey(keyName string, password string) (*ssh.PublicKeys, error)
GetSSHPubKey retrieves the public SSH key for the given key name, decrypting the associated private key if a password is provided.
**Parameters:**
keyName: String representing the name of the key to retrieve. password: String for the password used to decrypt the private key.
**Returns:**
*ssh.PublicKeys: Pointer to the PublicKeys object for the retrieved key. error: Error if one occurs during key retrieval or decryption.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { keyName := "id_rsa" password := "mypassword" publicKey, err := sys.GetSSHPubKey(keyName, password) if err != nil { log.L().Errorf("Failed to get SSH public key: %v", err) } log.L().Printf("Retrieved public key: %v", publicKey) }
Output:
func GetTempPath ¶ added in v2.1.6
func GetTempPath() string
GetTempPath determines the path to the temporary directory based on the operating system. This function is useful for retrieving a standard location for temporary files and directories.
**Returns:**
string: The path to the temporary directory. On Windows, it returns 'C:\\Temp'. On Unix/Linux systems, it returns '/tmp'.
Example ¶
package main import ( "fmt" "github.com/l50/goutils/v2/sys" ) func main() { tempPath := sys.GetTempPath() fmt.Println("Temporary path:", tempPath) }
Output:
func Gwd ¶
func Gwd() string
Gwd gets the current working directory (cwd). In case of failure, it logs the error and returns an empty string.
**Returns:**
string: The current working directory or an empty string if an error occurs.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { cwd := sys.Gwd() if cwd == "" { log.L().Error("Failed to get cwd") } log.L().Println("Current working directory:", cwd) }
Output:
func IsDirEmpty ¶
IsDirEmpty checks whether the input directory (name) is empty.
**Parameters:**
name: The path to the directory to check.
**Returns:**
bool: A flag indicating whether the directory is empty. error: An error if there's a problem reading the directory.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { isEmpty, err := sys.IsDirEmpty("/path/to/directory") if err != nil { log.L().Errorf("Error checking directory: %v", err) } log.L().Println("Is directory empty:", isEmpty) }
Output:
func KillProcess ¶
KillProcess sends a signal to the process with the specified PID. On Windows, it uses the taskkill command to terminate the process. On Unix-like systems, it sends the specified signal to the process using the syscall.Kill function.
Note that SignalKill may not work on all platforms. For more information, see the documentation for the syscall package.
**Parameters:**
pid: The process ID to kill. signal: The signal to send to the process. Currently, only SignalKill is supported, which terminates the process.
**Returns:**
error: An error if the process couldn't be killed.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { err := sys.KillProcess(1234, sys.SignalKill) if err != nil { log.L().Errorf("Failed to kill process: %v", err) } }
Output:
func RmRf ¶
RmRf deletes an input path and everything in it. If the input path doesn't exist, an error is returned.
**Parameters:**
path: A string representing the path to remove.
**Returns:**
error: An error if there was any problem removing the path.
Example ¶
package main import ( "fmt" "os" fileutils "github.com/l50/goutils/v2/file/fileutils" log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { // Create a temporary directory tmpDir, err := os.MkdirTemp("", "example") if err != nil { log.L().Errorf("Failed to create temp directory: %v", err) } // The temporary directory will be removed at the end of this function defer os.RemoveAll(tmpDir) // Convert tmpDir to RealFile type file := fileutils.RealFile(tmpDir) // Use RmRf to remove the directory if err := sys.RmRf(file); err != nil { log.L().Errorf("Error removing path: %v", err) } // Check if the directory was successfully removed _, err = os.Stat(tmpDir) if err == nil || !os.IsNotExist(err) { log.L().Errorf("Directory was not removed: %v", err) return } fmt.Println("Path successfully removed!") }
Output: Path successfully removed!
func RunCommand ¶
RunCommand executes a specified system command.
**Parameters:**
cmd: A string representing the command to run. args: A variadic parameter representing any command line arguments to the command.
**Returns:**
string: The output from the command. error: An error if there was any problem running the command.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { output, err := sys.RunCommand("ls", "-l") if err != nil { log.L().Errorf("Error running command: %v", err) } log.L().Println("Command output:", output) }
Output:
func RunCommandWithTimeout ¶
RunCommandWithTimeout executes a command for a specified number of seconds before timing out. The command will be run in its own process group to allow for killing child processes if necessary.
**Parameters:**
to: An int representing the number of seconds to allow the command to run before timing out. command: A string representing the command to run. args: A variadic parameter representing any command line arguments to the command.
**Returns:**
string: The output from the command if it completes successfully before the timeout. If the command does not complete before the timeout or an error occurs, an empty string is returned. error: An error if there was any problem running the command or if the command does not complete before the timeout.
Example ¶
package main import ( log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { output, err := sys.RunCommandWithTimeout(5, "sleep", "10") if err != nil { log.L().Errorf("Error running command: %v", err) } log.L().Println("Command output:", output) }
Output:
Types ¶
type Cmd ¶ added in v2.1.9
type Cmd struct { CmdString string Args []string Dir string Timeout time.Duration OutputHandler func(string) }
Cmd represents a command to be executed in a shell environment.
**Attributes:**
CmdString: The command string to be executed. Args: Arguments for the command. Dir: The working directory for the command. Timeout: Maximum duration to wait for the command to execute.
A value of 0 indicates no timeout.
OutputHandler: Function to handle the output of the command.
func (*Cmd) RunCmd ¶ added in v2.1.9
RunCmd executes a command with the settings specified in the Cmd struct. It starts the command, optionally manages a timeout, and captures the command's output. If the command does not complete within the specified timeout, it is forcibly terminated.
**Returns:**
string: The combined output from both standard output and standard error of the executed command. If an error occurs or the command times out, an empty string is returned. error: An error if any issue occurs while executing the command, including a timeout.
Example ¶
package main import ( "time" log "github.com/l50/goutils/v2/logging" "github.com/l50/goutils/v2/sys" ) func main() { cmd := sys.Cmd{ CmdString: "echo", Args: []string{"Hello, world!"}, Timeout: 5 * time.Second, OutputHandler: func(s string) { log.L().Println(s) }, } output, err := cmd.RunCmd() if err != nil { log.L().Errorf("Error executing command: %v\n", err) return } log.L().Println(output) }
Output: Hello, world!
type DefaultRuntimeInfoProvider ¶ added in v2.0.4
type DefaultRuntimeInfoProvider struct{}
DefaultRuntimeInfoProvider is the default implementation of the RuntimeInfoProvider interface.
func (*DefaultRuntimeInfoProvider) GetArch ¶ added in v2.0.4
func (p *DefaultRuntimeInfoProvider) GetArch() string
GetArch returns the current architecture.
**Returns:**
string: The current architecture.
func (*DefaultRuntimeInfoProvider) GetOS ¶ added in v2.0.4
func (p *DefaultRuntimeInfoProvider) GetOS() string
GetOS returns the current operating system.
**Returns:**
string: The current operating system.
type RuntimeInfoProvider ¶ added in v2.0.4
RuntimeInfoProvider is an interface for providing information about the current runtime environment.