github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/countlog/output/rotation/name_by_index.go (about)

     1  package rotation
     2  
     3  import (
     4  	"os"
     5  	"path"
     6  	"fmt"
     7  )
     8  
     9  type NameByIndex struct {
    10  	Directory  string
    11  	Pattern    string
    12  	StartIndex int
    13  }
    14  
    15  func (naming *NameByIndex) ListFiles() ([]string, error) {
    16  	dir, err := os.Open(naming.Directory)
    17  	if err != nil {
    18  		if os.IsNotExist(err) {
    19  			return []string{}, nil
    20  		}
    21  		return nil, err
    22  	}
    23  	names, err := dir.Readdirnames(0)
    24  	if err != nil {
    25  		return nil, err
    26  	}
    27  	paths := make([]string, 0, len(names))
    28  	for _, name := range names {
    29  		var idx int
    30  		n, err := fmt.Sscanf(name, naming.Pattern, &idx)
    31  		if err != nil {
    32  			continue
    33  		}
    34  		if n != 1 {
    35  			continue
    36  		}
    37  		paths = append(paths, path.Join(naming.Directory, name))
    38  	}
    39  	return paths, nil
    40  }