/* cmd-diff.c
 *
 * vim:smartindent ts=8:sts=2:sta:et:ai:shiftwidth=2
 ****************************************************************
 * Copyright (C) 2003 Tom Lord
 *
 * See the file "COPYING" for further information about
 * the copyright and warranty status of this work.
 */


#include "config-options.h"

#include "hackerlab/cmd/main.h"
#include "hackerlab/fs/file-names.h"
#include "hackerlab/os/errno.h"
#include "tla/libfsutils/rmrf.h"
#include "tla/libfsutils/tmp-files.h"
#include "tla/libarch/namespace.h"
#include "tla/libarch/project-tree.h"
#include "tla/libarch/patch-logs.h"
#include "tla/libarch/local-cache.h"
#include "tla/libarch/make-changeset.h"
#include "tla/libarch/changeset-report.h"
#include "tla/libarch/inode-sig.h"
#include "tla/libarch/chatter.h"
#include "tla/libarch/archive.h"
#include "tla/libarch/cmdutils.h"
#include "tla/libarch/cmd.h"
#include "tla/libarch/cmd-diff.h"
#include "tla/libarch/cmd-versions.h"
#include "tla/libarch/invent.h"


/* gettext support not yet incorporated into tla, reserve the gettext notation for later */
#define _(x) (x)
#define N_(x) (x)


/* __STDC__ prototypes for static functions */
static void make_changeset_callback (void * ign, char * fmt, va_list ap);



static t_uchar * usage = N_("[options] [revision] [-- files...]");
static t_uchar * version_string = (cfg__std__package " from regexps.com\n"
                                   "\n"
                                   "Copyright 2003 Tom Lord\n"
                                   "\n"
                                   "This is free software; see the source for copying conditions.\n"
                                   "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n"
                                   "PARTICULAR PURPOSE.\n"
                                   "\n"
                                   "Report bugs to " cfg__tla_bug_mail ".\n"
                                   "\n"
                                   cfg__std__release_id_string
                                   "\n");

#define OPTS(OP) \
  OP (opt_help_msg, "h", "help", 0, \
      N_("Display a help message and exit.")) \
  OP (opt_long_help, "H", 0, 0, \
      N_("Display a verbose help message and exit.")) \
  OP (opt_version, "V", "version", 0, \
      N_("Display a release identifier string and exit.")) \
  OP (opt_archive, "A", "archive", 1, \
      N_("Override `my-default-archive'.")) \
  OP (opt_dir, "d", "dir DIR", 1, \
      N_("Change to DIR first.")) \
  OP (opt_output_dir, "o", "output DIR", 1, \
      N_("Save changeset in DIR.")) \
  OP (opt_verbose, "v", "verbose", 0, \
      N_("Verbose changeset report.")) \
  OP (opt_quiet, "q", "quiet", 0, \
      N_("Suppress progress information")) \
  OP (opt_nodiffs, "s", "summary", 0, \
      N_("Do not include diffs in the output.")) \
  OP (opt_keep, "k", "keep", 0, \
      N_("Don't remove the output directory " \
      "on termination.")) \
  OP (opt_latest, "L", "latest", 0, \
      N_("compare against the latest revision (HEAD) in branch"))\
  OP (opt_exclude, "x", "exclude FILE", 1, \
      "exclude FILE from the files to commit") \
  OP (opt_hardlinks, 0, "link", 0, \
      N_("hardlink unchanged files to revision library"))\
  OP (opt_unescaped, 0, "unescaped", 0, \
      N_("show filenames in unescaped form"))\
  OP (opt_limit, 0, "limit LIMITS", 1, \
      N_("limit the diff to LIMITS")) \
  OP (opt_diff_opts, "D", "diff-options", 1, \
      N_("specify options for `diff' (for display only)"))


t_uchar arch_cmd_diff_help[] = N_("report about local changes in a project tree\n"
                                   "Generate a patch report describing the differences between the\n"
                                   "project tree containing DIR (or the current directory) and\n"
                                   "REVISION.\n"
                                   "\n"
                                   "The default patch level for a given version is the latest level for\n"
                                   "which the project tree has a patch.  The default archive and version\n"
                                   "is as printed by \"tla tree-version\".\n");

