sys

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2023 License: MIT Imports: 13 Imported by: 1

README

goutils/sys

The sys package is a part of goutils library.

These functions together provide a range of system utilities such as file handling, directory manipulation, process management, environment variable manipulation, and system information retrieval. They might be a part of a larger system or application toolkit.


Functions

CheckRoot
func CheckRoot() error

Checks if the current process is being run with root permissions. If not, it returns an error.

Cd
func Cd(path string) error

Changes the current working directory to the specified path.

CmdExists
func CmdExists(cmd string) bool

Checks if a given command is available in the $PATH.

Cp
func Cp(src string, dst string) error

Copies a file from the source path to the destination path.

EnvVarSet
func EnvVarSet(key string) error

Checks if a given environment variable is set. If not, it returns an error.

GetHomeDir
func GetHomeDir() (string, error) {

Returns the current user's home directory.

GetPublicSSHKey
func GetSSHPubKey(keyName string, password string) (*ssh.PublicKeys, error) {

Retrieves the public SSH key for the given key name, decrypting the associated private key if a password is provided.

Gwd
func Gwd() (string, error)

Returns the current working directory.

GetFutureTime
func GetFutureTime(years int, months int, days int) time.Time {

Returns the date and time of the input years, months, and days parameters from the current time.

GetOSAndArch
func GetOSAndArch() (string, string, error) {

Returns the current operating system and architecture.

IsDirEmpty
func IsDirEmpty(name string) (bool, error) {

Checks if the input directory is empty. Returns true if it is, otherwise returns false.

KillProcess
func KillProcess(pid int, signal Signal) error {

Sends a signal to the process with the specified PID.

RunCommand
func RunCommand(cmd string, args ...string) (string, error) {

Runs the specified command with the specified arguments and returns the output as a string.

RunCommandWithTimeout
func RunCommandWithTimeout(to time.Duration, command string, args ...string) (string,
error) {

Runs a command for a specified number of seconds before timing out and returning the output.

RmRf
func RmRf(path string) error {

Deletes the specified path and all of its contents.

ExpandHomeDir
func ExpandHomeDir(path string) string {

Expands the ~ character in the input path to the current user's home directory.


Installation

To use the goutils/sys package, you need to install it via go get:

go get github.com/l50/goutils/sys

Usage

After installation, you can import it in your project:

import "github.com/l50/goutils/sys"

Tests

To run the tests for the goutils/sys package, navigate to your $GOPATH/src/github.com/l50/goutils/sys directory and run go test:

go test -v

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.


License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cd

func Cd(path string) error

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:

err := Cd("/path/to/dir")

if err != nil {
    fmt.Println("Failed to change directory.")
}

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.

Example:

err := CheckRoot()

if err != nil {
    fmt.Println("The process must be run as root.")
}

func CmdExists

func CmdExists(cmd string) bool

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:

if !CmdExists("ls") {
    fmt.Println("The 'ls' command is not available.")
}

func Cp

func Cp(src string, dst string) error

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:

err := Cp("/path/to/src", "/path/to/dst")

if err != nil {
    fmt.Println("Failed to copy the file.")
}

func EnvVarSet

func EnvVarSet(key string) error

EnvVarSet checks if a given environment variable is set.

Parameters:

key: A string specifying the name of the environment variable to check.

Returns:

error: An error if the environment variable is not set.

Example:

err := EnvVarSet("HOME")

if err != nil {
    fmt.Println("The HOME environment variable is not set.")
}

func ExpandHomeDir

func ExpandHomeDir(path string) string

ExpandHomeDir expands the tilde (~) in a given path to the current user's home directory.

Parameters:

path: A string representing the path to be expanded.

Returns:

string: The expanded path.

Example:

path := "~/Documents/project" expandedPath := ExpandHomeDir(path)

fmt.Println("Expanded Path:", expandedPath)

func GetFutureTime

func GetFutureTime(years int, months int, days int) time.Time

GetFutureTime returns the date and time of the input years, months, and days parameters from the current time.

Parameters:

years: An integer representing the number of years to add. months: An integer representing the number of months to add. days: An integer representing the number of days to add.

Returns:

time.Time: The future date and time calculated from the current time.

Example:

futureTime := GetFutureTime(1, 2, 3) fmt.Println("Future date and time:", futureTime)

func GetHomeDir

func GetHomeDir() (string, error)

GetHomeDir returns the current user's home directory.

Returns:

string: The home directory of the current user. error: An error if there is a problem getting the home directory.

Example:

homeDir, err := GetHomeDir()

if err != nil {
  log.Fatalf("failed to get home dir: %v", err)
}

fmt.Println("Home Directory:", homeDir)

func GetOSAndArch

func GetOSAndArch() (string, string, error)

GetOSAndArch detects 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.

Example usage:

osName, archName, err := GetOSAndArch()
if err != nil {
	fmt.Printf("Error detecting OS and architecture: %v\n", err)
} else {
	fmt.Printf("Detected OS: %s, architecture: %s\n", osName, archName)
}

Returns:

string: The detected operating system name (i.e., "linux", "darwin", or "windows").
string: The detected architecture name (i.e., "amd64", "arm64", or "armv").
error: An error if the OS or architecture is not supported or cannot be detected.

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. It returns a pointer to the public key object, or an error if one occurs.

Parameters:

keyName: A string representing the name of the key to retrieve. password: A string representing the password used to decrypt the private key.

Returns:

*ssh.PublicKeys: A pointer to a PublicKeys object representing the retrieved public key. error: An error if one occurs during key retrieval or decryption.

Example:

keyName := "id_rsa" password := "mypassword" publicKey, err := GetSSHPubKey(keyName, password)

if err != nil {
  log.Fatalf("failed to get SSH public key: %v", err)
}

log.Printf("Retrieved public key: %v", publicKey)

func Gwd

func Gwd() string

Gwd returns the current working directory (cwd). If it fails to get the cwd, it prints the error and returns an empty string.

Returns:

string: The current working directory or an empty string if an error occurs.

Example:

cwd := Gwd()

if cwd == "" {
  log.Fatalf("failed to get cwd")
}

fmt.Println("Current Working Directory:", cwd)

func IsDirEmpty

func IsDirEmpty(name string) (bool, error)

IsDirEmpty checks if an input directory (name) is empty

Parameters:

name: A string representing the path to the directory to check.

Returns:

bool: A boolean indicating whether the directory is empty or not. error: An error if there was any problem reading the directory.

Example:

isEmpty, err := IsDirEmpty("/path/to/directory")

if err != nil {
  log.Fatalf("Error checking directory: %v", err)
}

fmt.Println("Is directory empty:", isEmpty)

func KillProcess

func KillProcess(pid int, signal Signal) error

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.

Parameters: - pid: The process ID of the process to kill. - signal: The signal to send to the process. Currently, only SignalKill is supported, which will terminate the process.

Returns: - error: An error if the process could not be killed.

Example usage:

err := KillProcess(1234, SignalKill) if err != nil { fmt.Printf("failed to kill process: %v", err) } else { fmt.Println("Process terminated successfully") }

Note that SignalKill may not work on all platforms. For more information, see the documentation for the syscall package.

func RmRf

func RmRf(path string) error

RmRf removes 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:

err := RmRf("/path/to/remove")

if err != nil {
  log.Fatalf("Error removing path: %v", err)
}

fmt.Println("Path successfully removed!")

func RunCommand

func RunCommand(cmd string, args ...string) (string, error)

RunCommand runs 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:

output, err := RunCommand("ls", "-l")

if err != nil {
  log.Fatalf("Error running command: %v", err)
}

fmt.Println("Command output:", output)

func RunCommandWithTimeout

func RunCommandWithTimeout(to time.Duration, command string, args ...string) ([]byte, error)

RunCommandWithTimeout runs 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: A time.Duration 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:

*exec.Cmd: The Cmd struct corresponding to the executed command. error: An error if there was any problem running the command.

Example:

cmd, err := RunCommandWithTimeout(time.Second*5, "sleep", "10")

if err != nil {
    log.Fatalf("Error running command: %v", err)
}

output, _ := cmd.Output() fmt.Println("Command output:", string(output))

Types

type Signal

type Signal int

Signal represents a signal that can be sent to a process.

const (
	// SignalKill is a signal that causes the process to be killed immediately.
	SignalKill Signal = iota
)

Jump to

Keyboard shortcuts

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