ディレクトリのTree表示

30分プログラム、その545。http://gauc.no-ip.org/awk-users-jp/blis.cgi/DoukakuAWK_040あたりに触発されて、ディレクトリのツリー表示をやってみる。
末尾の処理をさぼったので、ちょっと表示表示が変。

+[a]
| +--hoge
| +[c]
| | +--bar
| +[b]
| | +--foo
| | +--baz

書いてる途中で、派閥ジェネレータ - みずぴー日記で似た処理を書いたことを思い出した。

使い方

$ gosh tree.scm ./a
+[a]
| +--hoge
| +[c]
| | +--bar
| +[b]
| | +--foo
| | +--baz

ソースコード

#! /opt/local/bin/gosh
;; -*- mode:scheme; coding:utf-8 -*-
;;
;; tree.scm -
;;
;; Copyright(C) 2009 by mzp
;; Author: MIZUNO Hiroki / mzpppp at gmail dot com
;; http://howdyworld.org
;;
;; Timestamp: 2009/03/15 21:22:45
;;
;; This program is free software; you can redistribute it and/or
;; modify it under MIT Lincence.
;;

(use file.util)

(define (tree-dir path)
  (if (file-is-directory? path)
      (cons (sys-basename path)
	    (map tree-dir (glob (build-path path "*"))))
      (sys-basename path)))

(define (tree->string tree indent)
  (if (pair? tree)
      (let [(name     (car tree))
	    (children (cdr tree))]
	(string-append #`",|indent|+[,name]\n"
		       (string-join
			(map (cut tree->string <> #`"| ,indent")
			     children)
			"\n")))
      #`",|indent|+--,tree"))

(define (main args)
  (print (tree->string (tree-dir (cadr args)) "")))