;;; Guile-Git --- GNU Guile bindings of libgit2
;;; Copyright © 2025 Enrico Tolotto <etolotto@gmail.com>
;;;
;;; This file is part of Guile-Git.
;;;
;;; Guile-Git is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; Guile-Git is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Guile-Git.  If not, see <http://www.gnu.org/licenses/>.

(define-module (tests apply)
  #:use-module (git)
  #:use-module (git apply)
  #:use-module (tests helpers)
  #:use-module (srfi srfi-64))

(test-begin "apply")

(libgit2-init!)

(with-repository "simple" directory

  (test-equal "apply diff to index"
    "diff --git a/directory/message b/directory/message
new file mode 100644
index 0000000..b075b00
--- /dev/null
+++ b/directory/message
@@ -0,0 +1 @@
+a file in a directory\n"
    (let* ((repository (repository-open directory))
            (oid (reference-target (repository-head repository)))
            (commit1 (commit-lookup repository oid))
            (commit2 (commit-parent commit1))
            (commit-object (object-lookup repository (commit-id commit2)))
            (commit-diff (diff-tree-to-tree repository (commit-tree commit2) (commit-tree commit1)))
            (ret (reset repository commit-object RESET_HARD))
            (ret-apply (apply-diff repository commit-diff APPLY-LOCATION-INDEX))
            (diff-from-apply (diff-tree-to-index repository (commit-tree commit2) (repository-index repository))))
      (diff->string diff-from-apply)))

  (test-equal "apply diff to tree"
    ""
    (let* ((repository (repository-open directory))
            (oid (reference-target (repository-head repository)))
            (commit1 (commit-lookup repository oid))
            (commit2 (commit-parent commit1))
            (commit-diff (diff-tree-to-tree repository (commit-tree commit2) (commit-tree commit1)))
            (index-with-patch (apply-diff-to-tree repository (commit-tree commit2) commit-diff))
            (diff-from-apply (diff-tree-to-index repository (commit-tree commit1) index-with-patch)))
      (diff->string diff-from-apply))))

(libgit2-shutdown!)

(test-end "apply")
