#!/usr/pkg/bin/ruby25
#
# This script reads NDJSON-encoded Cucumber events from STDIN and prints
# the location of each pickle (scenario) matching a tag expression. If
# no tag expression is specified, all pickle locations are printed.
#
# Example:
#
#    gherkin features/*.feature | cucumber-tag-expressions "@foo and not @bar"
#
require 'json'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"../lib"))
require 'cucumber/tag_expressions'

tag_expression_parser = Cucumber::TagExpressions::Parser.new
tag_expression = ARGV[0] ? tag_expression_parser.parse(ARGV[0]) : nil

STDIN.each do |json|
  event = JSON.parse(json)
  if event['type'] == 'pickle'
    tag_names = event['pickle']['tags'].map {|tag| tag['name']}
    if tag_expression.nil? || tag_expression.evaluate(tag_names)
      location = "#{event['uri']}:#{event['pickle']['locations'][0]['line']}"
      puts location
    end
  end
end
