DEV Community

IamKhan
IamKhan

Posted on

Organize your desktop: Build a file organizer in Go.

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()
}
Enter fullscreen mode Exit fullscreen mode

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",
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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:

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
}
Enter fullscreen mode Exit fullscreen mode

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.

type fileDateAnalyzer struct {
    wd string
}

func newFileDateAnalyzer(wd string) *fileDateAnalyzer {
    return &fileDateAnalyzer{
        wd: wd,
    }
}

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

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

    return f.moveFileToDateDir(files...)
}

func (f fileDateAnalyzer) createFileDateDirs(files ...string) error {
    for _, file := range files {
        info, err := os.Stat(file)
        if err != nil {
            return err
        }

        if !slices.Contains(blacklist, getFileExtension(file)) {
            if err := mkdir(getCurrentDate(info.ModTime())); err != nil {
                return err
            }
        }
    }

    return nil
}

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

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

    for _, dir := range dirs {
        for _, file := range files {
            info, err := os.Stat(file)
            if err != nil {
                continue
            }

            if dir == getCurrentDate(info.ModTime()) {
                if err := moveFile(file, dir); err != nil {
                    continue
                }
            }
        }
    }

    return nil
}
Enter fullscreen mode Exit fullscreen mode

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 main() {
    logger := slog.Default()
    slog.SetDefault(logger)

    var analyzer fileAnalyzer

    wd, err := os.Getwd()
    if err != nil {
        log.Fatal(err)
    }

    var mode string

    flag.StringVar(&mode, "mode", "", "Provide sort mode (type|date)")
    flag.Parse()

    switch mode {
    case "date":
        analyzer = newFileDateAnalyzer(wd)
    case "type":
        analyzer = newFileTypeAnalyzer(wd)
    default:
        fmt.Println("Provide sort mode flag: --mode=(type|date)")
        return
    }

    if err := analyze(analyzer); err != nil {
        log.Fatal(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

a folder littered with files

Let's organize by file type:

sorting files by type

files sorted by type

Let's organize by file creation date:

sorting files by date

files sorted by date

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:

[CmdletBinding()]
Param(
  [Parameter(Mandatory)][string]$Action
)

function Get-Dirs {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory)][string]$Path
  )
  return Get-ChildItem -Path $Path | Where-Object { $_.GetType() -eq [System.IO.DirectoryInfo] }
}

switch($Action) {
  'build' {
    Write-Host -ForegroundColor green 'building binary...'
    go build -o sorter.exe
  }
  'remove' {
    $folders = Get-Dirs -Path '.'

    foreach($folder in $folders) {
      if ((Get-ChildItem $folder).Count -eq 0) {
        Remove-Item $folder
      } else {
        Write-Host -ForegroundColor yellow 'folder not empty'
      }
    }
  }
  'unsort' {
    Write-Host -ForegroundColor green 'unsorting...'
    Get-ChildItem (Get-Dirs -Path '.') | ForEach-Object { $_ | Move-Item -Destination '.' }
  }
  Default {
    Write-Host -ForegroundColor red 'invalid action'
  }
}
Enter fullscreen mode Exit fullscreen mode

To build your binary with the script:

build binary

To unorganize files with the script:

unsort files

To delete directories with script:

delete directories

Top comments (0)