(ns debian.dh-clojure-lein.util
  (:require
   [leiningen.core.main :as main]
   [leiningen.core.project :as proj]))

;; Don't use main/info, etc. because they write to *out*...

(defn info [& msg]
  (let [msg (apply str msg)]
    (binding [*out* *err*] (print "dh-clojure-lein:" msg) (flush))))

(defn debug [& msg] (when main/*debug* (apply info msg)))

(defn abort [& msg]
  (apply info msg)
  (main/exit 2))

(defn normalize-dep [dep]
  ;; leiningen can handle a missing version, but always expects a vec
  (if (symbol? dep) [dep] dep))

(defn dep-map-key [m]
  ;; See proj/dep-key
  (select-keys m [:group-id :artifact-id :classifier :extension]))

(defn dep-vecs->map
  "Returns a leiningen project style map for a project.clj vector of
  dependencies like [[org.clojure/clojure \"42.x\"]].  The result maps
  DEP-KEYs to the corresponding dependency maps, e.g. {{:group-id
  \"org.clojure\", :artifact-id \"clojure\"} {:artifact-id
  \"clojure\", :group-id \"org.clojure\", :version \"42.x\"}}."
  [deps]
  (reduce (fn add-dep-map [m dep]
            (let [dm (-> dep normalize-dep proj/dependency-map)]
              (assoc m (dep-map-key dm) dm)))
          {}
          deps))

(defn map->dep-vecs [m]
  (mapv proj/dependency-vec (vals m)))
