...

/

Updating the Function Archiving Files

Updating the Function Archiving Files

Update the archiving function for the walk tools in the main file.

This completes the changes to actions.go. Now, let’s update the main program in main.go.

Adding an archive field

We start by adding a new field called archive to the config struct to represent the target archive directory:

type config struct {
// extenstion to filter out
ext string
// min file size
size int64
// list files
list bool
// delete files
del bool
// log destination writer
wLog io.Writer
// archive directory
archive string
}
Adding the archive field

Updating the main() function

Now, we update the main() function. To make it configurable, we first add a flag called archive, which allows the user to specify the directory in which to archive files. If this option is specified, we’ll assume the user wants to archive the files. If it’s not, the archiving will be skipped.

// Parsing command line flags
root := flag.String("root", ".", "Root directory to start")
logFile := flag.String("log", "", "Log deletes to this file")
// Action options
list := flag.Bool("list", false, "List files only")
archive := flag.String("archive", "", "Archive directory")
del := flag.Bool("del", false, "Delete files")
Adding the main() function

Next, we map the archive flag value to the corresponding field in the config struct instance c so it will be passed to run():

// If list was explicitly set, don't do anything else
if cfg.list {
return listFile(path, out)
}
// Archive files and continue if successful
if cfg.archive != "" {
if err := archiveFile(cfg.archive, root, path); err != nil {
return err
}
}
// Delete files
if cfg.del {
Adding the archive field

Notice that when using the archiving option, the function should only return if there is an error, allowing the next action function delFile() to execute if the user requested it.

Updating the test file

Let’s include tests for the archiving feature next. We open the file main_test.go and add the package strings to the import list. We’ll use it to execute operations on strings such as joining or removing spaces:

import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
)
Importing strings

Then, at the end of the file, we add another test ...