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:
Let's organize by file type:
Let's organize by file creation 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:
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:
To unorganize files with the script:
To delete directories with script:
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!

Article discusses iterating through maps in Go, focusing on safe practices, modifying entries, and performance considerations for large maps.Main issue: Ensuring safe and efficient map iteration in Go, especially in concurrent environments and with l

The article discusses creating and manipulating maps in Go, including initialization methods and adding/updating elements.

The article discusses differences between arrays and slices in Go, focusing on size, memory allocation, function passing, and usage scenarios. Arrays are fixed-size, stack-allocated, while slices are dynamic, often heap-allocated, and more flexible.

The article discusses creating and initializing slices in Go, including using literals, the make function, and slicing existing arrays or slices. It also covers slice syntax and determining slice length and capacity.

The article explains how to create and initialize arrays in Go, discusses the differences between arrays and slices, and addresses the maximum size limit for arrays. Arrays vs. slices: fixed vs. dynamic, value vs. reference types.

Article discusses syntax and initialization of structs in Go, including field naming rules and struct embedding. Main issue: how to effectively use structs in Go programming.(Characters: 159)

The article explains creating and using pointers in Go, discussing benefits like efficient memory use and safe management practices. Main issue: safe pointer use.

The article discusses the benefits of using Go (Golang) in software development, focusing on its concurrency support, fast compilation, simplicity, and scalability advantages. Key industries benefiting include technology, finance, and gaming.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download
The most popular open source editor
