blob: 2eeaa89bc044defad4bd31c8897215f32c084cb2 [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001// 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
15package fileutil
16
17import (
18 "os"
19 "path/filepath"
20 "sort"
21)
22
23// ReadDirOp represents an read-directory operation.
24type ReadDirOp struct {
25 ext string
26}
27
28// ReadDirOption configures archiver operations.
29type ReadDirOption func(*ReadDirOp)
30
31// WithExt filters file names by their extensions.
32// (e.g. WithExt(".wal") to list only WAL files)
33func WithExt(ext string) ReadDirOption {
34 return func(op *ReadDirOp) { op.ext = ext }
35}
36
37func (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.
44func 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}