utils

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2023 License: MIT Imports: 35 Imported by: 3

README

goutils

License Go Report Card Tests Coverage Status Renovate

This repo is comprised of utilities that I use across various go projects.

Dependencies


Developer Environment Setup

  1. Fork this project

  2. (Optional) If you installed gvm:

    source "${HOME}/.gvm"
    
  3. Install pre-commit hooks and dependencies:

    mage installPreCommitHooks
    
  4. Update and run pre-commit hooks locally:

    mage runPreCommit
    
  5. Install keeper commander:

    python3 -m pip install --upgrade pip
    python3 -m pip install keepercommander
    
  6. Install rvm and ruby (for markdownlint):

    gpg --keyserver keyserver.ubuntu.com \
      --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
    \curl -sSL https://get.rvm.io | bash -s stable --ruby
    rvm install ruby-3.2.1
    

Create New Release

This requires the GitHub CLI and gh-changelog GitHub CLI extension.

Install changelog extension:

gh extension install chelnak/gh-changelog

Generate changelog:

NEXT_VERSION=v1.1.3
gh changelog new --next-version "${NEXT_VERSION}"

Create release:

gh release create "${NEXT_VERSION}" -F CHANGELOG.md

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddFencedCB added in v1.1.8

func AddFencedCB(filePath string, language string) error

AddFencedCB helps to address MD040 issues found with markdownlint by adding the input language to fenced code blocks in the input filePath.

func AddFile added in v1.0.9

func AddFile(filePath string) error

AddFile adds the `file` at the input `filePath` to the staging area for its associated repo.

func AnsiblePing added in v1.1.9

func AnsiblePing(hostsFile string) error

AnsiblePing runs ansible all -m ping against all nodes found in the input hostsFile.

Example hostsFile input: "k3s-ansible/inventory/cowdogmoo/hosts.ini"

func AppendToFile added in v1.0.3

func AppendToFile(file string, text string) error

AppendToFile appends an input text string to the end of the input file.

func CSVToLines added in v1.2.1

func CSVToLines(filename string) ([][]string, error)

CSVToLines reads the contents of the specified CSV file and returns its contents as a two-dimensional string slice, where each element in the outer slice represents a row in the CSV file, and each element in the inner slice represents a value in that row. The first row in the CSV file is skipped, as it is assumed to contain column headers. If the file cannot be read or parsed, an error is returned.

func Cd added in v1.0.8

func Cd(dst string) error

Cd is used to change the current working directory to the specified destination.

func CheckRoot

func CheckRoot() error

CheckRoot will check to see if the process is being run as root

func ClearPCCache added in v1.0.3

func ClearPCCache() error

ClearPCCache Clears the pre-commit cache.

func CloneRepo

func CloneRepo(url string, clonePath string, auth transport.AuthMethod) (
	*git.Repository, error)

CloneRepo clones the repo specified with the input `url` to `clonePath`.

func CmdExists added in v1.1.4

func CmdExists(cmd string) bool

CmdExists checks $PATH for for the input cmd. It returns true if the command is found, otherwise it returns false.

func CommanderInstalled added in v1.1.9

func CommanderInstalled() bool

CommanderInstalled returns true if keeper commander is installed on the current system.

func Commit added in v1.0.9

func Commit(repo *git.Repository, msg string) error

Commit commits the current staging area for the input `repo`.

func Cp

func Cp(src string, dst string) error

Cp is used to copy a file from `src` to `dst`.

func CreateDirectory added in v1.1.1

func CreateDirectory(path string) error

CreateDirectory creates a directory at the input path. If any part of the input path doesn't exist, create it. Return an error if the path already exists.

func CreateEmptyFile

func CreateEmptyFile(name string) bool

CreateEmptyFile creates an file based on the name input. It returns true if the file was created, otherwise it returns false.

func CreateFile added in v1.0.9

func CreateFile(filePath string, fileContents []byte) error

