In this tutorial series #12, we will learn how to delete files based on the modified date and time of each file to be deleted permanently without throwing into the recycle bin or trash folder using Golang programming language with step by step guide.
#MaharlikansCode
#DeleteFilesBasedOnModTimeInGolang
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper
If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode
Source Codes:
cmd/delmd.go:
package cmd
import (
"fmt"
"path/filepath"
"time"
"github.com/fatih/color"
"github.com/itrepablik/itrlog"
"github.com/itrepablik/kopy"
"github.com/spf13/cobra"
)
// delmdCmd represents the delmd command
var delmdCmd = &cobra.Command{
Use: "delmd",
Short: "Delete the files without confirmation from a specified directory with retentions option",
Long: `delmd command deletes the file from a directory or folder including its sub-folders contents.
Warning: This command executed immediately without confirmation.
Open the "config.yaml" configuration file, you can change the following default settings such as:
default:
command_properties:
delmd:
ignore: [.jpg, .png, folder_name, setup.exe]
log: true # true or false, make it true to log each deleted file
keep: 30 # e.g keep latest 30 days based on the modified files datetime
Example of a valid directory path in Windows:
"C:\source_folder_to_delete_files"
Or using the network directories, example:
"\\hostname_or_ip\source_folder_to_delete_files"`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// To make directory path separator a universal, in Linux "/" and in Windows "\" to auto change
// depends on the user's OS using the filepath.FromSlash organic Go's library.
src := filepath.FromSlash(args[0])
msg := `Starts deleting the files from:`
color.Blue(msg + " " + src)
itrlog.Infow(msg, "src", src, "log_time", time.Now().Format(logDTFormat))
// Starts deleting the latest files from.
deletedFiles, err := kopy.DeleteFilesWithRetention(src, delmdKeep, delmdLog, delmdIgnore)
if err != nil {
color.Red(err.Error())
itrlog.Errorw("error", "err", err, "log_time", time.Now().Format(logDTFormat))
return
}
// Give some info back to the user's console and the logs as well.
msg = `Done deleting the latest files from:`
color.Green(msg + " " + src + " Number of Files Deleted: " + fmt.Sprintf("%v", deletedFiles))
itrlog.Infow(msg, "src", src, "deleted_files", deletedFiles, "log_time", time.Now().Format(logDTFormat))
},
}
func init() {
rootCmd.AddCommand(delmdCmd)
}
root.go:
// ConfigDelMD is the collection of the delmd config values
type ConfigDelMD struct {
Ignore []string
Log bool
Keep int
}
var conDelMD []ConfigDelMD
var delmdIgnore []string
var delmdLog bool = false
var delmdKeep int = 0
// DeleteFilesWithRetention deletes the files from the specified source folder or directory
func DeleteFilesWithRetention(src string, modDays int, logCopiedFile bool, ignoreFT []string) (int, error) {
//Look for any sub sub-directories and its contents.
var files []string
// Converts positive to negative number
newModDays := modDays * -1
var startTime int64 = time.Now().AddDate(0, 0, newModDays).Unix() // Behind "x" days modified date and time to start the delete operation.
var endTime int64 = time.Now().Unix() // Current date and time
var err error
var numDeletedFiles int = 0 // Reset this counter variable
err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
_continue := false
for _, i := range ignoreFT {
if strings.Index(path, strings.TrimSpace(i)) != -1 {
// Only log when it's true
if logCopiedFile {
itrlog.Infow("ignored", "file", path, "log_time", time.Now().Format(logDateTimeFormat))
color.Yellow("ignored: " + path)
}
_continue = true // Loop : ignore files and folders here.
}
}
if _continue == false {
if !info.IsDir() {
files = append(files, path)
}
}
return nil
})
return numDeletedFiles, err
}
config.yaml:
delmd:
ignore: [.jpg, .xml]
log: true # true or false, make it true to log each deleted file
keep: 7 # e.g keep latest 30 days based on the modified files datetime
Source codes omitted...