Created
August 25, 2017 15:51
-
-
Save district10/d46a0e207d888d0526aef94fb8d8998c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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