CreateFile creates a file at the input filePath with the specified fileContents.

func CreateTag added in v1.0.9

func CreateTag(repo *git.Repository, tag string) error

CreateTag is used to create an input `tag` in the specified `repo` if it doesn't already exist. Resource: https://github.com/go-git/go-git/blob/bf3471db54b0255ab5b159005069f37528a151b7/_examples/tag-create-push/main.go

func DeleteFile added in v1.0.4

func DeleteFile(file string) error

DeleteFile deletes the input file

func DeletePushedTag added in v1.0.9

func DeletePushedTag(repo *git.Repository, tag string, auth transport.AuthMethod) error

DeletePushedTag deletes an input `tag` that has been pushed to remote.

func DeleteTag added in v1.0.9

func DeleteTag(repo *git.Repository, tag string) error

DeleteTag deletes the local input `tag` from the specified repo.

func DownloadFile added in v1.1.3

func DownloadFile(url string, dest string) (string, error)

DownloadFile downloads the file at the input `url` to the specified `dest` on the local filesystem.

func EnvVarSet added in v1.1.1

func EnvVarSet(key string) error

EnvVarSet checks if an input environment variable is set by checking the input key for an associated value. If an env var is not set, an error is returned.

func ExpandHomeDir added in v1.3.0

func ExpandHomeDir(path string) string

ExpandHomeDir expands the tilde character in a path to the user's home directory. The function takes a string representing a path and checks if the first character is a tilde (~). If it is, the function replaces the tilde with the user's home directory. The path is returned unchanged if it does not start with a tilde or if there's an error retrieving the user's home directory.

Example usage:

pathWithTilde := "~/Documents/myfile.txt"
expandedPath := ExpandHomeDir(pathWithTilde)

Parameters:

path: The string containing a path that may start with a tilde (~) character.

Returns:

string: The expanded path with the tilde replaced by the user's home directory, or the
        original path if it does not start with a tilde or there's an error retrieving
        the user's home directory.

func FileExists

func FileExists(fileLoc string) bool

FileExists will return true if a file specified with fileLoc exists. If the file does not exist, it returns false.

func FileToSlice

func FileToSlice(fileName string) ([]string, error)

FileToSlice reads an input file into a slice, removes blank strings, and returns it.

func FindExportedFuncsWithoutTests added in v1.2.2

func FindExportedFuncsWithoutTests(pkgPath string) ([]string, error)

FindExportedFuncsWithoutTests finds all exported functions in a given package path that do not have corresponding tests. It returns a slice of function names or an error if there is a problem parsing the package or finding the tests.

func FindFile added in v1.1.2

func FindFile(fileName string, dirs []string) (string, error)

FindFile looks for an input `filename` in the specified set of `dirs`. The filepath is returned if the `filename` is found.

func GHRelease added in v1.1.9

func GHRelease(newVer string) error

GHRelease creates a new release with the input newVer using the gh cli tool. Example newVer: v1.0.1

func GetDNSRecords added in v1.1.9

func GetDNSRecords(cf Cloudflare) error

GetDNSRecords retrieves the DNS records from cloudflare.

func GetFutureTime added in v1.0.7

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.

func GetHomeDir

func GetHomeDir() (string, error)

GetHomeDir returns the path to current user's home directory

func GetOSAndArch added in v1.2.5

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 added in v1.0.9

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

GetSSHPubKey returns the public SSH key for the input `keyName` and uses the input `password` (if provided) to decrypt the associated private key.

func GetTags added in v1.0.9

func GetTags(repo *git.Repository) ([]string, error)

GetTags returns the tags for an input `repo`.

func GoReleaser added in v1.1.4

func GoReleaser() error

GoReleaser Runs goreleaser to generate all of the supported binaries specified in `.goreleaser`.

func Gwd

func Gwd() string

Gwd will return the current working directory

