#!/usr/bin/env perl
package yq;
{
  $yq::VERSION = '0.011';
}
# ABSTRACT: Filter YAML through a command-line program

use App::YAML::Filter::Base;
use Pod::Usage::Return qw( pod2usage );
use Getopt::Long qw( GetOptionsFromArray );
use YAML;
use boolean qw( :all );
use Regexp::Common;

$|++; # no buffering

our $VERBOSE = $ENV{YQ_VERBOSE} // 0;

sub empty() {
    bless {}, 'empty';
}
sub is_empty {
    return ref $_[0] eq 'empty';
}

sub main {
    my ( $class, @argv ) = @_;
    my %opt;
    GetOptionsFromArray( \@argv, \%opt,
        'help|h',
        'verbose|v+',
        'version',
    );
    return pod2usage(0) if $opt{help};
    if ( $opt{version} ) {
        print "yq version $yq::VERSION (Perl $^V)\n";
        return 0;
    }

    $VERBOSE //= $opt{verbose};

    my $filter = shift @argv;
    return pod2usage("ERROR: Must give a filter") unless $filter;

    push @argv, "-" unless @argv;
    for $ARGV ( @argv ) {
        # We're doing a similar behavior to <>, but manually for easier testing.
        my $fh;
        if ( $ARGV eq '-' ) {
            # Use the existing STDIN so tests can fake it
            $fh = \*STDIN;
        }
        else {
            unless ( open $fh, '<', $ARGV ) {
                warn "Could not open file '$ARGV' for reading: $!\n";
                next;
            }
        }

        my $buffer;
        my $scope = {};
        while ( my $line = <$fh> ) {
            # --- is the start of a new document
            if ( $buffer && $line =~ /^---/ ) {
                # Flush the previous document
                my @output = $class->filter( $filter, YAML::Load( $buffer ), $scope );
                $class->write( @output );
                $buffer = '';
            }
            $buffer .= $line;
        }
        # Flush the buffer in the case of a single document with no ---
        if ( $buffer =~ /\S/ ) {
            #print STDERR "Buffer is: $buffer\n";
            my @output = $class->filter( $filter, YAML::Load( $buffer ), $scope );
            $class->write( @output );
        }

        # Finish the scope, cleaning up any collections
        $class->write( $class->finish( $scope ) );
    }

    return 0;
}

sub write {
    my ( $class, @docs ) = @_;
    for my $doc ( @docs ) {
        next if is_empty( $doc );
        if ( isTrue( $doc ) ) {
            print YAML::Dump( "true" );
        }
        elsif ( isFalse( $doc ) ) {
            print YAML::Dump( "false" );
        }
        else {
            print YAML::Dump( $doc );
        }
    }
}

sub diag {
    my ( $level, $text ) = @_;
    print STDERR "$text\n" if $VERBOSE >= $level;
}

