package main
import (
"flag"
"fmt"
"io/ioutil"
"path/filepath"
"sort"
"strconv"
"strings"
)
const (
PATTERN = "___"
)
var path = flag.String("p", "./", "path")
var format = flag.String("f", "", "format: xxx"+PATTERN+"xxx")
var blankLine = flag.String("b", "", "blank line by")
var blankLineNum = flag.Int("bn", 0, "blank line number")
var sortByNum = flag.Bool("sn", true, "sort by num")
type ByNum []string
func (paths ByNum) Len() int {
return len(paths)
}
func (paths ByNum) Swap(i, j int) {
paths[i], paths[j] = paths[j], paths[i]
}
func (paths ByNum) Less(i, j int) bool {
pathi := filepath.Base(paths[i])
pathj := filepath.Base(paths[j])
namei := strings.Split(pathi, ".")[0]
namej := strings.Split(pathj, ".")[0]
numi, _ := strconv.Atoi(namei)
numj, _ := strconv.Atoi(namej)
return numi < numj
}
func listDir(path *string) []string {
files, _ := ioutil.ReadDir(*path)
fileSlice := make([]string, len(files))
absPath, _ := filepath.Abs(*path)
for i, file := range files {
fileSlice[i] = absPath + "/" + file.Name()
}
if *sortByNum {
sort.Sort(ByNum(fileSlice))
} else {
sort.Strings(fileSlice)
}
return fileSlice
}
func formatStr(str *string) *string {
if len(*format) > 0 && strings.Contains(*format, PATTERN) {
replace := strings.Replace(*format, PATTERN, *str, -1)
return &replace
}
return str
}
func main() {
flag.Parse()
rets := listDir(path)
var ret string
for i := 0; i < len(rets); i++ {
ret = rets[i]
fmt.Println(*(formatStr(&ret)))
if i == len(rets)-1 {
break
}
for i := 0; i < *blankLineNum; i++ {
fmt.Println(*blankLine)
}
}
}