Skip to content

Instantly share code, notes, and snippets.

@district10
Created August 25, 2017 15:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save district10/d46a0e207d888d0526aef94fb8d8998c to your computer and use it in GitHub Desktop.
Save district10/d46a0e207d888d0526aef94fb8d8998c to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
# Based on: https://github.com/district10/cat/blob/master/bin/cat.pl
# Usage:
# perl unfold.pl INPUT_FILE > OUTPUT_FILE
# Inclusion syntax:
# <<[input_file.md]
use 5.010;
use strict;
use warnings;
use File::Basename;
use Cwd 'abs_path';
sub duplicates {
my $needle = shift;
my @haystack = @_;
foreach my $hay (@haystack) {
if ($needle eq $hay) { return 1; }
}
return 0;
}
sub unfold {
my $pd = shift;
my $fn = shift;
if (! -f $fn) {
print STDERR "Error openning file: [".$fn."].\n";
print $pd."Error openning file: [".$fn."].\n";
return;
}
my $ap = abs_path($fn);
open my $fh, '<', $fn or return;
if (&duplicates($ap, @_) == 1) {
while(<$fh>) {
s/\r?\n?$//;
print $pd.$_."\n";
}
} else {
unshift(@_, $ap);
my $dn = dirname($ap);
while(<$fh>) {
s/\r?\n?$//;
if (/^(\s*)<<\[(.*)\]$/) {
my $p = $1; my $f = $2;
$f = $dn."/".$f unless $f =~ /^.:/ or $f =~ /^\//;
&unfold($pd.$p, $f, @_);
} else {
print $pd.$_."\n";
}
}
}
}
if (-f $ARGV[0]) {
&unfold("", $ARGV[0]);
} else {
print STDERR "Error openning file: [".$ARGV[0]."].\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment