首页 >后端开发 >Golang >在下载文件夹中自组织文件(自动)

在下载文件夹中自组织文件(自动)

Barbara Streisand
Barbara Streisand原创
2024-11-29 13:29:14113浏览

Self-organize files in the downloads folder (automatically)

我想您可能见过许多监视下载文件夹并将其中的文件组织到与文件类型匹配的子文件夹中的项目。
这又是其中之一!但您不必每次都运行它......它会在下载新文件时主动监视文件夹,因此您无需执行任何操作?每当移动新文件时,它甚至会显示通知!

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "log"
    "os"
    "path/filepath"
    "time"

    "github.com/fsnotify/fsnotify"
    "github.com/gen2brain/beeep"
)

func alert(title, message string) {
    err := beeep.Alert(title, message, "warn.png")
    if err != nil {
        panic(err)
    }
}

func move(filename, baseFolder, jsonFile string) {
    time.Sleep(2 * time.Second)
    extMap := getExtensionMap(jsonFile)
    folders := getFolderNames(extMap)
    if isFolder(filename, folders) {
        return
    }

    folder := getFolderName(extMap, filepath.Ext(filename))
    createFolder(baseFolder, folder, folders)
    src := fmt.Sprintf("%s/%s", baseFolder, filename)
    dest := fmt.Sprintf("%s/%s/%s", baseFolder, folder, filename)
    os.Rename(src, dest)
    alert(fmt.Sprintf("New file to: %s", folder), fmt.Sprintf("Dest: %s", dest))
}

func startWatching(baseFolder, jsonFile string) {
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        log.Fatal(err)
    }
    defer watcher.Close()

    go func() {
        for {
            select {
            case event, ok := <-watcher.Events:
                if !ok {
                    return
                }

                if event.Has(fsnotify.Create) {
                    filename := filepath.Base(event.Name)
                    move(filename, baseFolder, jsonFile)
                }

            case err, ok := <-watcher.Errors:
                if !ok {
                    return
                }
                fmt.Println("error:", err)
            }
        }
    }()
    err = watcher.Add(baseFolder)
    if err != nil {
        log.Fatal(err)
    }
    <-make(chan struct{})
}

func createFolder(baseFolder, name string, folders []string) {
    for _, v := range folders {
        if name == v {
            newFolder := fmt.Sprintf("%s/%s", baseFolder, v)
            if _, err := os.Stat(newFolder); os.IsNotExist(err) {
                os.Mkdir(newFolder, 0755)
                fmt.Printf("Folder created: %s", newFolder)
            }
        }
    }
}

func isFolder(name string, folders []string) bool {
    for _, v := range folders {
        if name == v {
            return true
        }
    }
    return false
}

func getExtensionMap(jsonFile string) map[string][]string {
    file, err := os.Open(jsonFile)
    if err != nil {
        fmt.Println("Error opening file:", err)
        os.Exit(1)
    }
    defer file.Close()

    data, err := io.ReadAll(file)
    if err != nil {
        fmt.Println("Error reading file:", err)
        os.Exit(1)
    }
    var extensionMap map[string][]string
    err = json.Unmarshal(data, &extensionMap)
    if err != nil {
        fmt.Println("Error unmarshalling JSON:", err)
        os.Exit(1)
    }
    return extensionMap

}

func getFolderName(extensionMap map[string][]string, extension string) string {
    for i := range extensionMap {
        for _, v := range extensionMap[i] {
            if v == extension {
                return i
            }
        }
    }
    return "other"
}

func getFolderNames(extensionMap map[string][]string) []string {
    folders := make([]string, 0, len(extensionMap))
    for folder := range extensionMap {
        folders = append(folders, folder)
    }
    return folders

}

func main() {

    if len(os.Args) != 3 {
        fmt.Println("Folder or Map file is missing")
        os.Exit(1)
    }

    dir := os.Args[1]
    mapFile := os.Args[2]

    info, err := os.Stat(dir)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        os.Exit(1)
    }

    if !info.IsDir() {
        fmt.Printf("%s is not a directory\n", dir)
        os.Exit(1)
    }
    startWatching(dir, mapFile)
}

还没有安装#Go?只需运行源代码中的可执行文件即可!
仓库:https://github.com/costa86/folder-watcher

感谢您花时间阅读本文!

跟我来:
领英 |开发者 |请我喝杯咖啡 | GitHub

以上是在下载文件夹中自组织文件(自动)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn