#!/usr/bin/env perl

# Some tests for 'darcs rec --edit-long-comment'

use lib 'lib/perl';
use Test::More 'no_plan';
use Test::Darcs;
use strict;
use warnings;
use File::Path;
use File::Slurp;
use File::Temp 'tempdir';
chdir tempdir( CLEANUP => 1 );

my $GREP  = `which grep`;
chomp $GREP;

sub init_dir {
  my $d = shift;
  my $dq = shift;
  cleanup $d;
  mkdir $d;
  chdir $d;
  darcs 'init';
  write_file('file.t',"FIRST LINE\n");
  darcs 'add file.t';
}

sub clean_dir {
  my $d = shift;
   chdir '../';
   rmtree($d);
   ok((!-d $d), 'temp1 directory was deleted');
}

if ($^O =~ /win/i or $^O =~ /msys/i) {
  pass 'test does not work on windows';
} else {
  $ENV{DARCS_EDITOR}="/bin/cat -n";

  my $test_name = 'editor: space in command';

  init_dir('temp1');
  like(darcs('record --edit-long-comment -a -m foo file.t'), qr/2.*END OF DESCRIPTION/i, $test_name);
  clean_dir('temp1');

  $test_name = 'editor: space in path';

  my $d = 'temp2 dir';
  init_dir($d);
  like(darcs('record --edit-long-comment -a -m foo file.t'), qr/2.*END OF DESCRIPTION/i, $test_name);
  clean_dir($d);


  $ENV{DARCS_EDITOR}=${GREP}.' "END OF"';

  $test_name = 'editor: quoting in command';

  init_dir('temp1','temp1');
  like(darcs('record --edit-long-comment -a -m foo file.t'), qr/END OF/i, $test_name);
  clean_dir('temp1','temp1');

  $ENV{DARCS_EDITOR}='/bin/echo';

  $test_name = 'editor: evil filename';

  init_dir('temp1','temp1');
  `touch '; test-command'`;
  `printf "#!/bin/sh\necho EVIL" > test-command`;
  `chmod u+x test-command`;
  my $op = darcs(qw(record --logfile='; test-command' --edit-long-comment -a -m foo file.t));
  unlike($op, qr/EVIL/i, $test_name);
  clean_dir('temp1','temp1');
}