my $QUOTE_STRING = $RE{delimited}{-delim=>q{'"}};
my $EVAL_NUMS = qr{(?:0b$RE{num}{bin}|0$RE{num}{oct}|0x$RE{num}{hex})};

# Match a document path
my $FILTER = qr{
        [.] # entire document
        |
        (?:[.](?:\w+|\[\d*\]))+ # hash/array lookup
        |
        $QUOTE_STRING
        |
        $RE{num}{real}|$EVAL_NUMS
        |
        \w+ # Constant/bareword
    }x;
my $OP = qr{eq|ne|==|!=};
my $FUNC_NAME = qr{empty|select|grep|group_by};
my $EXPR = qr{
    \{(\s*$FILTER\s*:\s*(?0)\s*(?:,(?-1))*)\} # Hash constructor
    |
    \[(\s*(?0)\s*(?:,(?-1))*)\] # Array constructor
    |
    $FUNC_NAME(?:\(\s*(?0)\s*\))? # Function with optional argument
    |
    $FILTER\s+$OP\s+$FILTER # Binary operator
    |
    $FILTER
}x;
my $PIPE = qr{[|]};

# Filter MUST NOT mutate $doc!
sub filter {
    my ( $class, $filter, $doc, $scope ) = @_;
    if ( $filter =~ $PIPE ) {
        my @exprs = split /\s*$PIPE\s*/, $filter;
        my @in = ( $doc );
        for my $expr ( @exprs ) {
            my @out = ();
            for my $doc ( @in ) {
                push @out, $class->filter( $expr, $doc, $scope );
            }
            @in = @out;
        }
        return @in;
    }
    # Hash constructor
    elsif ( $filter =~ /^{/ ) {
        my %out;
        my ( $inner ) = $filter =~ /^\{\s*([^\}]+?)\s*\}$/;
        for my $pair ( split /\s*,\s*/, $inner ) {
            my ( $key_filter, $value_expr ) = split /\s*:\s*/, $pair;
            my $key = $class->filter( $key_filter, $doc );
            $out{ $key } = $class->filter( $value_expr, $doc );
        }
        return \%out;
    }
    elsif ( $filter =~ /^\[/ ) {
        my @out;
        my ( $inner ) = $filter =~ /^\[\s*([^\]]+?)\s*\]$/;
        for my $value_expr ( split /\s*,\s*/, $inner ) {
            push @out, $class->filter( $value_expr, $doc );
        }
        return \@out;
    }
    # , does multiple filters, yielding multiple documents
    elsif ( $filter =~ /,/ ) {
        my @filters = split /\s*,\s*/, $filter;
        return map { $class->filter( $_, $doc ) } @filters;
    }
    elsif ( $filter =~ /^($FUNC_NAME)(?:\(\s*($EXPR)\s*\))?$/ ) {
        my ( $func, $expr ) = ( $1, $2 );
        if ( $func eq 'empty' ) {
            if ( $expr ) {
                warn "empty does not take arguments\n";
            }
            return empty;
        }
        elsif ( $func eq 'select' || $func eq 'grep' ) {
            if ( !$expr ) {
                warn "'$func' takes an expression argument";
                return empty;
            }
            return $class->filter( $expr, $doc ) ? $doc : empty;
        }
        elsif ( $func eq 'group_by' ) {
            my $grouping = $class->filter( $expr, $doc );
            push @{ $scope->{ group_by }{ $grouping } }, $doc;
            return;
        }
    }
    # Hash and array keys to traverse the data structure
    elsif ( $filter =~ /^($FILTER)$/ ) {
        # Extract quoted strings
        if ( $filter =~ /^(['"])(.+)(\1)$/ ) {
            return $2;
        }
        # Eval numbers to allow bin, hex, and oct
        elsif ( $filter =~ /^$EVAL_NUMS$/ ) {
            ## no critic ( ProhibitStringyEval )
            return eval $filter;
        }
        # Constants/barewords do not begin with .
        elsif ( $filter !~ /^[.]/ ) {
            # If it's not a reserved word, it's a string
            # XXX: This is a very poor decision...
            return $filter;
        }
        my @keys = split /[.]/, $filter;
        my $subdoc = $doc;
        for my $key ( @keys[1..$#keys] ) {
            if ( $key =~ /^\[\]$/ ) {
                return @{ $subdoc };
            }
            elsif ( $key =~ /^\[(\d+)\]$/ ) {
                $subdoc = $subdoc->[ $1 ];
            }
            elsif ( $key =~ /^\w+$/ ) {
                $subdoc = $subdoc->{ $key };
            }
            else {
                die "Invalid filter key '$key'";
            }
        }
        return $subdoc;
    }
    elsif ( $filter =~ /^($FILTER)\s+($OP)\s+($FILTER)$/ ) {
        my ( $lhs_filter, $cond, $rhs_filter ) = ( $1, $2, $3 );
        my $lhs_value = $class->filter( $lhs_filter, $doc );
        my $rhs_value = $class->filter( $rhs_filter, $doc );
        diag( 1, join " ", "BINOP:", $lhs_value // '<undef>', $cond, $rhs_value // '<undef>' );
        if ( $cond eq 'eq' ) {
            return defined $lhs_value == defined $rhs_value 
                && $lhs_value eq $rhs_value
                ? true : false;
        }
        elsif ( $cond eq 'ne' ) {
            return defined $lhs_value != defined $rhs_value
                || $lhs_value ne $rhs_value ? true : false;
        }
        elsif ( $cond eq '==' ) {
            return defined $lhs_value == defined $rhs_value
                && $lhs_value == $rhs_value ? true : false;
        }
        elsif ( $cond eq '!=' ) {
            return defined $lhs_value != defined $rhs_value
                || $lhs_value != $rhs_value ? true : false;
        }
    }
    # If/then (future: else, better conditions)
    # NOTE: If we're capturing using $EXPR, then we _must_ use named captures,
    # because $EXPR has captures in itself
    elsif ( $filter =~ /^if\s+(?<expr>$EXPR)\s+then\s+(?<true>$FILTER)(?:\s+else\s+(?<false>$FILTER))?$/ ) {
        my ( $expr, $true_filter, $false_filter ) = @+{qw( expr true false )};
        my $expr_value = $class->filter( $expr, $doc );
        if ( $expr_value ) {
            return $class->filter( $true_filter, $doc );
        }
        else {
            return $false_filter ? $class->filter( $false_filter, $doc ) : ();
        }
    }
    else {
        die "Could not parse filter '$filter'\n";
    }
    return;
}

sub finish {
    my ( $class, $scope ) = @_;
    return $scope->{group_by} if ( $scope->{group_by} );
    return;
}

exit __PACKAGE__->main( @ARGV ) unless caller(0);

__END__

=pod

=head1 NAME

yq - Filter YAML through a command-line program

=head1 VERSION

version 0.011

=head1 SYNOPSIS

    yq [-v] <script> [<file>...]

    yq -h|--help|--version

=head1 DESCRIPTION

This program takes a stream of YAML documents (on STDIN or file arguments),
applies a filter, then writes the results to STDOUT.

=head1 ARGUMENTS

=head2 script

The script to run. For the script syntax, see L<SYNTAX>.

=head2 <file>

A YAML file to filter. The special file "-" refers to STDIN. If no files are
specified, filter STDIN.

=head1 OPTIONS

=head2 -v | --verbose

Set verbose mode to print out some internal program messages on STDERR to help
with debugging.

=head2 -h | --help

Show this help document.

=head2 --version

Print the current yq and Perl versions.

=head1 SYNTAX

=head2 EXPRESSIONS

An C<EXPRESSION> is allowed to be either a L<FILTER>, L<VALUE>, or a L<COMPARISON>.

=head2 FILTERS

Filters select a portion of the incoming documents. Filters can be combined
to reach deep inside the documents you're working with.

=over

=item .

Returns the entire document, unfiltered. Useful in if/then statements.

    # INPUT
    foo: bar
    baz: fuzz

    $ yq .
    foo: bar
    baz: fuzz

=item .key

Extract a single item out of a hash.

    # INPUT
    foo:
        bar: baz
        fizz: fuzz

    $ yq .foo
    bar: baz
    fizz: fuzz

    $ yq .foo.fizz
    fuzz

=item .[#]

Extract a single item out of an array.

    # INPUT
    - foo: fuzz
    - bar: buzz
    - baz:
        good: bad
        new: old

    $ yq .[1]
    bar: buzz

    $ yq .[2]
    baz:
        good: bad
        new: old

    $ yq .[2].baz
    good: bad
    new: old

    $ yq .[2].baz.new
    old

=item []

Use [] with no index to flatten an array.

    # INPUT
    - foo: fuzz
    - bar: buzz

    $ yq '.[]'
    foo: fuzz
    ---
    bar: buzz

=back

=head2 VALUES

=over

=item 'STRING' "STRING"

Both single- and double-quoted strings are allowed. Using \ will escape
the string delimiter.

=item { KEY: EXPRESSION, ... }

The hash constructor. C<KEY> may be any C<FILTER> or a bare value.

    # INPUT
    foo: bar
    baz: fuzz
    ---
    foo: 1
    baz: 2

    $ yq '{ bar: .foo, .baz: foo }'
    bar: bar
    fuzz: foo
    ---
    2: foo
    bar: 1

=item [ EXPRESSION, ... ]

The array constructor.

    # INPUT
    foo: bar
    baz: fuzz
    ---
    foo: 1
    baz: 2

    $ yq '[ .foo, .baz ]'
    - bar
    - fuzz
    ---
    - 1
    - 2

=item empty

The special value empty suppresses printing of a document. Normally,
an undefined document will show up in the output as "--- ~". If your
filter instead yields empty, the document will not be printed at all.

This is especially useful in conditionals:

    # INPUT
    foo: bar
    baz: fuzz

    $ yq 'if .foo eq bar then . else empty'
    foo: bar
    baz: fuzz

    $ yq 'if .foo eq buzz then . else empty'
    $

... though see the C<grep()> function for a shorter way of writing this.

=item Values

Any bareword that is not recognized as a syntax element is treated as a value.
These barewords may only contain letters, numbers, and underscore.

B<NOTE>: This may be subject to change to only allow quoted strings and bare
numbers in a future version.

=back

=head2 COMPARISONS

=over

=item eq

String equals comparison. Returns true if both sides are equal to each other
when treated as a string.

The two sides may be L<FILTERS> or L<VALUES>.

    # INPUT
    foo: bar
    baz: fuzz
    buzz: fuzz

    $ yq '.foo eq bar'
    true

    $ yq '.baz eq .buzz'
    true

    $ yq '.baz eq bar'
    false

YAML treats the string "true" as a true value, and the string "false" as a
false value.

=item ne

String not equals comparison. Returns true if one side is not equal to the
other side when compared as a string.

The two sides may be L<FILTERS> or L<VALUES>.

    # INPUT
    foo: bar
    baz: fuzz
    buzz: fuzz

    $ yq '.foo eq bar'
    true

    $ yq '.baz eq .buzz'
    true

    $ yq '.baz eq bar'
    false

YAML treats the string "true" as a true value, and the string "false" as a
false value.

=back

=head2 FUNCTIONS

=over

=item grep( EXPRESSION )

If C<EXPRESSION> is true, return the current document. Otherwise, return C<empty>.

This is exactly the same as:

    if EXPRESSION then . else empty

=item select( EXPRESSION )

Another name for C<grep()> to match C<jq>'s syntax.

=item group_by( EXPRESSION )

Group incoming documents based on the result of C<EXPRESSION>, yielding a single
document containing a hash of arrays.

    # INPUT
    ---
    foo: 'bar'
    baz: 1
    ---
    foo: 'bar'
    baz: 2
    ---
    foo: 'baz'
    baz: 3

    $ yq 'group_by( .foo )'
    bar:
        - foo: bar
          baz: 1
        - foo: bar
          baz: 2
    baz:
        - foo: baz
          baz: 3

NOTE: If you are filtering a lot of documents, this will consume a lot of memory.

=back

=head2 CONDITIONALS

=over

=item if EXPRESSION then TRUE_FILTER else FALSE_FILTER

If the C<EXPRESSION> is true, return the result of C<TRUE_FILTER>, otherwise
return the result of C<FALSE_FILTER>.

    # INPUT
    foo: bar
    baz: fuzz

    $ yq 'if .foo eq bar then .baz else .foo'
    fuzz

    $ yq 'if .foo eq buzz then .baz else .foo'
    bar

    $ yq 'if .foo then .baz'
    fuzz

    $ yq 'if .herp then .derp else .'
    foo: bar
    baz: fuzz

The C<else FALSE_FILTER> is optional and defaults to returning undefined.

=back

=head2 COMBINATORS

Combinators combine multiple expressions to yield one or more documents in the
output stream.

=over

=item ,

Multiple EXPRESSIONS may be separated by commas to yield multiple documents in the
output.

    # INPUT
    foo: bar
    baz: fuzz

    $ yq '.foo, .baz'
    bar
    ---
    fuzz

=item |

Multiple EXPRESSIONS may be separated by pipes to give the output of the left
expression as the input of the right expression (much like how shell pipes
work).

    # INPUT
    foo: bar
    baz: fuzz
    pop: more
    ---
    foo: buzz
    baz: fizz
    pop: jump

    $ yq '{ foo: .foo, val: .pop } | group_by( .foo )'
    bar:
        - foo: bar
          val: more
    buzz:
        - foo: buzz
          val: jump

The above example can be useful to avoid C<group_by> memory issues when dealing
with very large streams: Reduce the size of the working document by keeping
only the keys you want, then group those documents.

=back

=head1 ENVIRONMENT

=over

=item YQ_VERBOSE

Set the verbosity level. Useful when running the tests.

=back

=head1 SEE ALSO

=over

=item jq

L<http://stedolan.github.io/jq/> A filter for JSON documents. The inspiration
for this project.

=back

=head1 AUTHOR

Doug Bell <preaction@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by Doug Bell.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
