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

48
main.go
View File

@@ -6,11 +6,14 @@ import (
"log"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
)
var Error *log.Logger
var Warning *log.Logger
func init() {
log.SetFlags(log.Lmicroseconds | log.Lshortfile)
logFile, err := os.Create("main.log")
@@ -30,44 +33,63 @@ func init() {
}
func main() {
// Get the current PATH
currentPath := os.Getenv("PATH")
paths := strings.Split(currentPath, ";")
// Define paths to always include
alwaysInclude := []string{
"C:\\Program Files\\Git\\usr\\bin",
os.Getenv("GOPATH") + "\\bin",
}
// Clean up the PATH
cleanPaths := []string{}
for _, path := range paths {
// Check if the path exists
if _, err := os.Stat(path); err == nil {
cleanPaths = append(cleanPaths, path)
var err error
path = filepath.Clean(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 {
if !contains(cleanPaths, path) {
cleanPaths = append(cleanPaths, path)
}
}
// Join the clean paths
newPath := strings.Join(cleanPaths, ";")
// Set the new PATH permanently
cmd := exec.Command("setx", "PATH", newPath)
err := cmd.Run()
out, err := cmd.CombinedOutput()
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
}
fmt.Println("PATH has been updated successfully.")
log.Printf("PATH has been updated successfully")
}
func contains(slice []string, item string) bool {
@@ -77,4 +99,4 @@ func contains(slice []string, item string) bool {
}
}
return false
}
}