Help us shape the future of Go! Take the 2026 Go Developer Survey

system

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BrewCmd = &cobra.Command{
	Use:   "brew",
	Short: "Update Homebrew packages only",
	Long:  `This command updates only Homebrew packages, skipping system updates.`,
	Run: func(cmd *cobra.Command, _args []string) {
		isVerbose := utils.IsVerbose(cmd)
		updateBrew(isVerbose)
	},
}

BrewCmd represents the Homebrew update subcommand. It provides functionality to update only Homebrew packages, skipping system updates. This is useful when you want to update Homebrew packages independently of system packages.

View Source
var CompauditFixCmd = &cobra.Command{
	Use:   "compauditFix",
	Short: "Fix insecure directories reported by compaudit",
	Long:  `Runs 'compaudit' and applies 'chmod g-w,o-w' to any directories reported as insecure. This uses an interactive zsh so zsh functions like compaudit (from oh-my-zsh) are available.`,
	Run: func(cmd *cobra.Command, _args []string) {
		log.Start("Running compaudit and fixing insecure directories...")
		isVerbose := utils.IsVerbose(cmd)

		execCmd := exec.Command("zsh", "-ic", "compaudit | xargs --no-run-if-empty chmod g-w,o-w")
		log.Verbose(isVerbose, "Executing: %s", execCmd.String())

		outputBytes, err := execCmd.CombinedOutput()
		output := strings.TrimSpace(string(outputBytes))

		if err != nil {
			log.Error("Failed to run compaudit fix: %v", err)
			if output != "" {
				log.Error("Output: %s", output)
			}
			return
		}

		if output != "" {

			log.Message("%s", output)
		}

		log.Success("Finished applying compaudit fixes.")
	},
}

CompauditFixCmd runs 'compaudit' and removes group/world write permissions from any reported insecure directories.

