Home >Backend Development >Golang >Organize your desktop: Build a file organizer in Go.

Organize your desktop: Build a file organizer in Go.

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 03:06:14541browse

Is your desktop chaotic? Do you have files of all sorts cluttering your desktop or downloads directory? Let's fix that with a simple script.

As we do at the beginning of any go project, we generate our go.mod file with the "go mod init" directive. To keep things simple, we will write all of our logic in our main.go file.

Let's talk a little about how we will like the script to behave before we write any code. We want to be able to organize our files into directories that indicate the file type or creation date. In short, we want our script to sort video files into a videos directory, music files into a music directory and so on; or sort all files created on a particular date into the same directory.

Now let's code:

Create a main.go file and write the following:

package main

type fileAnalyzer interface {
    analyzeAndSort() error
}

func analyze(fa fileAnalyzer) error {
    return fa.analyzeAndSort()
}

Because we want our program to sort files by different criteria, we create a fileAnalyzer interface that defines a method: analyzeAndSort.
Then we write a function: analyze - that takes any struct that implements the fileAnalyzer interface as an argument and executes its analyzeAndSort method.

In some cases like we will see in this program, there may be certain files you don't want moved. For example, while testing the script, we don't want the program to move our go files or executable/binary into another directory. To prevent this from happening, we have to create a blacklist that includes all the files we will like to remain untouched.

In our main.go file, write the following:

var blacklist = []string{
    "go",
    "mod",
    "exe",
    "ps1",
}

Here, I added the file extension for files I will like to remain unsorted. ".go" and ".mod" are extensions for go files. Because I use a windows machine, my binary will have ".exe" as its extension. I also included ".ps1" because I like to work with powershell scripts in development - as you will see.

Next, we write some helper functions.

func getFileExtension(name string) string {
    return strings.TrimPrefix(filepath.Ext(name), ".")
}

func listFiles(dirname string) ([]string, error) {
    var files []string

    list, err := os.ReadDir(dirname)
    if err != nil {
        return nil, err
    }

    for _, file := range list {
        if !file.IsDir() {
            files = append(files, file.Name())
        }
    }

    return files, nil
}

func listDirs(dirname string) ([]string, error) {
    var dirs []string

    list, err := os.ReadDir(dirname)
    if err != nil {
        return nil, err
    }

    for _, file := range list {
        if file.IsDir() {
            dirs = append(dirs, file.Name())
        }
    }

    return dirs, nil
}

func mkdir(dirname string) error {
    err := os.Mkdir(dirname, 0644)

    if err != nil && os.IsExist(err) {
        return nil
    }

    var e *os.PathError

    if err != nil && errors.As(err, &e) {
        return nil
    }

    return err
}

func moveFile(name string, dst string) error {
    return os.Rename(name, filepath.Join(dst, name))
}

func getCurrentDate(t time.Time) string {
    return t.Format("2006-01-02")
}

func filter[T any](ts []T, fn func(T) bool) []T {
    filtered := make([]T, 0)

    for i := range ts {
        if fn(ts[i]) {
            filtered = append(filtered, ts[i])
        }
    }

    return filtered
}

Most of these are self-explanatory but I'll like to talk about the "mkdir" function. The "mkdir" function creates a directory with the name passed to it as argument - but the function does not return an error if the directory already exists or if there is an "os.PathError".

Now let's create a struct that implements the fileAnalyzer interface:

package main

type fileAnalyzer interface {
    analyzeAndSort() error
}

func analyze(fa fileAnalyzer) error {
    return fa.analyzeAndSort()
}

The fileTypeAnalyzer struct has two properties: wd which holds the name of the current working directory and a mapper. The mapper's keys will be the type of file detected while its values is a list of file extensions associated with the key. We then create a constructor function and provide the file types as well as their associative file extensions to the mapper. Feel free to add more file types and extensions to the list. The anaylyzeAndSort method calls a couple of helper functions and methods that maps file extension to a file type, creates the file type directory and moves the file into said directory. I also added a "misc" folder to hold files that were not captured by the mapper - excluding the blacklisted files of course.

We also want to be able to organize files by creation date. Let's create another struct that implements the fileAnalyzer interface but organizes files by date.

var blacklist = []string{
    "go",
    "mod",
    "exe",
    "ps1",
}

A lot of the logic is the same as that from the fileTypeAnalyzer. The main difference is we are not providing a mapper - instead we get the creation date from the file info and create directories accordingly.

Now let's put everything together in our main function:

func getFileExtension(name string) string {
    return strings.TrimPrefix(filepath.Ext(name), ".")
}

