Path: blob/dev/pkg/protocols/offlinehttp/find.go
2070 views
package offlinehttp12import (3"io/fs"4"os"5"path/filepath"6"strings"78"github.com/pkg/errors"9)1011// getInputPaths parses the specified input paths and returns a compiled12// list of finished absolute paths to the files evaluating any allowlist, denylist,13// glob, file or folders, etc.14func (request *Request) getInputPaths(target string, callback func(string)) error {15processed := make(map[string]struct{})1617// Template input includes a wildcard18if strings.Contains(target, "*") {19if err := request.findGlobPathMatches(target, processed, callback); err != nil {20return errors.Wrap(err, "could not find glob matches")21}22return nil23}2425// Template input is either a file or a directory26file, err := request.findFileMatches(target, processed, callback)27if err != nil {28return errors.Wrap(err, "could not find file")29}30if file {31return nil32}3334// Recursively walk down the Templates directory and run all35// the template file checks36if err := request.findDirectoryMatches(target, processed, callback); err != nil {37return errors.Wrap(err, "could not find directory matches")38}39return nil40}4142// findGlobPathMatches returns the matched files from a glob path43func (request *Request) findGlobPathMatches(absPath string, processed map[string]struct{}, callback func(string)) error {44matches, err := filepath.Glob(absPath)45if err != nil {46return errors.Errorf("wildcard found, but unable to glob: %s\n", err)47}48for _, match := range matches {49if filepath.Ext(match) != ".txt" {50continue // only process .txt files51}52if _, ok := processed[match]; !ok {53processed[match] = struct{}{}54callback(match)55}56}57return nil58}5960// findFileMatches finds if a path is an absolute file. If the path61// is a file, it returns true otherwise false with no errors.62func (request *Request) findFileMatches(absPath string, processed map[string]struct{}, callback func(string)) (bool, error) {63info, err := os.Stat(absPath)64if err != nil {65return false, err66}67if !info.Mode().IsRegular() {68return false, nil69}70if filepath.Ext(absPath) != ".txt" {71return false, nil // only process .txt files72}73if _, ok := processed[absPath]; !ok {74processed[absPath] = struct{}{}75callback(absPath)76}77return true, nil78}7980// findDirectoryMatches finds matches for templates from a directory81func (request *Request) findDirectoryMatches(absPath string, processed map[string]struct{}, callback func(string)) error {82err := filepath.WalkDir(83absPath,84func(p string, d fs.DirEntry, err error) error {85// continue on errors86if err != nil {87return nil88}89if d.IsDir() {90return nil91}92if filepath.Ext(p) != ".txt" {93return nil // only process .txt files94}95if _, ok := processed[p]; !ok {96callback(p)97processed[p] = struct{}{}98}99return nil100},101)102return err103}104105106