autoinsertっぽい何か

30分プログラム、その185。Emacsautoinsertっぽいことをやるコマンドラインプログラム。

今までautoinsertでプログラムの先頭に#!やらライセンス情報やらを挿入していた。かなり便利。ただ、最近Vimなども使うようにしているのでEmacsでしか使えないのはいまひとつ。

そこでERBを使って、似たプログラムを適当に書いてみた。

使い方

~/insertに「template.<対象の拡張子>」のようなファイルを置いておく。

# template.rbを評価した内容が、hoge.rbに書き込まれる
$ autoinsert hoge.rb
hoge.rb

# template.pyを評価した内容が、hoge.pyに書き込まれる
$ autoinsert hoge.py
hoge.py

結果として、引数の内容を返すのは、

$ vim `autoinsert hoge.rb`

のように使うため。autoinsert hoge.rb && vim hoge.rbよりもちょっとタイプ数が減って嬉しい気がする。

template.rbの例
#! /opt/local/bin/ruby -w
# -*- mode:ruby; coding:utf-8 -*-
#
# <%= path %> -
#
# Copyright(C) 2007 by <%= NickName %>
# Author: <%= Author %> / <%= Mail %>
# <%= Site %>
#
# Timestamp: <%= Time.now %>
#
# This program is free software; you can redistribute it and/or
# modify it under <%= Licence %>
#

ソースコード

#! /opt/local/bin/ruby -w
# -*- mode:ruby; coding:utf-8 -*-
#
# auto_insert.rb - auto-insert for command line
#
# Copyright(C) 2007 by mzp
# Author: MIZUNO Hiroki
# http://mzp.sakura.ne.jp/
#
# Timestamp: 2007/11/18 22:11:00
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Ruby itself.
#

# ----------------------------------------
# config section
# ----------------------------------------
# template file direcotry
TemplateDir = '~/insert/'

# optional. you can define additional infomation.
Author   = 'MIZUNO Hiroki'
Mail     = 'mzp.ppp at gmail dot com'
NickName = 'mzp'
Site     = 'http://howdyworld.org'
Licence  = 'MIT Licence'

# ----------------------------------------
require 'erb'

# Get template file path from filename
def get_template(filename)
  ext = File.extname(filename)
  File.expand_path "template#{ext}",TemplateDir
end

ARGV.map{|path|
  template = get_template path
  result = ERB.new(IO.read(template)).result(binding)

  File.open(path,'w'){|io|
    io.print result
  }

  puts path
}