よろずや

clgrep.py

UNIX Magazine に載っていた ChangeLog Memo は非常に便利だった.が,ChangeLog 形式のメモを検索するプログラムが Ruby で書かれていたのでこれを Python で書き直してみた.FreeBSD 4.4 RELEASE + Python 2.1.1 で動作確認.

#!/usr/bin/env python

import sys, os, re, getopt

def usage():
    print "[USAGE]: %s [options] PATTERN" % sys.argv[0]
    print "    -i -I   Ignore case"
    print "    -r      reverse output"
    sys.exit(0)

def main():
    memo_path = os.path.expanduser("~/memo")
    try:
        opts, args = getopt.getopt(sys.argv[1:],"iIrR")
    except getopt.GetoptError:
        usage()
    if args == [] or len(args) >= 2: usage()
    options = {'ignore-case': 0, 'reverse': 0}
    for key, value in opts:
        if key in ("-i", "-I"): options['ignore-case'] = re.I
        if key in ("-r", "-R"): options['reverse'] = 1
    r = re.compile(args[0],options['ignore-case'])
    lst, chunk = [], ""
    for line in open(memo_path,"r").readlines():
        if re.match("^\t.*$",line):
            chunk += line
        else:
            if r.search(chunk,1): lst.append(chunk)
            chunk = ""
    if options['reverse']: lst.reverse()
    for elem in lst:
        print elem

if __name__ == '__main__':
    main()