package Test::Snapshot;
use 5.008001;
use strict;
use warnings;
use Test2::API qw(context test2_add_callback_pre_subtest);
use Exporter 'import';
require Carp;
require File::Spec;
require File::Path;
require File::Basename;
require Data::Dumper;
use Text::Diff;

our $VERSION = "0.061";
our @EXPORT = qw(is_deeply_snapshot);

# capture subtest names
test2_add_callback_pre_subtest(sub {
  my ($name, $code, @args) = @_;
  my $ctx = context();
  my $hub = $ctx->hub;
  my @existing = @{$hub->get_meta('Test::Snapshot::subtest_names') // []};
  push @existing, $name;
  $hub->set_meta('Test::Snapshot::subtest_names', \@existing);
  $ctx->release;
});

sub is_deeply_snapshot {
  my ($got, $description) = @_;
  my $ctx = context();
  my $expected = "undef\n";
  my $filename = _get_filename($ctx, $description);
  if (-f $filename) {
    no strict;
    local $@;
    $expected = eval { _read_file($filename) };
    $ctx->diag("Error in snapshot '$filename': $@") if $@;
  } else {
    $ctx->diag("No snapshot filename '$filename' found");
  }
  my $dumper = Data::Dumper->new([$got]);
  $dumper->Indent(1)->Terse(1);
  $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
  my $dump = $dumper->Dump;
  my $result = $dump eq $expected;
  if ($result) {
    $ctx->pass($description);
  } else {
    $ctx->fail($description);
    $ctx->diag(diff \$expected, \$dump);
    if ($ENV{TEST_SNAPSHOT_UPDATE}) {
      _make_dir_for($filename);
      _write_file($filename, $dump);
    }
  }
  $ctx->release;
  $result;
}

sub _get_filename {
  my ($ctx, $description) = @_;
  Carp::croak("No description given") if !defined $description;
  my @stack = map $_->get_meta('Test::Snapshot::subtest_names'), $ctx->stack->all;
  @stack = map @$_, grep $_, @stack;
  my $topfile = $0;
  my ($v, $d, $f) = File::Spec->splitpath(File::Spec->rel2abs($topfile));
  unshift @stack, $f;
  push @stack, $description;
  @stack = map { my $t = $_; $t =~ s#[^a-z\-0-9]+#_#gi; $t } @stack;
  my $basename = pop @stack;
  File::Spec->catpath(
    $v,
    File::Spec->catdir($d, 'snapshots', @stack),
    $basename,
  );
}

sub _read_file {
  my ($filename) = @_;
  local $/;
  open my $fh, '<', $filename or die "$filename: $!\n";
  <$fh>;
}

sub _write_file {
  my ($filename, $data) = @_;
  open my $fh, '>', $filename or die "$filename: $!\n";
  print $fh $data or die "$filename: $!\n";
}

sub _make_dir_for {
  my ($filename) = @_;
  my $dir = File::Basename::dirname($filename);
  File::Path::make_path($dir); # will croak if fails
}

=encoding utf-8

=head1 NAME

Test::Snapshot - test against data stored in automatically-named file

=begin markdown

# PROJECT STATUS

| OS      |  Build status |
|:-------:|--------------:|
| Linux   | [![Build Status](https://travis-ci.org/mohawk2/Test-Snapshot.svg?branch=master)](https://travis-ci.org/mohawk2/Test-Snapshot) |

[![CPAN version](https://badge.fury.io/pl/Test-Snapshot.svg)](https://metacpan.org/pod/Test::Snapshot)

=end markdown

=head1 SYNOPSIS

  use Test::Snapshot;
  my $got = function_generating_data();
  is_deeply_snapshot $got, 'test description'; # could also be in a subtest

  # command line:
  TEST_SNAPSHOT_UPDATE=1 prove -lr t
  # or
  TEST_SNAPSHOT_UPDATE=1 make test
  # if your code means the expected data should change, then inspect with
  git diff -w

=head1 DESCRIPTION

Not connected with L<Test::Snapshots>, which is based on a similar
concept but for running executables.

As of 0.061, supports use under L<Test2::V0>.

Implements a function to automate the storing and updating of expected
test outputs. This is based on the idea known in frontend development
circles as "snapshot testing", hence the module name.

These snapshots will be stored in files whose names are automatically
generated from:

=over

=item the test filename (C<$0>)

=item any subtests' names surrounding and including this one

=item the test description if any

=back

If that file is not present, it will be treated as though it contains
an C<undef>.

=head1 FUNCTIONS

=head2 is_deeply_snapshot

Exported by default. Takes two mandatory arguments:

=over

=item

The "got" data (mandatory), a scalar which might be a reference. It will
be passed to L<Test::More/is_deeply> to be compared to the snapshotted
data.

=item

A text description of this test (mandatory). It will be used for reporting
results, but also to derive the filename in which the "expected" data
is stored.

=back

Will return the truth value of whether the test passed this time -
see below for automatic updating of "expected" data.

=head1 ENVIRONMENT

To have this module automatically update its "expected" data, set
environment variable C<TEST_SNAPSHOT_UPDATE> to a true value. If the
got and expected data do not match, a test failure will be reported,
but the "expected" data will be updated anyway.

This means it is safe to always have the variable set to a true value,
so long as you are using source control (you I<are> using source control,
right?) and check your diffs before committing.

=head1 FILE FORMAT

The "expected" data will be stored in a format generated by
L<Data::Dumper/Dumper>, with these values set to true, to maximise
readability (and to minimise diffs) of the stored data:

=over

=item Sortkeys

=item Indent

=item Terse

=back

=head1 AUTHOR

Ed J, C<< <etj at cpan.org> >>

=head1 LICENSE

Copyright (C) Ed J

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

=cut

1;