enum options
{
  OPTS (OPT_ENUM)
};

static struct opt_desc opts[] =
{
  OPTS (OPT_DESC)
    {-1, 0, 0, 0, 0}
};



int
arch_cmd_diff (t_uchar * program_name, int argc, char * argv[])
{
  int o;
  struct opt_parsed * option;
  t_uchar * dir = 0;
  t_uchar * output = 0;
  t_uchar * default_archive = 0;
  t_uchar ** diff_opts = 0;
  unsigned diff_opt_count = 0;
  t_uchar *limit_string = 0;
  int diffs = 1;
  int keep = 0;
  int verbose = 0;
  int quiet = 0;
  int exit_status = 0;
  int link_same = 0;
  int escape_classes = arch_escape_classes;
  int latest = 0;
  int files_specified = 0;
  rel_table exclude_list;
  dir = str_save (0, ".");
  exclude_list = rel_table_nil;

  safe_buffer_fd (1, 0, O_WRONLY, 0);

  option = 0;

  while (1)
    {
      if ((argc > 1) && !str_cmp ("--", argv[1]))
        break;

      o = opt_standard (lim_use_must_malloc, &option, opts, &argc, argv, program_name, usage,
      version_string, arch_cmd_diff_help, opt_help_msg, opt_long_help, opt_version);
      if (o == opt_none)
        break;
      switch (o)
        {
        default:
          safe_printfmt (2, "unhandled option `%s'\n", option->opt_string);
          panic ("internal error parsing arguments");

        usage_error:
          opt_usage (2, argv[0], program_name, usage, 1);
          exit (1);

          /* bogus_arg: */
          safe_printfmt (2, "ill-formed argument for `%s' (`%s')\n", option->opt_string, option->arg_string);
          goto usage_error;


        case opt_archive:
          {
            lim_free (0, default_archive);
            default_archive = str_save (0, option->arg_string);
            break;
          }

        case opt_dir:
          {
            lim_free (0, dir);
            dir = str_save (0, option->arg_string);
            break;
          }

        case opt_output_dir:
          {
            lim_free (0, output);
            output = str_save (0, option->arg_string);
            keep = 1;
            break;
          }

        case opt_nodiffs:
          {
            diffs = 0;
            break;
          }

        case opt_keep:
          {
            keep = 1;
            break;
          }

        case opt_quiet:
          {
            quiet = 1;
            break;
          }

        case opt_verbose:
          {
            verbose = 1;
            break;
          }

	    case opt_hardlinks:
	      {
	        link_same = 1;
	        break;
	      }

	    case opt_unescaped:
	      {
	        escape_classes = 0;
	        break;
	      }
        case opt_limit:
          {
            lim_free (0, limit_string);
            limit_string = str_save (0, option->arg_string);
           
            break;
          }
        case opt_latest:
          {
            latest = 1;
            break;
          }      
        case opt_exclude:
          {
            t_uchar * normalized_path = normal_from_path(option->arg_string);
            rel_add_records (&exclude_list, rel_singleton_record_taking (rel_make_field_str (normalized_path)), rel_record_null);
            
            lim_free(0, normalized_path);
            normalized_path = 0;
            files_specified = 1;
            break;
          
          }  
	    case opt_diff_opts:
          {
	        diff_opt_count++;
            diff_opts = lim_realloc (0, diff_opts, (diff_opt_count + 1) * sizeof (diff_opts[0]));
            diff_opts[diff_opt_count - 1] = str_save (0, option->arg_string);
            diff_opts[diff_opt_count] = 0;
            break;
          }
        }
    
    }

  {
    int argn;
    t_uchar * tree_root = 0;
    t_uchar * fqvsn = 0;
    t_uchar * rvsnspec = 0;
    t_uchar * archive = 0;
    t_uchar * revision = 0;
    t_uchar * log_file = 0;
    t_uchar * tree_arch = 0;
    t_uchar * tree_version = 0;
    t_uchar * latest_log = 0;
    t_uchar * local_spec = 0;
    rel_table limits = rel_table_nil;
    rel_table file_list = rel_table_nil;
    rel_table file_list2 = rel_table_nil;
    int commandline_rvsn = 0;

    if (default_archive && !arch_valid_archive_name (default_archive))
      {
        safe_printfmt (2, "%s: invalid archive name: %s\n",
                       argv[0], default_archive);
        exit (2);
      }

    tree_root = arch_tree_root (0, dir, 0);

    if (!tree_root)
      {
        safe_printfmt (2, "%s: not in a project tree\n  dir: %s\n",
                       argv[0], dir);
        exit (2);
      }

    local_spec = arch_get_tree_fqrevision(tree_root);

    if (!local_spec)
      {
        safe_printfmt (2, "%s: unable to determine project tree identifier.\n  tree: %s\n", argv[0], tree_root);
        exit (2);
      }


    if (!quiet)
        arch_chatter (1,  "* local directory is at %s\n", local_spec);


    argn = 1;

    if ((argc > argn) && str_cmp (argv[argn], "--"))
      {
        fqvsn = str_save (0, argv[argn]);
        ++argn;
        commandline_rvsn = arch_valid_package_name (fqvsn, arch_maybe_archive, arch_req_patch_level, 0);
      }
    else
      {
        fqvsn = arch_tree_version (tree_root);
        if (!fqvsn)
          {
            safe_printfmt (2, "%s: no tree-version set\n  tree: %s\n", argv[0], tree_root);
            exit (2);
          }
      }

    tree_arch = arch_parse_package_name (arch_ret_archive, 0, fqvsn);
    if (!tree_arch)
    {
        safe_printfmt(2, "please check if you mistakenly provided file names for "
          "revision names?\n");
        exit(2);
    }
    tree_version = arch_parse_package_name (arch_ret_non_archive, 0, fqvsn);

    invariant (!!tree_arch);

    if (!arch_valid_package_name (tree_version, arch_no_archive, arch_req_version, 0))
      {
	rvsnspec = str_save (0, fqvsn);
      }
    else
      {
         if (latest)
           {
             rel_table archive_levels ;
             struct arch_archive *arch = arch_archive_connect (tree_arch, 0);
             invariant (!!arch);
             archive_levels = arch_archive_revisions (arch, tree_version, 0);
             if (!rel_n_records (archive_levels))
               {
                 safe_printfmt (2, "%s: (WEIRD ERROR!) archive has no revisions for version (%s/%s)\n",
                                argv[0], tree_arch, tree_version);
                 exit (1);
               }
             latest_log = str_save (0, rel_peek_str (archive_levels, rel_n_records (archive_levels) - 1, 0));    
             rel_free_table (archive_levels);

             arch_archive_close (arch);
           }
         else  
	latest_log = arch_highest_patch_level (tree_root, tree_arch, tree_version);

	if (!latest_log)
	  {
	    safe_printfmt (2, "%s: tree shows no revisions in version\n  tree: %s\n  version: %s\n", argv[0], tree_root, fqvsn);
	    exit (2);
	  }

	rvsnspec = str_alloc_cat_many (0, fqvsn, "--", latest_log, str_end);
      }

    lim_free (0, fqvsn);
    lim_free (0, tree_arch);
    lim_free (0, tree_version);
    lim_free (0, latest_log);

    if (argc > argn)
      {
        t_uchar *normalized_path = 0;
        
        if (str_cmp (argv[argn], "--"))
          goto usage_error;

        files_specified = 1;
        ++argn;

        if (argc <= argn)
          goto usage_error;

        while (argc > argn)
          {
            normalized_path = normal_from_path(argv[argn]);
            rel_add_records (&file_list, rel_singleton_record_taking (rel_make_field_str (normalized_path)), rel_record_null);
            ++argn;
            lim_free(0, normalized_path);
            normalized_path = 0;
          }
      }

    if (limit_string)
      {
           rel_add_records (&limits, rel_singleton_record_taking (rel_make_field_str (limit_string)), rel_record_null);
      }      

    if (!arch_valid_package_name (rvsnspec, arch_maybe_archive, arch_req_patch_level, 0))
      {
        safe_printfmt (2, "%s: illegal revision name: %s\n",
                       argv[0], rvsnspec);
        exit (2);
      }

    archive = arch_parse_package_name (arch_ret_archive, default_archive, rvsnspec);
    revision = arch_parse_package_name (arch_ret_non_archive, 0, rvsnspec);
    invariant (!!archive);


    if (commandline_rvsn)
      arch_check_revision_local (archive, revision);

    if (!output)
      {
        t_uchar * output_basename = 0;

        output_basename = str_alloc_cat_many (0, ",,what-changed.", revision, "--", archive, str_end);
        output = file_name_in_vicinity (0, tree_root, output_basename);
        rmrf_file (output);

        lim_free (0, output_basename);
      }


    /****************************************************************
     * The heart of the matter.
     */
    {
      t_uchar * orig_tree = 0;
      struct arch_make_changeset_report make_report = {0, };
      struct arch_changeset_report report = {rel_table_nil, };
      assoc_table inode_shortcut = 0;
      /*
      if (!quiet)
        arch_chatter (1, "* looking for %s/%s to compare with\n", archive, revision);
      */ /*message show the same information as the string below, so commented out */

      orig_tree = arch_find_or_make_local_copy ((quiet ? -1 : 1), tree_root, 0, 0, archive, revision);

      if (!orig_tree)
        {
          safe_printfmt (2, "%s: no local copies to compare to (%s/%s)\n  consider `add-pristine --help'\n",
                         argv[0], archive, revision);
          exit (2);
        }


      if (!quiet)
        arch_chatter (1, "* comparing to %s/%s\n", archive, revision);

      if (!quiet)
        make_report.callback = make_changeset_callback;

      if (files_specified)
        {
          if (rel_n_records (file_list) == 0)
              file_list = arch_source_files_file_list(tree_root, 0, 0);
          file_list2 = rel_table_substract(file_list, exclude_list);
        }
      else
          arch_read_inode_sig (0, &inode_shortcut, tree_root, archive, revision);
      
      if (files_specified )
          arch_make_files_changeset (&make_report, output, file_list2, orig_tree, tree_root, arch_unspecified_id_tagging, arch_inventory_unrecognized, escape_classes);
      else
          arch_make_changeset (&make_report, orig_tree, tree_root, output, arch_unspecified_id_tagging, arch_inventory_unrecognized, limits, inode_shortcut, link_same, escape_classes);
      arch_evaluate_changeset (&report, output);
      exit_status = arch_any_changes (&report);

      if (exit_status && (diffs || verbose))
        {
          if (!quiet)
            safe_printfmt (1, "\n");

          if (verbose)
            /* verbose is a superset of diffs */
            arch_print_changeset (1, &report, diffs, escape_classes);
          else
            arch_print_changeset_custom_diffs (1, &report, orig_tree, tree_root, diff_opts, escape_classes);
        }

      arch_free_make_changeset_report_data (&make_report);
      arch_free_changeset_report_data (&report);
      lim_free (0, orig_tree);

      /* remove the changeset info unless the user requested it persist */
      if (!keep)
        rmrf_file (output);

      free_assoc_table (inode_shortcut);
    }

    {
      unsigned i;
      for (i = 0; i < diff_opt_count; i++)
	      lim_free (0, diff_opts[i]);
    }
    lim_free (0, diff_opts);
    lim_free (0, rvsnspec);
    lim_free (0, tree_root);
    lim_free (0, archive);
    lim_free (0, revision);
    lim_free (0, log_file);
    lim_free (0, limit_string);
    lim_free (0, local_spec);
    rel_free_table (limits);
    rel_free_table(file_list);
    rel_free_table(file_list2);
  }


  lim_free (0, dir);
  lim_free (0, output);
  lim_free (0, default_archive);

  exit (exit_status);
  return 0;
}




static void
make_changeset_callback (void * ign, char * fmt, va_list ap)
{
  safe_printfmt_va_list (1, fmt, ap);
  safe_flush (1);
}




/* tag: Tom Lord Fri May 23 14:06:15 2003 (cmd-diff.c)
 */
