#! /usr/bin/env ruby # -*- mode:ruby; coding:utf-8 -*- # # habatu.rb - # # Copyright(C) 2007 by mzp # Author: MIZUNO Hiroki / mzpppp at gmail dot com # http://howdyworld.org # # Timestamp: 2007/12/13 13:39:48 # # This program is free software; you can redistribute it and/or # modify it under MIT Lincence. # require 'yaml' require 'webrick/cgi' require 'jcode' $KCODE='u' class Array # treat Array as tree def value self.first end def children self[1] end end class Habastu < WEBrick::CGI # ChildJoinFirst = '┬─' ChildJoinFirst = '├─' ChildJoinMid = '├─' ChildJoinLast = '└─' ChildSpan = '│ ' ChildSpanLast = '  ' RootJoin = '' RootSpanJP = ' ' RootSpanEN = ' ' def add_prefix(top,rest,lines) x,*xs = lines [top+x] + xs.map{|y| rest + y } end def take_block(lines,marker) buf = [] until lines.empty? do break unless lines.first =~ marker buf.push lines.shift.sub(marker,'') end buf end def parse_tree(lines) buf = [] until lines.empty? do value = lines.shift.strip child = parse_tree take_block(lines,/\A-/) if child.empty? then buf.push value.to_s else buf.push [value,child] end end buf end def habastu(tree) if tree.class == String then [tree] else children = tree.children.map{|c| habastu c } if children.size >= 2 then first_child = add_prefix ChildJoinFirst,ChildSpan,children.first mid_child = children[1...-1].map{|x| add_prefix ChildJoinMid,ChildSpan,x } last_child = add_prefix ChildJoinLast,ChildSpanLast,children.last child = ([first_child]+mid_child+[last_child]).flatten else child = add_prefix(ChildJoinLast,ChildSpanLast,children[0]).flatten end root = "#{tree.value}#{RootJoin}" span = RootSpanJP*2 add_prefix root,span,[""]+child end end def make_span(str) span = '' str.each_char{|c| if c.size == 1 then span += RootSpanEN else span += RootSpanJP end } span end def do_GET(req,res) res['content-type'] = 'text/plain;charset=UTF-8' forrest = parse_tree req.query['input'].split("\n") res.body = forrest.map{|tree| habastu tree }.join("\n") end def do_POST(req,res) do_GET req,res end end Habastu.new.start