DirJanitor is tiny Go package that provides an easy and automated way to clean up a directory based on file ages. You can specify the maximum age of files to keep and the frequency of the cleanup operation.
I created this package for one of my private projects and decided to share it in case it's helpful to others. 👌
If you're running on Linux, this is the shell command that you can use to achieve a similar job, so you don't need to use this package.
find /path/to/directory -type f -mtime +1 -delete
This command will delete files older than one day. Adjust the value after -mtime to match the desired retention period in days.
To use the DirJanitor package in your Go project, you can add it as a dependency to your project's go.mod
file:
go get github.com/zizekuros/dir-janitor
This command will download and add the package to your project.
In your Go source code, import the dir-janitor package like this:
import "github.com/zizekuros/dir-janitor/pkg"
You can also use an alias for the package to make it more concise:
import dirjanitor "github.com/zizekuros/dir-janitor/pkg"
Here's an example of how to use the DirJanitor package to automate directory cleanup:
package main
import (
"log"
"time"
dirjanitor "github.com/zizekuros/dir-janitor/pkg"
)
func main() {
// Create a DirectoryCleaner instance
cleaner := &dirjanitor.DirectoryCleaner{
Directory: "/path/to/directory",
Retention: 30, // Max age of files to keep (in days)
Frequency: 3600, // Frequency of cleanup (in seconds)
}
// Set a custom logger for the cleaner (optional)
// cleaner.Logger = log.New(os.Stdout, "DirJanitor: ", log.Ldate|log.Ltime)
// Start the cleanup interval
cleaner.StartCleanupInterval()
// You can also perform cleanup job manually if you want like that:
// cleaner.PerformCleanup()
// Your application logic here
// Stop the cleanup routine when you're done
// Make sure to call this to release resources
cleaner.StopCleanupInterval()
}
In the above example, the DirectoryCleaner is configured to clean up files older than 30 days at a frequency of 1 hour (3600 seconds).
To run tests for the DirJanitor package, follow these steps:
- Open a terminal or command prompt.
- Navigate to the root directory of your Go project where the package is located.
- Run the following command to execute the tests:
go test -count=1 ./tests/...
v0.3.0 (Most Recent)
- Added support for manually performing cleanup actions, addressing Issue #2.
- Additional unit test provided (separate tests for "PerformCleanup" and "CleanupInterval").
- Improved documentation.
v0.2.1
- Fixed spelling errors and improved documentation.
v0.2.0
- Added support for custom Logger, addressing Issue #1.
- Added unit tests to ensure package stability.
v0.1.0
- Initial Release
This package is open source and is available under the MIT License.
Feel free to fork the repository, open issues, or submit pull requests. If you encounter any issues or have questions, please don't hesitate to create an issue.
Happy cleaning! 🧹