Dotfiles, utilities, and other apparatus.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.2 KiB

  1. #!/usr/bin/env perl
  2. # Execute shell commands with the included block passed to their stdin.
  3. #
  4. # I haven't wound up using this much, but in principle it has some
  5. # applications.
  6. #
  7. # See also: filter-exec, filter-exec-raw.
  8. use strict;
  9. use warnings;
  10. use 5.10.0;
  11. use IPC::Cmd qw(can_run run_forked);
  12. my $text;
  13. {
  14. # line separator:
  15. local $/ = undef;
  16. $text = <>;
  17. }
  18. $text =~ s{
  19. <!--[ ]exec-stdin[ ](.*?)[ ]-->\n
  20. (.*?)\n
  21. <!--[ ]end[ ]-->
  22. }{
  23. handle_block($1, $2);
  24. }egsx;
  25. print $text;
  26. sub handle_block {
  27. my ($command, $input) = @_;
  28. my $output_text = '';
  29. my $result = run_forked($command, {
  30. child_stdin => $input,
  31. timeout => 300,
  32. stdout_handler => sub { $output_text .= $_[0]; },
  33. stderr_handler => sub { $output_text .= $_[0]; }
  34. });
  35. # Kill any trailing newlines so that the output will fit between markers
  36. # without adding a blank line (something about this will probably lead to
  37. # bugs eventually):
  38. chomp($output_text);
  39. my $starter = 'exec-stdin';
  40. return "<!-- $starter $command -->\n$output_text\n<!-- end -->";
  41. }
  42. __DATA__
  43. A self-test - add some numbers and use ,r in vim to check:
  44. <!-- exec-stdin sort -n -->
  45. 1
  46. 2
  47. 8
  48. 9
  49. 10
  50. <!-- end -->