Web::Scraperのshellでhistory補完

Web::Scraperのshellをhistoryから補完できるようにしてみました。
shell系は使わないと忘れてしまうので、historyがあったほうがいいかなと思って作ってみました。

~/.scraperhistoryを作っておくと、historyが使えるようになります。

--- scraper.orig	2008-07-07 22:56:06.000000000 +0900
+++ scraper	2008-07-07 23:13:17.000000000 +0900
@@ -12,6 +12,9 @@
 use URI;
 use Web::Scraper;
 use YAML;
+use Path::Class;
+use File::HomeDir;
+use File::Slurp;
 
 sub WARN() {
     return sub {
@@ -36,12 +39,16 @@
 my $stuff   = process_args($ARGV[0])
     or die "Usage: scraper [URI-or-filename]\n";
 
-my $term    = Term::ReadLine->new("Web::Scraper");
+my $term = create_term();
 my $scraper = scraper { run_loop($_[0], $term) };
    $scraper->user_agent->env_proxy;
 
 my $result  = $scraper->scrape($stuff);
 
+END {
+    write_history($term);
+}
+
 sub process_args {
     my $uri = shift;
 
@@ -108,3 +115,50 @@
 CODE
 
 }
+
+sub create_term {
+    my $term    = Term::ReadLine->new("Web::Scraper");
+    return read_history($term);
+}
+
+sub _history_file {
+    return file( File::HomeDir->my_home, '.scraperhistory' )->stringify;
+}
+
+sub read_history {
+    my $term = shift;
+    my $h    = _history_file;
+
+    if ( $term->Features->{readHistory} ) {
+        $term->ReadHistory($h);
+    }
+    elsif ( $term->Features->{setHistory} ) {
+        if ( -e $h ) {
+            my @h = File::Slurp::read_file($h);
+            chomp @h;
+            $term->SetHistory(@h);
+        }
+    }
+    else {
+        # warn "Your ReadLine doesn't support setHistory\n";
+    }
+    $term;
+}
+
+sub write_history {
+    my $term = shift;
+    my $h    = _history_file;
+
+    if ( $term->Features->{writeHistory} ) {
+        $term->WriteHistory($h);
+    }
+    elsif ( $term->Features->{getHistory} ) {
+        my @h = map {"$_\n"} $term->GetHistory;
+        File::Slurp::write_file( $h, @h );
+    }
+    else {
+        # warn "Your ReadLine doesn't support getHistory\n";
+    }
+}
+
+

追記:
Term::ShellUIが簡易シェル作るのにいいよってid:dayflowerさんが書かれてますね。これはなかなか綺麗に書けていいなぁ。シングルスクリプト版のpsh3llも、これ使って書けばよかったかも。

http://d.hatena.ne.jp/dayflower/20080708/1215484119

追記2:
# lukerさんが「rlwrapでも出来るけど、こういうの組み込まれてた方が便利ですよね」と書かれてますが、これもいいかもしれないですね。