Skip to content

Instantly share code, notes, and snippets.

@tateisu
Created January 24, 2023 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tateisu/300c046e02f53829c5ef91958d737aa8 to your computer and use it in GitHub Desktop.
Save tateisu/300c046e02f53829c5ef91958d737aa8 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl --
use strict;
use warnings;
use feature qw(say);
use Getopt::Long;
my $verbose =0;
GetOptions(
"verbose|v:+" => \$verbose,
) or die "bad options.";
# systemやcloseの結果を整形する
sub cmdResult($){
my($rv)=@_;
if( $rv == 0 ){
return;
}elsif( $rv == -1 ){
return "failed to execute: $!";
}elsif ( $rv & 127 ) {
return sprintf "signal %d", ($rv & 127);
}else {
return sprintf "exitCode %d",($rv>>8);
}
}
sub cmd($){
system $_[0];
my $error = cmdResult $?;
$error and die "$error cmd=$_[0]";
}
sub chdirOrThrow($){
my($dir)=@_;
chdir($dir) or die "chdir failed. $dir $!";
}
sub cmdRead($&){
my($cmd,$block)=@_;
open(my $fh, "-|", "$cmd 2>&1") or die "can't fork. $!";
local $_;
while(1){
$_ = <$fh>;
last if not defined $_;
$block->();
}
if(not close($fh) ){
my $e1 = $!;
my $e2 = cmdResult $?;
die "execute failed. $e1 $e2";
}
}
chdirOrThrow "/dir/has/docker-compose-yml";
sub filterLog($){
for( split /[\x0d\x0a]+|\x1b\[\d[ABK]/ ){
s/\x1b\[\d{1,2}m//g;
if(not $verbose){
s/\A(Creating|Stopping|Removing) \S+\s+\.\.\. (done)?\z//;
s/\ARemoving network \S+\z//;
s/\ACreating network "\S+" with the default driver\z//;
}
length($_) and say "[$_]";
}
}
cmdRead "docker-compose down",sub{ filterLog($_) };
cmdRead "docker-compose up -d",sub{ filterLog($_) };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment