read_dir.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. package fileutil
  15. import (
  16. "os"
  17. "path/filepath"
  18. "sort"
  19. )
  20. // ReadDirOp represents an read-directory operation.
  21. type ReadDirOp struct {
  22. ext string
  23. }
  24. // ReadDirOption configures archiver operations.
  25. type ReadDirOption func(*ReadDirOp)
  26. // WithExt filters file names by their extensions.
  27. // (e.g. WithExt(".wal") to list only WAL files)
  28. func WithExt(ext string) ReadDirOption {
  29. return func(op *ReadDirOp) { op.ext = ext }
  30. }
  31. func (op *ReadDirOp) applyOpts(opts []ReadDirOption) {
  32. for _, opt := range opts {
  33. opt(op)
  34. }
  35. }
  36. // ReadDir returns the filenames in the given directory in sorted order.
  37. func ReadDir(d string, opts ...ReadDirOption) ([]string, error) {
  38. op := &ReadDirOp{}
  39. op.applyOpts(opts)
  40. dir, err := os.Open(d)
  41. if err != nil {
  42. return nil, err
  43. }
  44. defer dir.Close()
  45. names, err := dir.Readdirnames(-1)
  46. if err != nil {
  47. return nil, err
  48. }
  49. sort.Strings(names)
  50. if op.ext != "" {
  51. tss := make([]string, 0)
  52. for _, v := range names {
  53. if filepath.Ext(v) == op.ext {
  54. tss = append(tss, v)
  55. }
  56. }
  57. names = tss
  58. }
  59. return names, nil
  60. }