在clojure中给出相对路径的函数?

时间:2014-10-02 22:15:41

标签: clojure

我需要一个函数,当给定一个基本目录和另一个路径时,我做了一个简化版本,它只匹配绝对路径,但希望能够智能地处理'..'和'。'。在路上。我不确定最好的方法是什么

一些例子:

(relative-path "example" "example/hello") => "hello"

(relative-path "example" "../example/hello") => "hello"

(relative-path "example" "/usr/local") => "../../../usr/local"

1 个答案:

答案 0 :(得分:0)

我经过一些试验和错误后想出来了:

(require '[clojure.java.io :as io]
         '[clojure.string :as string])

(defn interpret-dots
  ([v] (interpret-dots v []))
  ([v output]
     (if-let [s (first v)]
       (condp = s
         "."  (recur (next v) output)
         ".." (recur (next v) (pop output))
         (recur (next v) (conj output s)))
       output)))

(defn drop-while-matching [u v]
  (cond (or (empty? u) (empty? v)) [u v]

        (= (first u) (first v))
        (recur (rest u) (rest v))

        :else [u v]))

(defn path-vector [path]
  (string/split (.getAbsolutePath (io/file path))
                (re-pattern (System/getProperty "file.separator"))))

(defn relative-path [root other]
  (let [[base rel] (drop-while-matching (interpret-dots (path-vector root))
                                        (interpret-dots (path-vector other)))]
    (if (and (empty? base) (empty? rel))
      "."
      (->> (-> (count base)
               (repeat "..")
               (concat rel))
           (string/join (System/getProperty "file.separator")))))

用法:

(relative-path "example/repack.advance/resources"
           "example/repack.advance/resources/eueueeueu/oeuoeu")
;;=> "eueueeueu/oeuoeu"

(relative-path "example/repack.advance/resources"
           "/usr/local")
;;=> "../../../../../../../../usr/local"