Dotfiles, utilities, and other apparatus.

filter-exec 778B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #!/usr/bin/env perl
  2. # Execute shell commands and include their output in the current buffer,
  3. # formatted as an indented code block with the original command, in Markdown.
  4. #
  5. # See also: filter-exec-raw for unformatted output without the original
  6. # command.
  7. use strict;
  8. use warnings;
  9. use 5.10.0;
  10. my $startmarker = '<!-- exec -->';
  11. my $endmarker = '<!-- end -->';
  12. my $text;
  13. {
  14. # line separator:
  15. local $/ = undef;
  16. $text = <>;
  17. }
  18. $text =~ s{$startmarker(.*?)$endmarker}{handle_block($1);}egs;
  19. print $text;
  20. sub handle_block {
  21. my ($block) = @_;
  22. my $cmd;
  23. if ($block =~ m/\$ (.*?)$/m) {
  24. $cmd = $1;
  25. } else {
  26. die "bogus cmd";
  27. }
  28. my $result = `$cmd`;
  29. $result =~ s/^/ /gm;
  30. return "$startmarker\n\n \$ " . $cmd . "\n" . $result . "\n$endmarker";
  31. }