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

system

package
v0.21.3 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2025 License: MIT Imports: 11 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)
	},
}
View Source
var FindNonMovieFoldersCmd = &cobra.Command{
	Use:   "findNonMovieFolders [directory]",
	Short: "Find and optionally delete non-movie folders",
	Long: `This command searches recursively through the supplied directory for directories
that do not contain video files (mp4, mkv, avi, mov, wmv, flv, webm, mpeg, mpg, m4v).
It identifies top-level subdirectories within the supplied directory that lack
any such files anywhere within their structure.

It lists the files within the identified folders before taking action.
It can optionally delete these identified directories if the --dry-run flag is set to false.
By default, --dry-run is true.`,
	Args: cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {

		log.Start("Scanning for non-movie folders...")

		directory := args[0]
		isDryRun, _ := cmd.Flags().GetBool("dry-run")
		isVerbose := utils.IsVerbose(cmd)

		if _, err := os.Stat(directory); os.IsNotExist(err) {
			log.Error("Provided directory does not exist: %s", directory)
			return
		}

		log.Verbose(isVerbose, "Searching for directories in: %s", directory)
		log.Verbose(isVerbose, "Dry run mode: %t", isDryRun)

		spinner := utils.NewProgressSpinner("Scanning directories...")
		spinner.Start()

		nonMovieFolders, err := findNonMovieFolders(isVerbose, directory, func(done, total int) {
			progress := 0.0
			if total > 0 {
				progress = float64(done) / float64(total)
			}
			spinner.SetProgressBar(progress, fmt.Sprintf("Scanning... (%d/%d)", done, total))
		})

		if err != nil {
			spinner.Stop()
			log.Error("Error finding non-movie folders: %s", err)
			return
		}
		spinner.UpdateMessage("Scan complete.")
		spinner.SetProgressBar(1.0)
		spinner.Stop()
		time.Sleep(100 * time.Millisecond)

		log.Verbose(isVerbose, "Found %d potential non-movie folders.", len(nonMovieFolders))

		if len(nonMovieFolders) == 0 {
			log.Success("No non-movie folders found in %s.", directory)
			return
		}

		log.Message("\nProcessing %d non-movie folder(s)...", len(nonMovieFolders))

		deletedCount := 0
		skippedCount := 0
		errorMessages := []string{}

		for _, folder := range nonMovieFolders {

			listFilesCmd := exec.Command("find", ".", "-type", "f")
			listFilesCmd.Dir = folder

			filesToDeleteBytes, listErr := listFilesCmd.Output()

			var actualFiles []string
			var fileCount int
			var listErrorString string

			if listErr != nil {

				errMsg := fmt.Sprintf("Could not list files in folder %s (may be empty or permission issue): %s", folder, listErr)
				log.Warn(errMsg)
				errorMessages = append(errorMessages, errMsg)
				listErrorString = "(error listing files)"
				fileCount = 0
			} else {
				filesList := strings.Split(strings.TrimSpace(string(filesToDeleteBytes)), "\n")

				if len(filesList) > 0 && filesList[0] != "" {
					actualFiles = filesList
				}
				fileCount = len(actualFiles)
				listErrorString = ""
			}

			if isDryRun {
				log.Message("[Dry Run] Would delete folder: %s", folder)
				if listErrorString != "" {
					log.Message("  %s", listErrorString)
				} else if fileCount > 0 {
					for _, file := range actualFiles {

						displayPath := filepath.Join(filepath.Base(folder), strings.TrimPrefix(file, "./"))
						log.Message("  - %s", displayPath)
					}
				} else {
					log.Message("  (Contains no files or only empty subdirectories)")
				}
				skippedCount++
			} else {
				log.Warn("Preparing to delete non-movie folder: %s", folder)
				if listErrorString != "" {
					log.Warn("  %s", listErrorString)
				} else if fileCount > 0 {
					log.Message("  Files within this folder:")
					for _, file := range actualFiles {
						displayPath := filepath.Join(filepath.Base(folder), strings.TrimPrefix(file, "./"))
						log.Message("    - %s", displayPath)
					}
				} else {
					log.Message("  (Folder contains no files or only empty subdirectories)")
				}

				log.Warn("Executing delete: rm -rf %s", folder)
				deleteCmd := exec.Command("rm", "-rf", "--", folder)
				if err := deleteCmd.Run(); err != nil {
					errMsg := fmt.Sprintf("Error deleting folder %s: %s", folder, err)
					log.Error(errMsg)
					errorMessages = append(errorMessages, errMsg)
					skippedCount++
				} else {
					log.Success("Deleted: %s", folder)
					deletedCount++
				}
			}
			log.Message("")
		}

		if len(errorMessages) > 0 {
			log.Warn("Encountered %d error(s) during processing.", len(errorMessages))
		}

		if isDryRun {
			log.Success("Dry run complete. %d folder(s) identified for deletion.", skippedCount)
		} else {
			log.Success("Processing complete. Deleted %d folder(s), skipped %d due to errors.", deletedCount, skippedCount)
		}
	},
}

FindNonMovieFoldersCmd defines the cobra command for finding and optionally deleting directories that do not contain common video file types.

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 the 'lsof' command and then terminates that process forcefully using 'kill -9'.

Requires 'lsof' and 'kill' commands to be available on the system.
Primarily intended for Unix-like systems (Linux, macOS).`,
	Args: cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		portStr := args[0]
		isVerbose := utils.IsVerbose(cmd)

		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)

		lsofCmd := exec.Command("lsof", "-ti:"+portStr)
		log.Verbose(isVerbose, "Executing: %s", lsofCmd.String())

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

		if err != nil {

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

			if _, ok := err.(*exec.ExitError); ok && output == "" {
				log.Warn("No process found listening on port %s.", portStr)
			} else {

				log.Error("Failed to execute lsof command: %v", err)
				log.Error("lsof 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("lsof command returned empty output after trimming.")
			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", "-9", 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)
				errorCount++
			} else {
				log.Success("Successfully sent kill signal to process with PID %s.", 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 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()
	},
}
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)
		log.Verbose(isVerbose, "Checking system type...")

		checkCmd := exec.Command("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)
		} 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)))
		}
	},
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

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