...

Source file src/go.etcd.io/etcd/client/pkg/v3/fileutil/read_dir.go

Documentation: go.etcd.io/etcd/client/pkg/v3/fileutil

     1  // Copyright 2018 The etcd Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package fileutil
    16  
    17  import (
    18  	"os"
    19  	"path/filepath"
    20  	"sort"
    21  )
    22  
    23  // ReadDirOp represents an read-directory operation.
    24  type ReadDirOp struct {
    25  	ext string
    26  }
    27  
    28  // ReadDirOption configures archiver operations.
    29  type ReadDirOption func(*ReadDirOp)
    30  
    31  // WithExt filters file names by their extensions.
    32  // (e.g. WithExt(".wal") to list only WAL files)
    33  func WithExt(ext string) ReadDirOption {
    34  	return func(op *ReadDirOp) { op.ext = ext }
    35  }
    36  
    37  func (op *ReadDirOp) applyOpts(opts []ReadDirOption) {
    38  	for _, opt := range opts {
    39  		opt(op)
    40  	}
    41  }
    42  
    43  // ReadDir returns the filenames in the given directory in sorted order.
    44  func ReadDir(d string, opts ...ReadDirOption) ([]string, error) {
    45  	op := &ReadDirOp{}
    46  	op.applyOpts(opts)
    47  
    48  	dir, err := os.Open(d)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  	defer dir.Close()
    53  
    54  	names, err := dir.Readdirnames(-1)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	sort.Strings(names)
    59  
    60  	if op.ext != "" {
    61  		tss := make([]string, 0)
    62  		for _, v := range names {
    63  			if filepath.Ext(v) == op.ext {
    64  				tss = append(tss, v)
    65  			}
    66  		}
    67  		names = tss
    68  	}
    69  	return names, nil
    70  }
    71  

View as plain text