From b1db1b44ea1725f90e4ff11d50fbf63e8479f1a7 Mon Sep 17 00:00:00 2001
From: Eric Wong <e@80x24.org>
Date: Wed, 15 Jun 2016 00:14:23 +0000
Subject: [PATCH] learn: remove IPC::Run dependency

We'll be relying on our spawn implementation, for now;
since it'll be consistent with the rest of our code and
can optionally take advantage of vfork.
---
 script/public-inbox-learn | 36 ++++++++++++++++++++++++------------
 1 file changed, 24 insertions(+), 12 deletions(-)

diff --git a/script/public-inbox-learn b/script/public-inbox-learn
index bfbf0233..783cf03a 100755
--- a/script/public-inbox-learn
+++ b/script/public-inbox-learn
@@ -14,17 +14,35 @@ use Email::MIME;
 use Email::MIME::ContentType;
 $Email::MIME::ContentType::STRICT_PARAMS = 0; # user input is imperfect
 use PublicInbox::Address;
-use IPC::Run qw/run/;
+use PublicInbox::Spawn qw(spawn);
 my $train = shift or die "usage: $usage\n";
 if ($train !~ /\A(?:ham|spam)\z/) {
 	die "`$train' not recognized.\nusage: $usage\n";
 }
 
 my $pi_config = PublicInbox::Config->new;
+my $err;
 my $mime = Email::MIME->new(eval {
 	local $/;
 	my $data = scalar <STDIN>;
 	$data =~ s/\AFrom [^\r\n]*\r?\n//s;
+	eval {
+		my @cmd = (qw(spamc -L), $train);
+		my ($r, $w);
+		pipe($r, $w) or die "pipe failed: $!";
+		open my $null, '>', '/dev/null' or
+					die "failed to open /dev/null: $!";
+		my $nullfd = fileno($null);
+		my %rdr = (0 => fileno($r), 1 => $nullfd, 2 => $nullfd);
+		my $pid = spawn(\@cmd, undef, \%rdr);
+		close $null;
+		close $r or die "close \$r failed: $!";
+		print $w $data or die "print \$w failed: $!";
+		close $w or die "close \$w failed: $!";
+		waitpid($pid, 0);
+		die "spamc failed with: $?\n" if $?;
+	};
+	$err = $@;
 	$data
 });
 
@@ -43,14 +61,10 @@ if ($train eq "ham") {
 	PublicInbox::Filter->run($mime);
 }
 
-my $err = 0;
-my @output = qw(> /dev/null > /dev/null);
-
 # n.b. message may be cross-posted to multiple public-inboxes
 foreach my $recipient (keys %dests) {
 	my $dst = $pi_config->lookup($recipient) or next;
 	my $git_dir = $dst->{mainrepo} or next;
-	my ($out, $err) = ("", "");
 	my $git = PublicInbox::Git->new($git_dir);
 	# We do not touch GIT_COMMITTER_* env here so we can track
 	# who trained the message.
@@ -74,15 +88,13 @@ foreach my $recipient (keys %dests) {
 		$im->add($mime);
 	}
 	$im->done;
-	my $in = $mime->as_string;
-	if (!run([qw(spamc -L), $train], \$in, @output)) {
-		$err = 1;
-	}
-
-	$err or eval {
+	eval {
 		require PublicInbox::SearchIdx;
 		PublicInbox::SearchIdx->new($git_dir, 2)->index_sync;
 	};
 }
 
-exit $err;
+if ($err) {
+	warn $err;
+	exit 1;
+}
-- 
2.50.0