Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for globbing in the middle of the path #114

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions src/me/raynes/fs.clj
Original file line number Diff line number Diff line change
Expand Up @@ -387,12 +387,12 @@
curly-depth)
:else (recur (next stream) (str re c) curly-depth)))))

(defn glob
(defn- glob-1
"Returns files matching glob pattern."
([pattern]
(let [parts (split pattern)
root (apply file (if (= (count parts) 1) ["."] (butlast parts)))]
(glob root (last parts))))
(glob-1 root (last parts))))
([^File root pattern]
(let [regex (glob->regex pattern)]
(seq (.listFiles
Expand All @@ -401,6 +401,58 @@
(accept [_ _ filename]
(boolean (re-find regex filename)))))))))

(defn- has-wildcard?
"Checks if a path part has a wildcard in it."
[s]
(boolean (or (re-find #"(?<!\\)[\*\?]" s)
(re-find #"(?<!\\)\[[^\]]+(?<!\\)\]" s))))

(defn- fix-empty-prefix
"If the prefix list is empty, replace it with [\".\"]"
[prefix]
(if (empty? prefix)
["."]
prefix))

(defn- find-first-pattern
"Finds the first part (from a list of strings) that contains a wildcard, then returns a 3-tuple of
[prefix, part-with-wildcard, suffix], where both prefix and suffix are lists."
[parts]
(loop [prefix []
part (first parts)
suffix (rest parts)]
(cond
(and part (has-wildcard? part))
[(fix-empty-prefix prefix) part suffix]

(not-empty suffix)
(recur (conj prefix part)
(first suffix)
(rest suffix))

:else
[(fix-empty-prefix prefix) part nil])))

(defn glob
"Returns files matching glob pattern."
[path]
(loop [to-process [(find-first-pattern (split path))]
found []]
(if (empty? to-process)
found
(let [[prefix pattern suffix] (first to-process)
files (glob-1 (apply file prefix) pattern)]
(if (empty? suffix)
(recur (rest to-process)
(concat found files))
(recur (concat
(reduce (fn [acc f]
(conj acc (find-first-pattern (concat (split (.getPath f)) suffix))))
[]
files)
(rest to-process))
found))))))

(defn- iterzip
"Iterate over a zip, returns a sequence of the nodes with a nil suffix"
[z]
Expand Down