func InstallBrewDeps added in v1.2.1

func InstallBrewDeps(brewPackages []string) error

InstallBrewDeps runs brew install for the input brew packages.

func InstallBrewTFDeps added in v1.2.1

func InstallBrewTFDeps() error

InstallBrewTFDeps installs dependencies for terraform projects with homebrew.

func InstallGoDeps added in v1.0.3

func InstallGoDeps(deps []string) error

InstallGoDeps runs go install for the input dependencies.

func InstallGoPCDeps added in v1.0.3

func InstallGoPCDeps() error

InstallGoPCDeps Installs dependencies used for pre-commit with golang projects.

func InstallPCHooks added in v1.0.3

func InstallPCHooks() error

InstallPCHooks Installs pre-commmit hooks locally.

func InstallVSCodeModules added in v1.0.8

func InstallVSCodeModules() error

InstallVSCodeModules installs the modules used by the vscode-go extension in VSCode.

func IsDirEmpty

func IsDirEmpty(name string) (bool, error)

IsDirEmpty checks if an input directory (name) is empty

func KeeperLoggedIn added in v1.1.0

func KeeperLoggedIn() bool

KeeperLoggedIn returns true if keeper vault is logged in with the input `email`. Otherwise, it returns false.

func KillProcess added in v1.2.5

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 ListFilesR added in v1.1.7

func ListFilesR(path string) ([]string, error)

ListFilesR lists the files found recursively from the input `path`.

func ModUpdate added in v1.1.3

func ModUpdate(recursive bool, v bool) error