View Source
var KillPortCmd = &cobra.Command{
	Use:   "killPort [port]",
	Short: "Find and kill the process listening on a specific port",
	Long: `This command finds the process ID (PID) listening on the specified network port
using available tools (lsof, ss, netstat) and then terminates that process.

If no port is provided or --interactive is used, it lists listening ports for selection.
Requires appropriate tools to be available on the system.
Primarily intended for Unix-like systems (Linux, macOS).`,
	Args: cobra.MaximumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		isVerbose := utils.IsVerbose(cmd)

		var portStr string
		var selectedPort PortInfo

		if len(args) == 0 || interactive {
			log.Message("Listing listening ports...")
			ports, err := listPorts(filter)
			if err != nil {
				log.Error("Failed to list ports: %v", err)
				return
			}
			if len(ports) == 0 {
				log.Warn("No listening ports found.")
				return
			}
			selectedPort, err = selectPort(ports)
			if err != nil {
				log.Error("Failed to select port: %v", err)
				return
			}
			portStr = selectedPort.Port
		} else {
			portStr = args[0]

			if _, err := strconv.Atoi(portStr); err != nil {
				log.Error("Invalid port number provided: %s. Port must be an integer.", portStr)
				return
			}
		}

		log.Message("Attempting to find process on port %s...", portStr)

		tool := findPortTool()
		if tool == "" {
			log.Error("No suitable tool found for finding processes on ports.")
			return
		}

		var lsofCmd *exec.Cmd
		switch tool {
		case "lsof":
			lsofCmd = exec.Command("lsof", "-ti:"+portStr)
		case "ss":

			lsofCmd = exec.Command(
				"sh",
				"-c",
				fmt.Sprintf("ss -tulpn | grep ':%s ' | grep -o 'pid=[0-9]*' | cut -d'=' -f2 | head -1", portStr),
			)
		case "netstat":
			lsofCmd = exec.Command(
				"sh",
				"-c",
				fmt.Sprintf("netstat -tulpn | grep ':%s ' | awk '{print $7}' | cut -d'/' -f1 | head -1", portStr),
			)
		}
		log.Verbose(isVerbose, "Executing: %s", lsofCmd.String())

		outputBytes, err := lsofCmd.CombinedOutput()
		output := strings.TrimSpace(string(outputBytes))

		if err != nil {

			log.Verbose(isVerbose, "Command finished with error: %v", err)
			log.Verbose(isVerbose, "lsof output: %s", output)

			// Check if the error is ExitError and output is empty - common case for "port not found"
			var exitErr *exec.ExitError
			if errors.As(err, &exitErr) && output == "" {
				log.Warn("No process found listening on port %s.", portStr)
			} else {

				log.Error("Failed to execute command: %v", err)
				log.Error("Command output (if any): %s", output)
			}
			return
		}

		if output == "" {
			log.Warn("lsof ran successfully but found no process ID on port %s.", portStr)
			return
		}

		pids := strings.Fields(output)
		if len(pids) == 0 {
			log.Warn("Command ran successfully but found no process ID on port %s.", portStr)
			return
		}

		killedCount := 0
		errorCount := 0
		for _, pid := range pids {
			log.Info("Found process with PID %s on port %s. Attempting to kill...", pid, portStr)

			killCmd := exec.Command("kill", "-"+signal, pid)
			log.Verbose(isVerbose, "Executing: %s", killCmd.String())

			if err := killCmd.Run(); err != nil {
				log.Error("Failed to kill process with PID %s: %v", pid, err)
				if strings.Contains(err.Error(), "permission denied") {
					log.Warn("Try running with sudo: sudo kill -%s %s", signal, pid)
				}
				errorCount++
			} else {
				log.Success("Successfully sent kill signal %s to process with PID %s.", signal, pid)
				killedCount++
			}
		}

		if killedCount > 0 && errorCount == 0 {
			log.Success("Finished killing process(es) on port %s.", portStr)
		} else if killedCount > 0 && errorCount > 0 {
			log.Warn(
				"Finished attempting to kill process(es) on port %s, but encountered %d error(s).",
				portStr,
				errorCount,
			)
		} else if killedCount == 0 && errorCount > 0 {
			log.Error("Failed to kill any process found on port %s.", portStr)
		}

	},
}
View Source
var KillProcessCmd = &cobra.Command{
	Use:   "killProcess [pid]",
	Short: "Find and kill a process by PID or interactively",
	Long: `This command finds and kills a process by its PID, or lists processes for interactive selection.
If no PID is provided or --interactive is used, it lists running processes for selection.
Requires 'ps' and 'kill' commands to be available on the system.
Primarily intended for Unix-like systems (Linux, macOS).`,
	Args: cobra.MaximumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		isVerbose := utils.IsVerbose(cmd)

		var pidStr string
		var selectedProcess ProcessInfo

		if len(args) == 0 || processInteractive {
			log.Message("Listing running processes...")
			processes, err := listProcesses(processFilter)
			if err != nil {
				log.Error("Failed to list processes: %v", err)
				return
			}
			if len(processes) == 0 {
				log.Warn("No processes found.")
				return
			}
			selectedProcess, err = selectProcess(processes)
			if err != nil {
				log.Error("Failed to select process: %v", err)
				return
			}
			pidStr = selectedProcess.PID
		} else {
			pidStr = args[0]

			if _, err := strconv.Atoi(pidStr); err != nil {
				log.Error("Invalid PID provided: %s. PID must be an integer.", pidStr)
				return
			}
		}

		log.Message("Attempting to kill process with PID %s...", pidStr)

		killCmd := exec.Command("kill", "-"+processSignal, pidStr)
		log.Verbose(isVerbose, "Executing: %s", killCmd.String())

		if err := killCmd.Run(); err != nil {
			log.Error("Failed to kill process with PID %s: %v", pidStr, err)
			if strings.Contains(err.Error(), "permission denied") {
				log.Warn("Try running with sudo: sudo kill -%s %s", processSignal, pidStr)
			}
		} else {
			log.Success("Successfully sent kill signal %s to process with PID %s.", processSignal, pidStr)
		}
	},
}
View Source
var ProxyCmd = &cobra.Command{
	Use:   "proxy",
	Short: "Show or configure system proxies",
	Long:  `This command displays and manages multiple proxy configurations and allows enabling, disabling, or setting them via subcommands.`,
	Run: func(cmd *cobra.Command, args []string) {
		listProxyConfigurations(cmd)
	},
}
View Source
var SetupASDFCmd = &cobra.Command{
	Use:   "asdf",
	Short: "Setup asdf plugins from $HOME/.tool-versions",
	Long:  `Reads $HOME/.tool-versions and installs asdf plugins listed there.`,
	Run: func(cmd *cobra.Command, args []string) {
		setupASDF(utils.IsVerbose(cmd))
	},
}
View Source
var SetupCmd = &cobra.Command{
	Use:   "setup",
	Short: "Setup development tools",
	Long: `Setup various development tools.
Running this command without subcommands will run all setup steps:
- Oh My Zsh
- ASDF plugins
- Dotfiles installation`,
	Run: func(cmd *cobra.Command, _args []string) {
		verbose := utils.IsVerbose(cmd)
		if err := EnsurePrerequisites(verbose); err != nil {
			log.Fatal("Prerequisites check failed: %v", err)
		}

		setupOhMyZsh(verbose)
		setupASDF(verbose)
		if err := setupDotfiles(verbose); err != nil {
			log.Error("Dotfiles setup failed: %v", err)
		}
		setupSoftware(verbose)
	},
}
View Source
var SetupDotfilesCmd = &cobra.Command{
	Use:   "dotfiles",
	Short: "Setup dotfiles from your git repository",
	Long: `Setup dotfiles from your git repository. This command will:
  - Check and install prerequisites (Homebrew, Git, Bash, SSH keys)
  - Clone your dotfiles repository as a bare repository
  - Backup any conflicting files
  - Checkout dotfiles to your home directory
  - Initialize git submodules
  - Configure git to hide untracked files`,
	Run: func(cmd *cobra.Command, args []string) {
		if err := setupDotfiles(utils.IsVerbose(cmd)); err != nil {
			log.Fatal("Dotfiles setup failed: %v", err)
		}
	},
}
View Source
var SetupOhMyZshCmd = &cobra.Command{
	Use:   "oh-my-zsh",
	Short: "Install Oh My Zsh",
	Long:  `Downloads and installs Oh My Zsh. Skips if already installed.`,
	Run: func(cmd *cobra.Command, args []string) {
		setupOhMyZsh(utils.IsVerbose(cmd))
	},
}
View Source
var SetupSSHCmd = &cobra.Command{
	Use:   "ssh",
	Short: "Setup SSH keys for GitHub access",
	Long: `Setup SSH keys for GitHub access. This command will:
  - Check for existing SSH keys
  - Attempt to retrieve SSH keys from Bitwarden vault
  - Generate new SSH keys if none found
  - Configure SSH config for GitHub`,
	Run: func(cmd *cobra.Command, args []string) {
		if err := setupSSH(utils.IsVerbose(cmd)); err != nil {
			log.Fatal("SSH setup failed: %v", err)
		}
	},
}
View Source
var SystemCmd = &cobra.Command{
	Use:   "system",
	Short: "A command for managing the system",
	Long:  `This command will help manage various aspects of MacOS and Linux systems.`,
	Run: func(cmd *cobra.Command, _args []string) {
		err := cmd.Help()
		cobra.CheckErr(err)
	},
}
View Source
var UpdateCmd = &cobra.Command{
	Use:     "update",
	Aliases: []string{"update", "u"},
	Short:   "Update the system",
	Long:    `This command updates the system. It supports Ubuntu and WSL Linux systems and logs a message for unsupported systems.`,
	Run: func(cmd *cobra.Command, _args []string) {
		isVerbose := utils.IsVerbose(cmd)
		autoApprove, _ := cmd.Flags().GetBool("yes")
		cleanupTimeout, _ := cmd.Flags().GetInt("cleanup-timeout")
		log.Verbose(isVerbose, "Checking system type...")

		checkCmd := execCommand("uname", "-a")
		output, err := checkCmd.Output()
		if err != nil {
			log.Error("Error checking system type: %s", err)
			return
		}

		uname := strings.ToLower(string(output))
		log.Verbose(isVerbose, "System type detected: %s", strings.TrimSpace(string(output)))

		if strings.Contains(uname, "ubuntu") || strings.Contains(uname, "linux") {
			log.Verbose(isVerbose, "Detected Ubuntu/Linux system, running system update...")
			updateUbuntu(isVerbose, autoApprove, cleanupTimeout)
		} else if strings.Contains(uname, "darwin") {
			log.Verbose(isVerbose, "Detected macOS system, running macOS update...")
			updateMacOS(isVerbose)
		} else if strings.Contains(uname, "raspberrypi") || strings.Contains(uname, "raspbian") {
			log.Verbose(isVerbose, "Detected Raspberry Pi system, running Raspberry Pi update...")
			updateRaspberryPi(isVerbose)
		} else {
			log.Warn("This system is not yet supported for updates.")
			log.Verbose(isVerbose, "Unsupported system type: %s", strings.TrimSpace(string(output)))
		}
	},
}

UpdateCmd represents the system update command. It provides functionality to update system packages and perform cleanup operations. Supports Ubuntu/Linux systems with optional cleanup including apt autoremove, autoclean, and docker prune. The -y flag can be used to auto-approve cleanup operations without prompting.

Functions

func EnsurePrerequisites added in v0.28.0

func EnsurePrerequisites(verbose bool) error

EnsurePrerequisites checks and installs all prerequisites needed for dotfiles installation. Returns an error if any critical prerequisite cannot be satisfied.

Types

type PortInfo added in v0.31.0

type PortInfo struct {
	Command string
	PID     string
	Port    string
	User    string
}

type ProcessInfo added in v0.31.0

type ProcessInfo struct {
	Command string
	PID     string
	User    string
}

type Software added in v0.29.0

type Software struct {
	Name        string
	Description string
	Optional    bool
	URL         string      // For manual downloads
	Check       func() bool // Returns true if already installed
	// Install returns an error if installation fails.
	// For manual installs, this typically involves opening a URL.
	Install func() error
	// OS restriction (empty means both, otherwise "linux" or "darwin")
	OS string
}

Jump to

Keyboard shortcuts

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