func listFiles(dirname string) ([]string, error) {
    var files []string

    list, err := os.ReadDir(dirname)
    if err != nil {
        return nil, err
    }

    for _, file := range list {
        if !file.IsDir() {
            files = append(files, file.Name())
        }
    }

    return files, nil
}

func listDirs(dirname string) ([]string, error) {
    var dirs []string

    list, err := os.ReadDir(dirname)
    if err != nil {
        return nil, err
    }

    for _, file := range list {
        if file.IsDir() {
            dirs = append(dirs, file.Name())
        }
    }

    return dirs, nil
}

func mkdir(dirname string) error {
    err := os.Mkdir(dirname, 0644)

    if err != nil && os.IsExist(err) {
        return nil
    }

    var e *os.PathError

    if err != nil && errors.As(err, &e) {
        return nil
    }

    return err
}

func moveFile(name string, dst string) error {
    return os.Rename(name, filepath.Join(dst, name))
}

func getCurrentDate(t time.Time) string {
    return t.Format("2006-01-02")
}

func filter[T any](ts []T, fn func(T) bool) []T {
    filtered := make([]T, 0)

    for i := range ts {
        if fn(ts[i]) {
            filtered = append(filtered, ts[i])
        }
    }

    return filtered
}

We configure a logger; get the current working directory to pass as an argument to our fileAnalyzer implementation; create a mode variable to hold values passed in as flags to the application and a switch statement to control how we want to sort. Finally we call the analyze function and pass our fileAnalyzer implementation as argument.

That's all. Let's build our binary and test. I called mine sorter. You can call yours whatever you want to call it with "go build -o [name]"

Here is a folder littered with files of different types:

Organize your desktop: Build a file organizer in Go.

Let's organize by file type:

Organize your desktop: Build a file organizer in Go.

Organize your desktop: Build a file organizer in Go.

Let's organize by file creation date:

Organize your desktop: Build a file organizer in Go.

Organize your desktop: Build a file organizer in Go.

As a bonus, if you use a windows machine and you use powershell - here's a script to help make testing your program seemless.

Create a task.ps1 file and type the following:

type fileTypeAnalyzer struct {
    wd     string
    mapper map[string][]string
}

func newFileTypeAnalyzer(wd string) *fileTypeAnalyzer {
    return &fileTypeAnalyzer{
        wd: wd,
        mapper: map[string][]string{
            "video":  {"mp4", "mkv", "3gp", "wmv", "flv", "avi", "mpeg", "webm"},
            "music":  {"mp3", "aac", "wav", "flac"},
            "images": {"jpg", "jpeg", "png", "gif", "svg", "tiff"},
            "docs":   {"docx", "csv", "txt", "xlsx"},
            "books":  {"pdf", "epub"},
        },
    }
}

func (f fileTypeAnalyzer) analyzeAndSort() error {
    files, err := listFiles(f.wd)
    if err != nil {
        return fmt.Errorf("could not list files: %w", err)
    }

    if err := f.createFileTypeDirs(files...); err != nil {
        return err
    }

    return f.moveFileToTypeDir(files...)
}

func (f fileTypeAnalyzer) moveFileToTypeDir(files ...string) error {
    dirs, err := listDirs(f.wd)
    if err != nil {
        return fmt.Errorf("could not list directories: %w", err)
    }

    for _, dir := range dirs {
        for _, file := range files {
            if slices.Contains(f.mapper[dir], strings.ToLower(getFileExtension(file))) {
                if err := moveFile(file, dir); err != nil {
                    return err
                }
            }
        }
    }

    files, err = listFiles(f.wd)
    if err != nil {
        return err
    }

    if len(files) == 0 {
        return nil
    }

    files = filter(files, func(f string) bool {
        return !slices.Contains(blacklist, getFileExtension(f))
    })

    for i := range files {
        if err := f.moveToMisc(files[i]); err != nil {
            return err
        }
    }

    return nil
}

func (f fileTypeAnalyzer) moveToMisc(file string) error {
    if err := mkdir("misc"); err != nil {
        return err
    }

    return moveFile(file, "misc")
}

func (f fileTypeAnalyzer) createFileTypeDirs(files ...string) error {
    for ftype, fvalues := range f.mapper {
        for _, file := range files {
            if slices.Contains(fvalues, getFileExtension(file)) {
                if err := mkdir(ftype); err != nil {
                    return fmt.Errorf("could not create folder: %w", err)
                }
            }
        }
    }

    return nil
}

To build your binary with the script:

Organize your desktop: Build a file organizer in Go.

To unorganize files with the script:

Organize your desktop: Build a file organizer in Go.

To delete directories with script:

Organize your desktop: Build a file organizer in Go.

The above is the detailed content of Organize your desktop: Build a file organizer in Go.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn