Implement cleaning up path and removing non existent ones
This commit is contained in:
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
main.log
|
46
main.go
46
main.go
@@ -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 {
|
||||
|
Reference in New Issue
Block a user