ModUpdate runs `go get -u` or `go get -u ./... if `recursive` is set to true. The `v` parameter provides verbose output if set to true.

func PublicIP added in v1.0.1

func PublicIP(protocol uint) (string, error)

PublicIP uses several external services to get the public IP address of the system running it using https://pkg.go.dev/github.com/GlenDC/go-external-ip. It returns a public IP address or an error.

func PullRepos added in v1.2.2

func PullRepos(dirs ...string) error

PullRepos updates all git repositories found in the given directories by pulling changes from the upstream branch. It looks for repositories by finding directories with a ".git" subdirectory. If a repository is not on the default branch, it will switch to the default branch before pulling changes. Returns an error if any step of the process fails.

func Push added in v1.0.9

func Push(repo *git.Repository, auth transport.AuthMethod) error

Push pushes the contents of the input `repo` to the default remote (origin).

func PushTag added in v1.0.9

func PushTag(repo *git.Repository, tag string, auth transport.AuthMethod) error

PushTag is used to push a tag to remote.

func RandomString added in v1.0.7

func RandomString(length int) (string, error)

RandomString returns a random string of the specified length.

func RepoRoot added in v1.1.8

func RepoRoot() (string, error)

RepoRoot returns the root of the git repo a user is currently in.

func RmRf added in v1.1.1

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.

func RunCommand

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

RunCommand runs a specified system command

func RunCommandWithTimeout added in v1.0.5

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

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

func RunPCHooks added in v1.0.3

func RunPCHooks() error

RunPCHooks Runs all pre-commit hooks locally.

func SearchKeeperRecords added in v1.1.9

func SearchKeeperRecords(searchTerm string) (string, error)

SearchKeeperRecords searches the logged-in user's keeper records for records matching the input searchTerm.

The searchTerm can be a string or regex.

Example Inputs:

SearchKeeperRecords("TESTING") SearchKeeperRecords("TEST.*RD")

If a searchTerm matches a record, the associated UID is returned.

func StringInFile added in v1.0.3

func StringInFile(path string, searchStr string) (bool, error)

StringInFile searches for input searchStr in input the input filepath.

func StringInSlice

func StringInSlice(strToFind string, inputSlice []string) bool

StringInSlice determines if an input string exists in an input slice. It returns true if the string is found, otherwise it returns false.

func StringSlicesEqual added in v1.3.0

func StringSlicesEqual(a, b []string) bool

StringSlicesEqual checks if two string slices are equal.

It returns true if the slices have the same length and same values, false otherwise.

Parameters: a: the first string slice to be compared. b: the second string slice to be compared.

Returns: bool: true if the slices are equal, false otherwise.

func StringToInt64 added in v1.0.6

func StringToInt64(value string) (int64, error)

StringToInt64 returns the converted int64 value of an input string.

func StringToSlice added in v1.1.2

func StringToSlice(delimStr string, delim string) []string

StringToSlice converts an input string (`delimStr`) using the accompanying delimiter (`delim`) to a string slice.

func Tidy added in v1.0.3

func Tidy() error

Tidy runs `go mod tidy`.

func UpdateMageDeps added in v1.0.8

func UpdateMageDeps(magedir string) error

UpdateMageDeps updates mage-specific dependencies using the input path to the associated go.mod.

func UpdatePCHooks added in v1.0.3

func UpdatePCHooks() error

UpdatePCHooks Updates pre-commit hooks locally.

Types

type Cloudflare added in v1.1.9

type Cloudflare struct {
	CFApiKey string
	CFEmail  string
	CFZoneID string
	Email    string
	Endpoint string
	Client   http.Client
}

Cloudflare holds information needed to interface with the cloudflare API.

type FuncInfo added in v1.2.1

type FuncInfo struct {
	// FilePath is the file path of the source file containing the function declaration.
	FilePath string
	// FuncName is the name of the exported function.
	FuncName string
}

FuncInfo contains information about an exported function, including the file path and function name.

func FindExportedFunctionsInPackage added in v1.2.1

func FindExportedFunctionsInPackage(pkgPath string) ([]FuncInfo, error)

FindExportedFunctionsInPackage finds all exported functions in a given Go package by recursively parsing all non-test Go files in the package directory and returning a slice of FuncInfo structs, each containing the file path and the name of an exported function. If no exported functions are found in the package, an error is returned.

Parameters:

pkgPath: A string representing the path to the directory containing the package to search for exported functions.

Returns:

[]FuncInfo: A slice of FuncInfo structs, each containing the file path and the name of an exported function found in the package. error: An error if no exported functions are found.

Example:

packagePath := "/path/to/your/go/package" funcs, err := FindExportedFunctionsInPackage(packagePath)

if err != nil {
	 log.Fatalf("failed to find exported functions: %v", err)
}

for _, f := range funcs {
	 log.Printf("Exported function %s found in file %s\n", f.Name, f.FilePath)
}

type GitConfigUserInfo added in v1.0.9

type GitConfigUserInfo struct {
	User  string
	Email string
}

GitConfigUserInfo holds a username and email to use for user.name and user.email.

func GetGlobalUserCfg added in v1.0.9

func GetGlobalUserCfg() (GitConfigUserInfo, error)

GetGlobalUserCfg returns the username and email from the global git user settings.

type KeeperRecord added in v1.1.9

type KeeperRecord struct {
	UID      string
	Title    string
	URL      string
	Username string
	Password string
	TOTP     string
	Note     string
}

KeeperRecord represents a record maintained by Keeper.

func RetrieveKeeperRecord added in v1.2.3

func RetrieveKeeperRecord(keeperUID string) (KeeperRecord, error)

RetrieveKeeperRecord returns the record found with the input keeperPath.

type LogInfo added in v1.0.4

type LogInfo struct {
	Dir      string
	FilePtr  *os.File
	FileName string
	Path     string
}

LogInfo contains parameters associated with logging throughout the program.

func CreateLogFile added in v1.0.4

func CreateLogFile() (LogInfo, error)

CreateLogFile creates logs/ in the cwd. The cwd name is used to name the log file.

type Signal added in v1.2.5

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
)

Directories

Path Synopsis
v2
web Module

Jump to

Keyboard shortcuts

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