sys

package
v2.2.6 Latest Latest
Warning

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

Go to latest
Published: May 2, 2024 License: MIT Imports: 17 Imported by: 1

README

goutils/v2/sys

The sys package is a collection of utility functions designed to simplify common sys tasks.


Table of contents


Functions

Cd(string)
Cd(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.


CheckRoot()
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.


Cmd.RunCmd()
RunCmd() string, error

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.


CmdExists(string)
CmdExists(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.


Cp(string, string)
Cp(string, 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.


DefaultRuntimeInfoProvider.GetArch()
GetArch() string

GetArch returns the current architecture.

Returns:

string: The current architecture.


DefaultRuntimeInfoProvider.GetOS()
GetOS() string

GetOS returns the current operating system.

Returns:

string: The current operating system.


EnvVarSet(string)
EnvVarSet(string) error

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.


ExpandHomeDir(string)
ExpandHomeDir(string) string

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.


GetFutureTime(int, int, int)
GetFutureTime(int, int, int) time.Time

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.


GetHomeDir()
GetHomeDir() string, error

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.


GetOSAndArch(RuntimeInfoProvider)
GetOSAndArch(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.


GetSSHPubKey(string, string)
GetSSHPubKey(string, 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.


GetTempPath()
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'.


Gwd()
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.


IsDirEmpty(string)
IsDirEmpty(string) bool, error

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.


KillProcess(int, Signal)
KillProcess(int, 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.

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.


RmRf(fileutils.File)
RmRf(fileutils.File) error

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.


RunCommand(string, ...string)
RunCommand(string, ...string) string, error

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.


RunCommandWithTimeout(int, string, ...string)
RunCommandWithTimeout(int, string, ...string) string, error

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.


Installation

To use the goutils/v2/sys package, you first need to install it. Follow the steps below to install via go get.

go get github.com/l50/goutils/v2/sys

Usage

After installation, you can import the package in your Go project using the following import statement:

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

Tests

To ensure the package is working correctly, run the following command to execute the tests for goutils/v2/sys:

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

Examples

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
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

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
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

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
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

func EnvVarSet(key string) error

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

func ExpandHomeDir(path string) string

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

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

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

func GetHomeDir() (string, error)

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

func IsDirEmpty(name string) (bool, error)

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

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.

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

func RmRf(file fileutils.File) error

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

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

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

func RunCommandWithTimeout(to int, cmd string, args ...string) (string, error)

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

func (c *Cmd) RunCmd() (string, error)

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

GetOS returns the current operating system.

**Returns:**

string: The current operating system.

type RuntimeInfoProvider added in v2.0.4

type RuntimeInfoProvider interface {
	GetOS() string
	GetArch() string
}

RuntimeInfoProvider is an interface for providing information about the current runtime environment.

type Signal

type Signal int

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

**Attributes:**

SignalKill: A signal that causes the process to be killed immediately.

const (
	// SignalKill represents a signal that kills a process immediately
	SignalKill Signal = iota
)

Signal constants

Jump to

Keyboard shortcuts

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