Implement cleaning up path and removing non existent ones

This commit is contained in:
2024-10-02 22:41:04 +02:00
parent fb00267a5b
commit 885f92aa0f
2 changed files with 36 additions and 13 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
main.log

46
main.go
View File

@@ -6,11 +6,14 @@ import (
"log" "log"
"os" "os"
"os/exec" "os/exec"
"path/filepath"
"slices"
"strings" "strings"
) )
var Error *log.Logger var Error *log.Logger
var Warning *log.Logger var Warning *log.Logger
func init() { func init() {
log.SetFlags(log.Lmicroseconds | log.Lshortfile) log.SetFlags(log.Lmicroseconds | log.Lshortfile)
logFile, err := os.Create("main.log") logFile, err := os.Create("main.log")
@@ -30,44 +33,63 @@ func init() {
} }
func main() { func main() {
// Get the current PATH
currentPath := os.Getenv("PATH") currentPath := os.Getenv("PATH")
paths := strings.Split(currentPath, ";") paths := strings.Split(currentPath, ";")
// Define paths to always include
alwaysInclude := []string{ alwaysInclude := []string{
"C:\\Program Files\\Git\\usr\\bin", "C:\\Program Files\\Git\\usr\\bin",
os.Getenv("GOPATH") + "\\bin", os.Getenv("GOPATH") + "\\bin",
} }
// Clean up the PATH
cleanPaths := []string{} cleanPaths := []string{}
for _, path := range paths { for _, path := range paths {
// Check if the path exists var err error
if _, err := os.Stat(path); err == nil { path = filepath.Clean(path)
cleanPaths = append(cleanPaths, path) if !filepath.IsAbs(path) {
path, err = filepath.Abs(path)
if err != nil {
Error.Printf("error getting absolute path for %v: %v", path, err)
return
}
} }
path = filepath.FromSlash(path)
fhandle, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
Warning.Printf("Path %v does not exist", path)
continue
}
Warning.Printf("Error opening path %v: %v", path, err)
continue
}
fhandle.Close()
if slices.Contains(cleanPaths, path) {
Warning.Printf("Path %v already exists in cleanPaths", path)
continue
}
cleanPaths = append(cleanPaths, path)
log.Printf("Added path %v", path)
} }
// Add the always include paths
for _, path := range alwaysInclude { for _, path := range alwaysInclude {
if !contains(cleanPaths, path) { if !contains(cleanPaths, path) {
cleanPaths = append(cleanPaths, path) cleanPaths = append(cleanPaths, path)
} }
} }
// Join the clean paths
newPath := strings.Join(cleanPaths, ";") newPath := strings.Join(cleanPaths, ";")
// Set the new PATH permanently
cmd := exec.Command("setx", "PATH", newPath) cmd := exec.Command("setx", "PATH", newPath)
err := cmd.Run() out, err := cmd.CombinedOutput()
if err != nil { if err != nil {
fmt.Println("Error setting PATH:", err) Error.Printf("Error setting PATH with error: %v and output:\n%s", err, string(out))
return return
} }
fmt.Println("PATH has been updated successfully.") log.Printf("PATH has been updated successfully")
} }
func contains(slice []string, item string) bool { func contains(slice []string, item string) bool {