Created
July 4, 2011 13:54
-
-
Save syohex/1063358 to your computer and use it in GitHub Desktop.
Perl版 get-shit-done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!perl | |
package App::GetShitDone; | |
use strict; | |
use warnings; | |
use Carp qw(croak); | |
my $HOSTS = '/etc/hosts'; | |
my $START_TOKEN = '## start-gsd'; | |
my $END_TOKEN = '## end-gsd'; | |
my @DEFAULT_DENIES = ( | |
'yahoo.co.jp', 'livedoor.com', 'twitter.com', 'nicovideo.jp', | |
'owata-net.com', | |
); | |
sub new { | |
my ($class, @args) = @_; | |
_usage() if scalar @args < 1; | |
_usage() unless $args[0] eq 'work' || $args[0] eq 'play'; | |
croak("Please run script as root") unless $< == 0; | |
my $code_ref = $args[0] eq 'work' ? \&work : \&play; | |
bless $code_ref, $class; | |
} | |
sub work { | |
croak "already 'work' mode!!" if is_work_mode(); | |
open my $fh, ">>", $HOSTS or croak "Can't open $HOSTS"; | |
print {$fh} "$START_TOKEN\n"; | |
for my $site (@DEFAULT_DENIES) { | |
print {$fh} "127.0.0.1\t$site\n"; | |
print {$fh} "127.0.0.1\twww.$site\n"; | |
} | |
print {$fh} "$END_TOKEN\n"; | |
close $fh; | |
rehash(); | |
} | |
sub rehash { | |
my @cmd = qw{/etc/init.d/networking restart}; | |
my $status = system @cmd; | |
croak("Error: $!(exec @cmd)") unless $status == 0; | |
} | |
sub play { | |
croak "not 'work' mode now!!" unless is_work_mode(); | |
open my $fh, "<", $HOSTS or croak "Can't open $HOSTS"; | |
my $deny_flag = 0; | |
my @lines; | |
while (my $line = <$fh>) { | |
chomp $line; | |
if ($line eq $START_TOKEN) { | |
$deny_flag = 1; | |
} elsif ($line eq $END_TOKEN) { | |
$deny_flag = 0; | |
} else { | |
push @lines, $line if $deny_flag == 0; | |
} | |
} | |
close $fh; | |
open my $wfh, ">", $HOSTS or croak "Can't open $HOSTS"; | |
print {$wfh} "$_\n" for @lines; | |
close $wfh; | |
rehash(); | |
} | |
sub is_work_mode { | |
open my $fh, "<", $HOSTS or croak "Can't open $HOSTS"; | |
my $content = do { | |
local $/; | |
<$fh>; | |
}; | |
close $fh; | |
if ($content =~ m{$START_TOKEN}ms && $content =~ m{$END_TOKEN}ms) { | |
return 1; | |
} | |
return 0; | |
} | |
sub run { | |
$_[0]->(); | |
} | |
sub _usage { | |
croak("Usage: $0 [work|play]"); | |
} | |
package main; | |
use strict; | |
use warnings; | |
unless (caller) { | |
my $app = App::GetShitDone->new(@ARGV); | |
$app->run; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment