Overview

When we’re developing our own command-line tools, we often need to interact with the file system, navigate around the directory tree, or perform actions on files or directories. When we’re building a tool that’s supposed to work on multiple platforms, we also have to pay special attention to how we manipulate paths and file names to ensure our tool works appropriately no matter where it’s run.

For example, Windows uses a backslash \ as a path separator, such as C:\WINDOWS\SYSTEM, while most variations of UNIX use the forward slash / instead, as in /usr/lib. In these scenarios, hard-coding paths and file names into the program can lead to errors or unexpected results.

File path package

To avoid these complications, Go provides the filepath package to manipulate paths, ensuring compatibility across different operating systems. We’ll use this package to develop a command-line tool called walk, which crawls into file system directories looking for specific files. When the tool finds the files it’s looking for, it can list, archive, or delete them. As we develop this tool, we’ll apply the skills required to handle file system objects in our own programs, such as creating directories, copying and deleting files, and handling logs and compressed files. We’ll end up with a useful tool that helps us back up and clean up file systems. We can use this tool manually, or even better, we can schedule it to run automatically by using a background job scheduler such as cron.

Main goals of walk

The walk tool has two main goals: descending into a directory tree to look for files that match a specified criteria, and executing an action on these files. Let’s start building this tool by implementing the search and filter functionality. The only action we’ll implement now is listing the files. This enables us to try the tool and ensure it’s finding the correct files. Later, we’ll implement other actions, such as delete and archive.

This initial version accepts four command-line parameters:

  • -root: The root of the directory tree to start the search. The default is the current directory.
  • -list: List files found by the tool. When specified, no other actions will be executed.
  • -ext: File extension to search. When specified, the tool will only match files with this extension.
  • -size: Minimum file size in bytes. When specified, the tool will only match files whose size is larger than this value.

Creating the directory

We start by creating the directory fileSystem/walk for our new command-line tool:

Get hands-on with 1200+ tech skills courses.