How to Remove All Files In a Directory In Go - Backup Files Software From Scratch Written in Go #11

Опубликовано: 10 Октябрь 2024
на канале: Maharlikans Code
134
4

In this tutorial series #11, we will learn how to remove all the files including subfolders, and its contents deleted permanently without throwing into the recycle bin or trash folder using Golang programming language with step by step guide.

#MaharlikansCode
#RemoveAllFilesInDirectoryInGo
#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:
deldir.go:
package cmd

import (
"fmt"
"path/filepath"
"time"

"github.com/fatih/color"
"github.com/itrepablik/itrlog"
"github.com/itrepablik/kopy"

"github.com/spf13/cobra"
)

// deldirCmd represents the deldir command
var deldirCmd = &cobra.Command{
Use: "deldir",
Short: "Delete the entire folder or directory recursively without confirmation",
Long: `deldir command deletes the entire folder or directory and its contents without confirmation
with the ignored folder or file extension options, the parent folder or directory may not be deleted
if some folders or files need to be kept based on the ignored options from the 'config.yaml' configuration.

Warning: This command executed immediately without confirmation and retention period.

Open the "config.yaml" configuration file, you can change the following default settings such as:
default:
command_properties:
deldir:
ignore: [.jpg, .png, folder_name, setup.exe]
log: true # true or false, make it true to log each deleted file

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 folder from:`
color.Blue(msg + " " + src)
itrlog.Infow(msg, "src", src, "log_time", time.Now().Format(logDTFormat))

// Starts deleting the entire foler and its contents.
deletedFiles, err := kopy.DeleteEntireFolder(src, deldirLog, deldirIgnore)
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 folder 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(deldirCmd)
}

config.yaml:
deldir:
ignore: [.zip]
log: true # true or false, make it true to log each deleted file

kopy.DeleteEntireFolder:
// DeleteEntireFolder deletes the entire folder from the specified source folder or directory with ignored options
func DeleteEntireFolder(src string, logCopiedFile bool, ignoreFT []string) (int, error) {
//Look for any sub sub-directories and its contents.
var files []string
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
})

// Delete any single files matching the retention in specified days old.
for _, f := range files {
// Remove the rest of the old backup files here
srcFile := filepath.FromSlash(f)

// Delete files and folders now
errRemove := os.Remove(srcFile)
if errRemove != nil {
itrlog.Infow("delete_file_error", "file", srcFile, "log_time", time.Now().Format(logDateTimeFormat))
color.Red("deleted file error: " + srcFile)
continue
}

// Delete all the empty folders now
DeleteEmptyFolders(src)

numDeletedFiles++
// Only log when it's true
if logCopiedFile {
itrlog.Infow("deleted_file", "file", srcFile, "log_time", time.Now().Format(logDateTimeFormat))
color.Magenta("deleted file: " + srcFile)
}
}

// Delete all the empty folders now
DeleteEmptyFolders(src)

if err != nil {
return numDeletedFiles, err
}
return numDeletedFiles, err
}

root.go:
// ConfigDelDir is the collection of the deldir config values
type ConfigDelDir struct {
Ignore []string
Log bool
}

var conDelDir []ConfigDelDir
var deldirIgnore []string
var deldirLog bool = false

Source codes omitted...