Skip to content

Instantly share code, notes, and snippets.

@barbagrigia
Forked from practicalli-johnny/core.cljs
Created May 14, 2017 23:36
Show Gist options
  • Select an option

  • Save barbagrigia/b8a17ec4ef671be302971633b474e0b4 to your computer and use it in GitHub Desktop.

Select an option

Save barbagrigia/b8a17ec4ef671be302971633b474e0b4 to your computer and use it in GitHub Desktop.
(ns birch.core
(:require [clojure.string :as str]))
;; (println ">>>" (first *command-line-args*))
(def node-fs (js/require "fs"))
(def node-path (js/require "path"))
(def read-dir (.-readdirSync node-fs))
(def stat (.-statSync node-fs))
(def path-join (.-join node-path))
(def cli-color (js/require "cli-color"))
(def blue-text (.-blue cli-color))
(def red-text (.-red cli-color))
(defn directory? [f]
(.isDirectory (stat f)))
(def t-branch "|--")
(def i-branch "| ")
(def l-branch "|__")
(def spacer " ")
(declare tree-entry)
(defn child-entries [path]
(map #(tree-entry path %) (read-dir path)))
(defn tree-entry [path name]
(let [path (path-join path name)
is-dir (directory? path)]
{:name name
:directory? is-dir
:children (if is-dir (child-entries path))}))
(defn render-tree [{:keys [name children directory?]}]
(cons
(if directory?
(blue-text name)
(red-text name))
(mapcat (fn [child index]
(let [[first & rest] (render-tree child)
last? (= index (dec (count children)))
prefix-first (if last? l-branch t-branch)
prefix-last (if last? spacer i-branch)]
(cons (str prefix-first first)
(map #(str prefix-last %) rest))))
children)))
(defn -main [dir]
(->> (tree-entry "" dir)
render-tree
(str/join "\n")
print))
;; Example data structure
#_{:name "A"
:children '({:name "B" :children nil}
{:name "C" :children nil}
{:name "D" :children nil})}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment