Skip to content

Instantly share code, notes, and snippets.

@itachi-19
Last active January 26, 2025 08:34
Show Gist options
  • Save itachi-19/8e32ba6066ab4cfda4c383caeb40f024 to your computer and use it in GitHub Desktop.
Save itachi-19/8e32ba6066ab4cfda4c383caeb40f024 to your computer and use it in GitHub Desktop.
Go Folder Cleanup Script
package main
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"slices"
)
var (
Documents = "Documents"
Pictures = "Pictures"
Music = "Music"
Videos = "Videos"
Others = "Others"
)
func main() {
srcFile := os.Args[1]
destinationRoot := "/home/itachi/" // Replace with your destination root
// Map of extensions to destination subfolders
extMap := map[string][]string {
Documents: {"pdf", "docx", "txt", "xlsx", "csv"},
Pictures: {"jpg", "jpeg", "png", "gif"},
Videos: {"mov", "mp4", "mkv"},
Music: {"mp3", "flac"},
}
err := moveFileByExtension(srcFile, destinationRoot, extMap)
if err != nil {
log.Fatal("[❌] ",err)
}
fmt.Println("[✅] File move completed!")
}
func moveFileByExtension(file, destinationRoot string, extMap map[string][]string) error {
// Skip directories
fileInfo, err := os.Stat(file)
if err != nil {
return err
}
if fileInfo.IsDir() {
return nil
}
destDir, err := getDestinationDir(file, extMap)
destinationFolderPath := filepath.Join(destinationRoot, destDir)
return moveFile(file, destinationFolderPath)
}
func getDestinationDir(path string, extMap map[string][]string) (string, error) {
ext := filepath.Ext(path)[1:]
var destDir = Others
for folder, extensions := range extMap {
if slices.Contains(extensions, ext) {
destDir = folder
}
}
return destDir, nil
}
func moveFile(file string, destinationFolderPath string) error {
// Open source file
sourceFile, err := os.Open(file)
if err != nil {
return err
}
defer sourceFile.Close()
// Create destination file
os.MkdirAll(destinationFolderPath, 0755) // Create destination directory if it doesn't exist
destFilePath := filepath.Join(destinationFolderPath, filepath.Base(file))
newFile, err := os.Create(destFilePath)
if err != nil {
return err
}
defer newFile.Close()
// Copy data to new file
_, err = io.Copy(newFile, sourceFile) // Copy the file content
if err != nil {
return err
}
return os.Remove(file) // Remove the original file completing the move operation
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment