From 491d976677492e0765147bc4c76887af813ebc71 Mon Sep 17 00:00:00 2001
From: Sander Schobers <sander@schobers.eu>
Date: Thu, 11 Feb 2021 21:07:12 +0100
Subject: [PATCH] Added methods to retrieve all file paths in a directory.

---
 utio/dir.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)

diff --git a/utio/dir.go b/utio/dir.go
index f78b508..d9076a0 100644
--- a/utio/dir.go
+++ b/utio/dir.go
@@ -2,8 +2,45 @@ package utio
 
 import (
 	"os"
+	"path/filepath"
+	"regexp"
+	"strings"
 )
 
+// Files gives back all the files in the specified directory
+func Files(root string) ([]string, error) {
+	var files []string
+	if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
+		if err != nil {
+			return nil
+		}
+		if info.IsDir() {
+			return nil
+		}
+		files = append(files, path)
+		return nil
+	}); err != nil {
+		return nil, err
+	}
+	return files, nil
+}
+
+// Files gives back all the files in the specified directory that match the specified glob pattern.
+func FilesFilter(dir, glob string) ([]string, error) {
+	files, err := Files(dir)
+	if err != nil {
+		return nil, err
+	}
+	var filtered []string
+	globRE := globToRE(glob)
+	for _, f := range files {
+		if globRE.MatchString(f) {
+			filtered = append(filtered, f)
+		}
+	}
+	return filtered, nil
+}
+
 // Home gives back the home directory for the current user.
 func Home() (string, error) {
 	return os.UserHomeDir()
@@ -20,3 +57,12 @@ func PathDoesNotExist(path string) bool {
 	var _, err = os.Stat(path)
 	return os.IsNotExist(err)
 }
+
+func globToRE(glob string) *regexp.Regexp {
+	pattern := glob
+	pattern = strings.ReplaceAll(pattern, "\\", "\\\\")
+	pattern = strings.ReplaceAll(pattern, ".", "\\.")
+	pattern = strings.ReplaceAll(pattern, "*", ".*")
+	pattern = strings.ReplaceAll(pattern, "?", ".")
+	return regexp.MustCompile(pattern)
+}