AnyEvent-MCP
view release on metacpan or search on metacpan
lib/AnyEvent/MCP.pm view on Meta::CPAN
checks, if required.
Context must match exactly: apply with fuzz zero. For each hunk,
C<$max_offset> permits relocation by at most the number of distinct old-side
lines minus one, or zero for a pure insertion. Repeated old-side lines do
not increase this allowance. The applier must enforce these limits; an
unrestricted search for matching context can select the wrong occurrence.
For live Vim buffers, also require the expected changedtick to match.
File-based users need an equivalent check before replacing the file.
To work around GNU patch's handling of asymmetric context, the
first context line of each hunk is rewritten as an identity
removal/addition. The line contents and old/new line counts are
unchanged. This is normalization for the patch applier, not a relaxation
of context matching.
=over
=item ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff $diff
Normalizes a relaxed, single-file unified diff into ordinary unified diff
syntax. Returns the normalized C<$diff> and an array reference C<$max_offset>
containing the permitted whole-hunk relocation for each hunk, in order.
Dies on malformed hunks or when no hunks are found.
Here is a suitable description for the diff format, e.g. in a tool
definition:
Apply a unified diff to one regular file. Hunk counts are recomputed,
fuzz is disabled, whole-hunk relocation is limited per hunk by distinct
old-side lines. Pure insertion is allowed only at the beginning;
elsewhere include old-side context.
=item $cv = AnyEvent::MCP::apply_udiff $input, $output, $diff
Asynchronously applies the relaxed C<$diff> to the input file C<$input>,
writing a separate output file C<$output>. C<$diff> must contain bytes;
callers working with characters must encode them for the file themselves.
Normalizes the diff, runs GNU patch using C<AnyEvent::Util::run_cmd>, and
validates its verbose output with C<check_patch_output>. The command uses
batch/forward mode, binary mode and fuzz zero. No shell is involved.
C<$output> must not exist. It is reserved with mode 0600; patch runs in its
directory so incidental temporary files stay there. Input and output paths
are made absolute before starting the command. These must be trusted paths
in a directory controlled by the caller.
Returns a condition variable. Its C<recv> returns the validated hunk array
reference, or throws on command/application failure. Setup failures throw
synchronously. Failed or partial output is removed. C<$input> is unchanged.
The caller owns committing the successful output and removing it when no
longer needed. Freshness checks, metadata preservation, atomic replacement
and application-specific permissions also belong to the caller.
For your reference, the exact options used are:
--verbose --batch --forward --binary --fuzz=0
--no-backup-if-mismatch
--reject-file=- --output=... -- <inputfile>
=item $parsed = AnyEvent::MCP::parse_patch_output $output
Parses C<LC_ALL=C> GNU patch C<--verbose> output without judging whether
the application is acceptable. C<$parsed> has two fields:
=over
=item hunks => [$hunk...]
Hunk records in output order. Each record contains C<hunk> (the one-based
number), C<success>, C<line> (the reported application line), C<fuzz> and
the signed C<offset>. Omitted fuzz and offset are zero. Failed and ignored
hunks have false C<success>.
=item unparsed => [$line...]
Lines not recognized as hunk results or GNU patch's verbose framing.
The parser preserves them for callers to interpret or reject.
=back
Use verbose output: ordinary patch output omits exact-position successes,
so it cannot account for every hunk.
=item $hunks = AnyEvent::MCP::check_patch_output $status, $output, [$max_offset...]
Parses C<$output> and validates a complete application. C<$status> is the
raw process wait status, as returned by C<waitpid> or
C<AnyEvent::Util::run_cmd>, not just the exit code.
Requires status zero, no unrecognized output, exactly the expected hunks
in numbered order, successful application, fuzz zero and each signed offset
within its corresponding absolute limit. C<[$max_offset...]> is the array
reference returned by C<normalize_udiff>. At least one hunk is required.
Returns the parsed hunk array reference on success; otherwise dies with a
diagnostic. This is also suitable for callers running patch inside their
own sandbox.
=back
=head1 SMALL UTILITIES
=over
=item $name = AnyEvent::MCP::instance_name ($name)
Validate an instance name, defaulting to C<default> if undefined. Names
start with an ASCII letter, digit or underscore, followed by letters,
digits, underscores, hyphens, dots, C<@> and C<+>. This intentionally
small character set is convenient to use unquoted in a shell.
=item $lock = AnyEvent::MCP::file_lock ($file)
Create the parent directory and state file if necessary, and obtain an
exclusive advisory lock. If another cooperating writer atomically replaced
the pathname while waiting, retry on the new inode. Keep the handle alive
through reading, modifying and replacing the file.
lib/AnyEvent/MCP.pm view on Meta::CPAN
|| /^Using Plan [AB]\.\.\.\z/ || /^done\z/) {
# GNU patch --verbose framing, not hunk results.
} else {
push @unparsed, $_;
}
}
{ hunks => \@hunks, unparsed => \@unparsed }
}
sub check_patch_output {
my ($status, $output, $max_offset) = @_;
my $parsed = parse_patch_output $output;
my $hunks = $parsed->{hunks};
die "patch failed (wait status $status):\n$output"
if $status;
die "patch: unrecognized output:\n" . (join "\n", @{$parsed->{unparsed}}) . "\n"
if @{$parsed->{unparsed}};
die "patch: expected " . @$max_offset . " hunks, got " . @$hunks . "\n"
unless @$hunks == @$max_offset && @$hunks;
for my $i (0 .. $#$hunks) {
my $hunk = $hunks->[$i];
die "patch: unexpected hunk number $hunk->{hunk}\n"
unless $hunk->{hunk} == $i + 1;
die "patch: hunk $hunk->{hunk} failed\n"
unless $hunk->{success};
die "patch: hunk $hunk->{hunk} used fuzz $hunk->{fuzz}\n"
if $hunk->{fuzz};
die "patch: hunk $hunk->{hunk} offset $hunk->{offset} exceeds $max_offset->[$i]\n"
if abs $hunk->{offset} > $max_offset->[$i];
}
$hunks
}
sub apply_udiff {
my ($input, $output, $diff) = @_;
my ($normalized, $max_offset) = normalize_udiff $diff;
require AnyEvent::Util;
require File::Spec;
require File::Basename;
require Fcntl;
$input = File::Spec->rel2abs ($input);
$output = File::Spec->rel2abs ($output);
my $directory = File::Basename::dirname ($output);
sysopen my $fh, $output, Fcntl::O_WRONLY () | Fcntl::O_CREAT () | Fcntl::O_EXCL (), 0600
or die "$output: $!\n";
close $fh or do { my $error = $!; unlink $output; die "$output: $error\n" };
my $cv = AE::cv ();
my $log;
my $process = eval {
AnyEvent::Util::run_cmd ([
"patch", "--verbose", "--batch", "--forward", "--binary", "--fuzz=0",
"--no-backup-if-mismatch", "--reject-file=-", "--output=$output", "--", $input,
],
"<" => \$normalized,
">" => \$log,
close_all => 1,
on_prepare => sub {
$ENV{LC_ALL} = "C";
chdir $directory or die "$directory: $!\n";
defined POSIX::dup2 (1, 2) or die "dup2: $!\n";
},
);
};
if ($@) {
my $error = $@;
unlink $output;
die $error;
}
$process->cb (sub {
my $hunks;
eval { $hunks = check_patch_output $_[0]->recv, $log, $max_offset; 1 } or do {
my $error = $@;
unlink $output;
$cv->croak ($error);
return;
};
$cv->send ($hunks);
});
$cv
}
sub _clean_text($) {
my ($text) = @_;
my ($prefix) = (join "\n", grep /\S/, split /\n/, $text)
=~ /\A([ \t]*)[^\n]*(?:\n\1[^\n]*)*\z/;
$text =~ s/^\Q$prefix\E//mg;
$text =~ s/\A\s+//;
$text =~ s/\s+\z//;
$text
}
package AnyEvent::MCP::Base;
sub new {
my ($class, %kv) = @_;
bless \%kv, $class
}
sub event {
my ($self, $event, @args) = @_;
($self->{"on_$event"} or return)->($self, @args)
}
=head1 SEE ALSO
( run in 0.704 second using v1.01-cache-2.11-cpan-99fa8243a42 )