Source

chicken-git / git.scm

Full commit
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; git.scm - libgit2 bindings for Chicken Scheme
;;;
;;; Copyright (c) 2013-2014, Evan Hanson
;;; See LICENSE for details.
;;;
;;; Pretty stable.
;;; Please report bugs (see README).
;;;

(require-library extras posix files lolevel data-structures git-lolevel)

(module git ()
  (import scheme)
  (import (except chicken repository-path make-blob blob?))
  (import (only extras format)
          (only git-lolevel git-error)
          (only posix current-directory regular-file?)
          (only files normalize-pathname make-pathname)
          (only lolevel record-instance-slot record-instance?
                        make-locative move-memory! number-of-bytes)
          (rename (only data-structures o) (o compose))
          (prefix (except git-lolevel git-error) git-)
          (rename (only chicken make-blob blob?)
                  (blob? chicken-blob?)
                  (make-blob make-chicken-blob)))
  (include "git-exports.scm")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Syntax helpers.
;;;

(define-syntax define-git-record-type
  (let ((s+ symbol-append))
    (lambda (e . c)
      (let* ((name      (cadr e))
             (spec      (caddr e))
             (printer   (cadddr e))
             (free      (cddddr e))
             (slots     (cdar spec))
             (attrs     (cdr spec))
             (make      (s+ 'make- name))
             (%make     (s+ '%make- name))
             (->pointer (s+ name '->pointer))
             (pointer-> (s+ 'pointer-> name)))
        `(begin
           (define-record ,name >pointer ,@slots)
           (define ,%make ,make)
           (define-record-printer (,name ,name out)
             (display ,printer out))
           (define (,pointer-> ,@slots ptr)
             (and-let* ((ptr)
                        (obj (,%make ptr ,@slots)))
               ,(if (null? free)
                    'obj
                    `(set-finalizer! obj
                      (lambda (o)
                        (,(caar free) (,->pointer o)))))))
           ,@(map (lambda (attr)
                    (let ((getter (s+ name '- attr)))
                      (case attr
                        ((id oid)
                         `(define (,(s+ name '-id) obj)
                            (pointer->oid (,(s+ 'git- getter) (,->pointer obj)))))
                        (else
                         `(define (,getter obj)
                            (,(s+ 'git- getter) (,->pointer obj)))))))
                  attrs))))))

(define-syntax begin0-let
  (syntax-rules ()
    ((_ ((n e) . rest) . body)
     (let ((n e) . rest) (begin . body) n))))

(define ((git-record-attribute-setter f) r v) (f (object->pointer r) v))
(define ((set-owner m f) o) (m o (f o)))
(define ((preserve-owner m f) o) (m (object-owner o) (f o)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generics & OIDs
;;;

;; OIDs are allocated/freed by git-lolevel.scm.
(define-git-record-type oid
  ((oid))
  (format "#<oid ~S>" (oid->string oid 7)))

;; The first slot in all Git record types is the object pointer.
(define (object->pointer obj) (record-instance-slot obj 0))

;; If an object has an owner, it's in the second slot.
(define (object-owner obj) (record-instance-slot obj 1))

;; The type symbol of the given object as reported by Git, or #f.
;; Only valid for the Commit, Tree, Blob & Tag types.
(define (object-type obj)
  (let ((type (git-object-type (object->pointer obj))))
    (and (not (memq type '(ext1 ext2))) type)))

(define (object=? obj1 obj2)
  (oid=? (object-id obj1) (object-id obj2)))

(define (object-sha obj #!optional (len 40))
  (oid->string (object->oid obj) len))

(define (oid=? oid1 oid2)
  (git-oid-equal (oid->pointer oid1) (oid->pointer oid2)))

(define (oid->string id #!optional (len 40))
  (git-oid-tostr (min len 40) (oid->pointer id)))

(define oid->path   (compose git-oid-pathfmt oid->pointer))
(define string->oid (compose pointer->oid git-oid-fromstr))
(define object-id   (compose pointer->oid git-oid-cpy git-object-id object->pointer))

(define (object->oid obj)
  (cond ((oid? obj) obj)
        ((string? obj) (string->oid obj))
        ((reference? obj) (reference-target obj))
        ((record-instance? obj) (object-id obj))
        (else (error 'object->oid "Can't convert to OID" obj))))

(define object->oid->pointer
  (compose oid->pointer object->oid))

(define (object->reference-name obj)
  (cond ((string? obj) obj)
        ((reference? obj) (reference-name obj))
        (else (git-error 'object->reference-name "Not a valid reference" obj))))

(define (pointer->object repo ptr)
  (case (git-object-type ptr)
    ((blob)   (pointer->blob repo ptr))
    ((commit) (pointer->commit repo ptr))
    ((tag)    (pointer->tag repo ptr))
    ((tree)   (pointer->tree repo ptr))
    (else     (git-error 'pointer->object "Not a valid object pointer" ptr))))

(define (merge-base repo a b)
  (pointer->commit
   repo
   (git-commit-lookup
    (repository->pointer repo)
    (pointer->oid
     (git-merge-base
      (repository->pointer repo)
      (oid->pointer a)
      (oid->pointer b))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Signatures
;;;

(define-git-record-type signature
  ((signature) name email)
  (format "#<signature \"~A <~A>\">" (signature-name signature) (signature-email signature))
  (git-signature-free))

(define signature-time        (compose git-time-time git-signature-time signature->pointer))
(define signature-time-offset (compose git-time-offset git-signature-time signature->pointer))

(define (make-signature name email #!optional time (offset 0))
  (pointer->signature
   (cond (time (git-signature-new name email time offset))
         (else (git-signature-now name email)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Repositories
;;;

(define-git-record-type repository
  ((repository) is-empty is-bare path workdir head-unborn head-detached)
  (format "#<repository ~S>" (repository-path repository))
  (git-repository-free))

(define repository-empty? repository-is-empty)
(define repository-bare? repository-is-bare)
(define repository-head-unborn? repository-head-unborn)
(define repository-head-detached? repository-head-detached)
(define repository-working-directory repository-workdir)

(define (repository-open #!optional (path (current-directory)))
  (let ((path (normalize-pathname path)))
    (pointer->repository
     (condition-case
       (git-repository-open path)
       ((git) (git-repository-open (git-repository-discover path)))))))

(define (repository-ref repo ref #!optional (type 'any))
  (condition-case
    (pointer->object
     repo
     (git-object-lookup
      (repository->pointer repo)
      (object->oid->pointer ref)
      type))
    ((git) #f)))

(define (create-repository #!optional (path (current-directory)) bare)
  (pointer->repository (git-repository-init path bare)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Revspec

(define (parse-revision-specification repo str)
  (condition-case
    ;; Try a single revision first.
    (let ((revspec (git-revparse-single (repository->pointer repo) str)))
      (values (pointer->object repo revspec) #f))
    ((git)
     (condition-case
       ;; If str didn't specify a single revision, try parsing it as a range.
       (let ((revspec (git-revparse (repository->pointer repo) str)))
         (values (pointer->object repo (git-revspec-from revspec))
                 (pointer->object repo (git-revspec-to revspec))))
       ((git)
        ;; Neither a single revision nor a range, return falses.
        ;; XXX Error here?
        (values #f #f))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; References

(define-git-record-type reference
  ((reference repository) type name delete)
  (format "#<reference ~S>" (reference-name reference))
  (git-reference-free))

(define repository-head   (set-owner pointer->reference (compose git-repository-head repository->pointer)))
(define reference-resolve (preserve-owner pointer->reference (compose git-reference-resolve reference->pointer)))

(define reference-branch? (compose git-reference-is-branch reference->pointer))
(define reference-remote? (compose git-reference-is-remote reference->pointer))

(define (reference-target ref)
  ;; We have to dig out the intermediate reference in order to free it.
  (let* ((ref* (git-reference-resolve (reference->pointer ref)))
         (oid* (git-oid-cpy (git-reference-target ref*))))
    (git-reference-free ref*)
    (pointer->oid oid*)))

(define (reference repo name)
  (pointer->reference repo (git-reference-lookup (repository->pointer repo) name)))

(define (references-fold kons knil repo #!optional (type 'all))
  (begin0-let ((state knil))
    (git-reference-foreach-name
     (repository->pointer repo)
     (lambda (name)
       (set! state
         (kons (pointer->reference
                repo
                (git-reference-lookup
                 (repository->pointer repo)
                 name))
               state))))))

(define (references repo #!optional (type 'all))
  (references-fold cons '() repo type))

(define (create-reference repo #!key name target symbolic force)
  (let ((repo* (repository->pointer repo)))
    (pointer->reference
     repo
     (if (not symbolic)
         ;; Direct references are created by OID.
         (git-reference-create repo* name (object->oid->pointer target) force)
         ;; Symbolic references require the target to be given by a string.
         (git-reference-symbolic-create repo* name (object->reference-name target) force)))))

(define (reference-target-set! ref target)
  (git-reference-set-target
   (reference->pointer ref)
   (object->oid->pointer target)))

(define (reference-rename ref name #!optional force)
  (pointer->reference
   (reference-repository ref)
   (git-reference-rename (reference->pointer ref) name force)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Trees

(define-git-record-type tree
  ((tree repository) id entrycount)
  (format "#<tree ~S>" (oid->string (tree-id tree) 7))
  (git-tree-free))

(define-git-record-type tree-entry
  ((tree-entry owner) id name type)
  (format "#<tree-entry ~S>" (tree-entry-name tree-entry))
  (git-tree-entry-free))

(define (tree repo ref)
  (pointer->tree
   repo
   (git-tree-lookup
    (repository->pointer repo)
    (object->oid->pointer ref))))

(define (tree-ref tree key)
  (pointer->tree-entry
   tree
   (let ((tree* (tree->pointer tree)))
     ;; dup the resulting entry so it's under our control w.r.t. GC.
     (cond ((number? key)
            (git-tree-entry-dup (git-tree-entry-byindex tree* key)))
           ((oid? key)
            (git-tree-entry-dup (git-tree-entry-byoid tree* key)))
           ((string? key)
            (cond
              ((git-tree-entry-byname tree* key) => git-tree-entry-dup)
              (else
               ;; Entries retrieved by path are already owned by the user.
               (condition-case
                 (git-tree-entry-bypath tree* key)
                 ((git) #f)))))
           (else
            (git-error 'tree-ref "Invalid key" key))))))

(define tree-entry->object
  (case-lambda
    ((entry)
     (let ((owner (tree-entry-owner entry)))
       (if (tree? owner)
           (tree-entry->object (tree-repository owner) entry)
           (git-error 'tree-entry->object "Can't determine owning repository" entry))))
    ((repo entry)
     (pointer->object
      repo
      (git-tree-entry-to-object
       (repository->pointer repo)
       (tree-entry->pointer entry))))))

(define (create-tree repo #!optional (index (index-open repo)))
  (pointer->tree
   repo
   (git-tree-lookup
    (repository->pointer repo)
    (git-index-write-tree (index->pointer index)))))

(define (tree-fold kons knil tree #!optional (mode 'post))
  (begin0-let ((state knil))
    (git-tree-walk
     (tree->pointer tree)
     (lambda (path entry*)
       (set! state
         (kons path (pointer->tree-entry tree (git-tree-entry-dup entry*)) state)))
     mode)))

(define (tree-entries tree)
  (tree-fold (lambda (path entry acc) (cons (cons path entry) acc)) '() tree))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Tree Builders

(define-git-record-type tree-builder
  ((tree-builder) clear)
  "#<tree-builder>"
  (git-tree-builder-free))

(define (make-tree-builder #!optional tree)
  (pointer->tree-builder
   (git-tree-builder-create
    (and tree (tree->pointer tree)))))

(define (tree-builder-ref tb path)
  (and-let* ((entry* (git-tree-builder-get (tree-builder->pointer tb) path)))
    (pointer->tree-entry tb (git-tree-entry-dup entry*))))

(define (tree-builder-insert tb obj path attributes)
  (pointer->tree-entry
   tb
   (git-tree-entry-dup
    (git-tree-builder-insert
     (tree-builder->pointer tb)
     path
     (object->oid->pointer obj)
     attributes))))

(define (tree-builder-write repo tb)
  (pointer->tree
   repo
   (git-tree-lookup
    (repository->pointer repo)
    (git-tree-builder-write
     (repository->pointer repo)
     (tree-builder->pointer tb)))))

(define (tree-builder-remove tb path)
  (git-tree-builder-remove (tree-builder->pointer tb) path))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Branches

(define (branch repo name #!optional (type 'all))
  (pointer->reference repo (git-branch-lookup (repository->pointer repo) name type)))

;; I'm changing branch-move to branch-rename here, perhaps gratuitously.
;; I'm just so sick of typing `git branch rename foo bar` and having
;; git whine at me, consider this payback.
(define (branch-rename ref name #!optional force)
  (pointer->reference
   (reference-repository ref)
   (git-branch-move (reference->pointer ref) name force)))

;; XXX Returns a reference.
(define (create-branch repo #!key name target force)
  (pointer->reference
   repo
   (git-branch-create
    (repository->pointer repo)
    name
    (commit->pointer target)
    force)))

(define branch-name     (compose git-branch-name reference->pointer))
(define branch-delete   (compose git-branch-delete reference->pointer))
(define branch-head?    (compose git-branch-is-head reference->pointer))

(define (branches-fold kons knil repo #!optional (type 'all))
  (let* ((repo* (repository->pointer repo))
         (iter  (set-finalizer! (git-branch-iterator-new repo* type) git-branch-iterator-free)))
     (let loop ((state knil))
       (let ((b (condition-case
                  (git-branch-next iter)
                  ((git) #f))))
         (if (not b)
             state
             (loop (kons (pointer->reference repo b) state)))))))

(define (branches repo #!optional (type 'all))
  (branches-fold cons '() repo type))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Checkout

(define (checkout repo #!optional object)
  (cond
    ((not object)
     (git-checkout-head (repository->pointer repo) git-checkout-options-default))
    ((index? object)
     (git-checkout-index (repository->pointer repo) (index->pointer object) git-checkout-options-default))
    ((memq (object-type object) '(commit tag tree))
     (git-checkout-tree (repository->pointer repo) (object->pointer object) git-checkout-options-default))
    (else
     (git-checkout-tree (repository->pointer repo) (object->oid->pointer object) git-checkout-options-default))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Commits

(define-git-record-type commit
  ((commit repository) id parentcount message message-raw message-encoding time time-offset raw-header)
  (format "#<commit ~S>" (oid->string (commit-id commit) 7))
  (git-commit-free))

(define commit-header commit-raw-header)

(define commit-tree      (preserve-owner pointer->tree (compose git-commit-tree commit->pointer)))
(define commit-tree-id   (compose pointer->oid git-oid-cpy git-commit-tree-id commit->pointer))
(define commit-parent-id (compose pointer->oid git-oid-cpy git-commit-parent-id commit->pointer))
(define commit-author    (compose pointer->signature git-signature-dup git-commit-author commit->pointer))
(define commit-committer (compose pointer->signature git-signature-dup git-commit-committer commit->pointer))

(define (commit-parent cmt #!optional (n 0))
  (condition-case
    (pointer->commit
     (commit-repository cmt)
     (git-commit-parent (commit->pointer cmt) n))
    ((git) #f)))

(define (commit-ancestor cmt #!optional (n 1))
  (condition-case
    (pointer->commit
     (commit-repository cmt)
     (git-commit-nth-gen-ancestor (commit->pointer cmt) n))
    ((git) #f)))

(define (commit-parents c)
  (let ((n (commit-parentcount c)))
    (do ((i 0 (+ i 1))
         (p '() (cons (commit-parent c i) p)))
        ((= i n)
         (reverse p)))))

(define (commit repo ref)
  (pointer->commit
   repo
   (git-commit-lookup
    (repository->pointer repo)
    (object->oid->pointer ref))))

(define (commits-fold kons knil repo #!key initial (hide '()) (sort 'none))
  (let ((repo* (repository->pointer repo)))
    (if (git-repository-head-unborn repo*)
        '() ; No HEAD means no commits.
        (let ((iter (set-finalizer! (git-revwalk-new repo*) git-revwalk-free)))
          (if initial ; Set the initial revision.
              (git-revwalk-push iter (object->oid->pointer initial))
              (git-revwalk-push-head iter))
          ;; Set sort mode, from '(none topo time rev).
          (git-revwalk-sorting iter sort)
          ;; Set hidden commits.
          (for-each (lambda (h) (git-revwalk-hide iter (object->oid->pointer h))) hide)
          ;; Iterate commits.
          (let loop ((state knil))
            (let ((c (condition-case
                       (git-revwalk-next iter)
                       ((git) #f))))
              (if (not c)
                  state ; Exhausted iterator.
                  (loop (kons (pointer->commit
                               repo
                               (git-commit-lookup repo* c))
                              state)))))))))

(define (commits repo #!rest rest)
  (apply commits-fold cons '() repo rest))

(define (create-commit repo #!key message author (committer author) (tree (create-tree repo)) (reference #f) (parents '()))
  (pointer->commit
   repo
   (git-commit-lookup
    (repository->pointer repo)
    (git-commit-create
     (repository->pointer repo)
     (and reference (object->reference-name reference))
     (signature->pointer author)
     (signature->pointer committer)
     message
     (tree->pointer tree)
     (map commit->pointer parents)))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Blobs

(define-git-record-type blob
  ((blob repository) id rawsize rawcontent is-binary)
  (format "#<blob ~S>" (oid->string (blob-id blob) 7))
  (git-blob-free))

(define blob-length  blob-rawsize)
(define blob-content blob-rawcontent)
(define blob-binary? blob-is-binary)

(define (blob-content blob)
  (let* ((size (blob-rawsize blob))
         (dest (make-chicken-blob size)))
    (move-memory! (blob-rawcontent blob) dest size)
    dest))

(define (blob repo ref)
  (pointer->blob
   repo
   (git-blob-lookup
    (repository->pointer repo)
    (object->oid->pointer ref))))

(define (create-blob repo source)
  (let ((repo* (repository->pointer repo)))
    (pointer->blob
     repo
     (git-blob-lookup
      repo*
      (cond ((blob? source)
             (git-blob-create-frombuffer repo* source))
            ((string? source)
             (if (regular-file? source)
                 (git-blob-create-fromdisk repo* source)
                 (git-blob-create-fromworkdir repo* source)))
            (else
             (git-error 'create-blob "Invalid blob source" source)))))))

(define blob* blob)
(define blob*-binary? blob-binary?)
(define blob*-content blob-content)
(define blob*-id blob-id)
(define blob*-size blob-length)
(define blob*? blob?)
(define create-blob* create-blob)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Index

(define-git-record-type index
  ((index) entrycount write clear)
  "#<index>"
  (git-index-free))

(define-git-record-type index-entry
  ((index-entry owner) dev oid ino mode uid gid size stage flags extended path)
  (format "#<index-entry ~S>" (index-entry-path index-entry)))

(define index-entry-ctime (compose git-index-time-seconds git-index-entry-mtime index-entry->pointer))
(define index-entry-mtime (compose git-index-time-seconds git-index-entry-mtime index-entry->pointer))

(define (index-open loc)
  (pointer->index
   (cond ((string? loc)
          (git-index-open loc))
         ((repository? loc)
          (git-repository-index (repository->pointer loc)))
         (else
          (git-error 'index-open "Invalid index location" loc)))))

(define (index-find ix path)
  (if (not (string? path))
      (git-error 'index-find "String required" path)
      (and-let* ((pos (git-index-find #f (index->pointer ix) path)))
        (and (<= 0 pos) pos))))

(define (index-add ix arg)
  (cond ((index-entry? arg)
         (git-index-add (index->pointer ix) arg 0))
        ((string? arg)
         (git-index-add-bypath (index->pointer ix) arg))
        (else
         (git-error 'index-open "Cannot add to index" arg))))

(define (index-remove ix ref)
  (git-index-remove (index->pointer ix) ref 0))

(define (index-read ix #!optional force)
  (git-index-read (index->pointer ix) force))

(define (index-ref ix key)
  (let ((ix* (index->pointer ix)))
    (pointer->index-entry
     ix
     (cond ((number? key)
            (git-index-get-byindex ix* key))
           ((string? key)
            (git-index-get-bypath ix* key 0))
           (else
            (git-error 'index-ref "Invalid key" key))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Status

(define (file-status repo path)
  (git-status-file (repository->pointer repo) path))

(define (file-ignored? repo path)
  (git-status-should-ignore (repository->pointer repo) path))

(define (file-statuses-fold kons knil repo)
  (begin0-let ((state knil))
    (git-status-foreach
     (lambda (path status)
       (set! state (kons path status state)))
     (repository->pointer repo))))

(define (file-statuses repo)
  (file-statuses-fold
   (lambda (path status acc)
     (cons (cons path status) acc))
   '()
   repo))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Notes

(define-git-record-type note
  ((note repository) message oid)
  "#<note>"
  (git-note-free))

(define (note repo object #!optional reference)
  (pointer->note
   repo
   (git-note-read
    (repository->pointer repo)
    reference
    (object->oid->pointer object))))

(define (delete-note repo #!key target reference author (committer author))
  (git-note-remove
   (repository->pointer repo)
   reference
   (signature->pointer author)
   (signature->pointer committer)
   (object->oid->pointer target)))

(define (create-note repo #!key message target reference author (committer author) force)
  (let ((repo* (repository->pointer repo))
        (oid*  (object->oid->pointer target)))
    ;; git-note-create returns the new note's OID, but AFAIK there's no
    ;; way to look up a note by OID. So, to return the new note, we
    ;; first create it...
    (git-note-create
     repo*
     (signature->pointer author)
     (signature->pointer committer)
     reference
     oid*
     message
     force)
    ;; ... Then retrieve it by reading it from the target object.
    (pointer->note
     repo
     (git-note-read
      repo*
      reference
      oid*))))

(define notes-fold
  (let ((reference-exists?
         (lambda (repo* ref)
           (condition-case
             (and (git-reference-free (git-reference-lookup repo* ref)) #t)
             ((git) #f)))))
    (lambda (kons knil repo #!optional reference)
      (let ((repo* (repository->pointer repo)))
        ;; If the notes reference doesn't exist, return knil immediately.
        (if (not (reference-exists? repo* (or reference (git-note-default-ref repo*))))
            knil
            (begin0-let ((state knil))
              (git-note-foreach
               repo*
               reference
               (lambda (bid* oid*)
                 (set! state
                   (kons (pointer->note repo (git-note-read repo* reference oid*)) state))))))))))

(define (notes repo #!optional reference)
  (notes-fold cons '() repo reference))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ODB

(define-git-record-type odb
  ((odb))
  "#<odb>"
  (git-odb-free))

(define-git-record-type odb-object
  ((odb-object owner) id size type)
  "#<odb-object>"
  (git-odb-object-free))

(define (odb-has-object? odb obj)
  (git-odb-exists
   (odb->pointer odb)
   (object->oid->pointer obj)))

(define (odb-open loc)
  (pointer->odb
   (cond ((string? loc)
          (git-odb-open loc))
         ((repository? loc)
          (git-repository-odb (repository->pointer loc)))
         (else
          (git-error 'odb-open "Invalid odb location" loc)))))

(define (odb-read odb obj)
  (pointer->odb-object
   odb
   (git-odb-read
    (odb->pointer odb)
    (object->oid->pointer obj))))

(define (odb-write odb data #!optional (type 'blob))
  (pointer->oid (git-odb-write (odb->pointer odb) data (number-of-bytes data) type)))

(define (odb-hash data #!optional (type 'blob))
  (pointer->oid (git-odb-hash data (number-of-bytes data) type)))

(define (odb-object-data obj)
  (let* ((data (git-odb-object-data (odb-object->pointer obj)))
         (size (odb-object-size obj))
         (dest (make-chicken-blob size)))
    (move-memory! data dest size)
    dest))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Tags

(define-git-record-type tag
  ((tag repository) id name message)
  (format "#<tag ~S>" (tag-name tag))
  (git-tag-free))

(define (tag repo ref)
  (pointer->tag
   repo
   (git-tag-lookup
    (repository->pointer repo)
    (object->oid->pointer ref))))

(define (tags-fold kons knil repo)
  (begin0-let ((state knil)
               (repo* (repository->pointer repo)))
    (git-tag-foreach
     (lambda (name oid*)
       ;; Skip lightweight tags (for which git_tag_lookup fails).
       (and-let* ((tag* (condition-case
                          (git-tag-lookup repo* oid*)
                          ((git) #f))))
         (set! state (kons (pointer->tag repo tag*) state))))
     repo*)))

(define (tags repo)
  (tags-fold cons '() repo))

(define tag-peel   (preserve-owner pointer->object (compose git-tag-peel tag->pointer)))
(define tag-target (preserve-owner pointer->object (compose git-tag-target tag->pointer)))
(define tag-tagger (compose pointer->signature git-signature-dup git-tag-tagger tag->pointer))

(define (tag-delete tag)
  (git-tag-delete (git-object-owner (tag->pointer tag)) (tag-name tag)))

(define (create-tag repo #!key target name message tagger force)
  (pointer->tag
   repo
   (git-tag-lookup
    (repository->pointer repo)
    (git-tag-create
     (repository->pointer repo)
     name
     (object->pointer target)
     (signature->pointer tagger)
     message
     force))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Diffs

(define-git-record-type diff
  ((diff repository) num-deltas)
  (format "#<diff (~a)>" (diff-num-deltas diff))
  (git-diff-free))

(define-git-record-type diff-file
  ((diff-file diff) oid mode path size flags)
  (format "#<diff-file ~s>" (diff-file-path diff-file)))

(define-git-record-type diff-delta
  ((diff-delta diff hunks) old-file new-file status)
  (format "#<diff-delta (~a) ~s>" (diff-delta-status diff-delta) (diff-delta-path diff-delta)))

(define-git-record-type diff-hunk
  ((diff-hunk diff lines) old-start old-lines new-start new-lines header-len header)
  (format "#<diff-hunk ~s>" (diff-hunk-header diff-hunk)))

(define-git-record-type diff-line
  ((diff-line diff content) origin old-lineno new-lineno num-lines content-len content-offset)
  (format "#<diff-line (~a)>" (diff-line-origin diff-line)))

(define diff-delta-old-file (preserve-owner pointer->diff-file diff-delta-old-file))
(define diff-delta-new-file (preserve-owner pointer->diff-file diff-delta-new-file))

(define (diff-delta-path delta)
  (diff-file-path
   (or (diff-delta-new-file delta)
       (diff-delta-old-file delta))))

(define (diff-fold kons knil diff)
  ;; This is ugly: the git_diff_{hunk,line} structs associated with a
  ;; git_diff are only valid for the duration of the callbacks that
  ;; produce them (and the git_diff_delta only until its git_diff is
  ;; freed), so any non-immediate data we want to be available later
  ;; (like the structs themselves, and anything accessed by reference
  ;; through their fields) have to be copied out. Some of this is done
  ;; in git-lolevel.scm (`git_diff_file_cb` et al.), and some is done
  ;; below.
  (begin0-let ((state knil)
               (delta #f)
               (hunk #f))
    (let ((yield!
           (lambda ()
             (diff-delta-hunks-set!
              delta
              (foldl (lambda (a hunk)
                       (diff-hunk-lines-set!
                        hunk
                        (reverse (diff-hunk-lines hunk)))
                       (cons hunk a))
                     '()
                     (diff-delta-hunks delta)))
             (begin0-let ((state* (kons delta state)))
               (set! state state*)))))
      (git-diff-foreach
       (lambda (*delta)
         (when delta (yield!))
         (set! delta (pointer->diff-delta diff '() *delta)))
       (lambda (*delta *hunk)
         (set! hunk (pointer->diff-hunk delta '() *hunk))
         (diff-delta-hunks-set! delta (cons hunk (diff-delta-hunks delta))))
       (lambda (*delta *hunk *line)
         (let* ((len  (git-diff-line-content-len *line))
                (str  (make-string len))
                (line (pointer->diff-line hunk str *line)))
           (move-memory! (git-diff-line-content *line) str len)
           (diff-hunk-lines-set! hunk (cons line (diff-hunk-lines hunk)))))
       (diff->pointer diff))
      (when delta (yield!)))))

(define diff
  (case-lambda
    ((repo)
     (diff repo (index-open repo)))
    ((repo object)
     (pointer->diff
      repo ; Stored as the diff's parent object.
      (let ((repo* (repository->pointer repo)))
        (cond ((index? object)
               (git-diff-index-to-workdir repo* (index->pointer object)))
              ((tree? object)
               (git-diff-tree-to-workdir repo* (tree->pointer  object)))
              (else
               (git-error 'diff "Undiffable object" object))))))
    ((repo tree object)
     (pointer->diff
      repo ; Stored as the diff's parent object.
      (let ((repo* (repository->pointer repo))
            (tree* (tree->pointer tree)))
        (cond ((tree? object)
               (git-diff-tree-to-tree repo* tree* (tree->pointer object)))
              ((index? object)
               (git-diff-tree-to-index repo* tree* (index->pointer object)))
              (else
               (git-error 'diff "Undiffable object" object))))))))

(define (diff-deltas . args)
  (diff-fold cons '() (apply diff args)))

(: diffs (deprecated diff-deltas))
(define diffs diff-deltas)

(define (diff-patch diff i)
  (pointer->patch
   (diff-repository diff)
   (git-patch-from-diff (diff->pointer diff) i)))

(define (diff-patches diff)
  (do ((n (fx- (diff-num-deltas diff) 1)
          (fx- n 1))
       (a (list)
          (cons (diff-patch diff n) a)))
      ((fx< n 0) a)))

(define (diff->string diff)
  (do ((n (fx- (diff-num-deltas diff) 1)
          (fx- n 1))
       (s (string)
          (string-append (patch->string (diff-patch diff n)) s)))
      ((fx= n 0) s)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Patch
;;;

(define-git-record-type patch
  ((patch repository) num-hunks line-stats)
  (format "#<patch (~a)>" (patch-num-hunks patch))
  (git-patch-free))

(define patch-stats patch-line-stats)

(define patch->string
  (compose git-patch-to-str patch->pointer))

(define (patch-size patch)
  (git-patch-size
   (patch->pointer patch)
   #t   ; Context.
   #t   ; Hunk headers.
   #t)) ; Line headers.

;; TODO How best to pass the path arguments?
(define (patch blob1 object2)
  (pointer->patch
   (blob-repository blob1)
   (cond
     ((blob? object2)
      (git-patch-from-blobs
       (blob->pointer blob1)
       #f      ; blob1 pathname.
       (blob->pointer blob1)
       #f      ; blob2 pathname.
       #f))    ; diff options.
     ((or (string? object2)
          (chicken-blob? object2))
      (git-patch-from-blob-and-buffer
       (blob->pointer blob1)
       #f      ; blob1 pathname.
       (make-locative object2)
       (number-of-bytes object2)
       #f      ; object2 pathname.
       #f))))) ; diff options.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Remotes
;;;

(define-git-record-type remote
  ((remote repository) clear-refspecs connected disconnect fetch name pushurl refspec-count stop save update-fetchhead update-tips url)
  (format "#<remote ~S (~a)>"
          (remote-name remote)
          (if (remote-connected? remote) "connected" "disconnected"))
  (git-remote-free))

(define-git-record-type refspec
  ((refspec remote) src dst string direction force)
  (format "#<refspec ~S ~S>" (refspec-source refspec) (refspec-destination refspec)))

(define-git-record-type transfer-progress
  ((transfer-progress remote) total-objects indexed-objects received-objects received-bytes)
  "#<transfer-progress>")

(define refspec-source refspec-src)
(define refspec-destination refspec-dst)
(define refspec-force? refspec-force)

(define remote-clear-refspecs! remote-clear-refspecs)
(define remote-connected? remote-connected)
(define remote-url-valid? git-remote-valid-url)
(define remote-url-supported? git-remote-supported-url)
(define remote-name-valid? git-remote-is-valid-name)
(define remote-disconnect! remote-disconnect)
(define remote-fetch! remote-fetch)
(define remote-update-tips! remote-update-tips)
(define remote-update-fetchhead? remote-update-fetchhead)

(define remote-url-set!              (git-record-attribute-setter git-remote-set-url))
(define remote-pushurl-set!          (git-record-attribute-setter git-remote-set-pushurl))
(define remote-update-fetchhead-set! (git-record-attribute-setter git-remote-update-fetchhead))

(define (remote-refspec-add! rem spec #!optional (direction 'fetch))
  (case direction
    ((fetch) (git-remote-add-fetch (remote->pointer rem) spec))
    ((push)  (git-remote-add-push  (remote->pointer rem) spec))
    (else    (git-error 'remote-refspec-add! "Invalid refspec direction" direction))))

(define (remote-refspecs rem)
  (let lp ((i 0)
           (a '()))
    (cond ((git-remote-get-refspec (remote->pointer rem) i) =>
           (lambda (refspec)
             (lp (fx+ i 1)
                 (cons (pointer->refspec rem refspec) a))))
          (else a))))

(define (remote repo name)
  (pointer->remote repo (git-remote-load (repository->pointer repo) name)))

(define (remotes repo)
  (map (lambda (name) (remote repo name))
       (git-remote-list (repository->pointer repo))))

(define (remote-connect! rem #!optional (direction 'fetch))
  (git-remote-connect (remote->pointer rem) direction))

(define (remote-rename rem name #!optional callback)
  (git-remote-rename (remote->pointer rem) name callback))

(define (remote-stats rem)
  (pointer->transfer-progress rem (git-remote-stats (remote->pointer rem))))

(define (remote-download! rem)
  (cond ((remote-connected? rem)
         (git-remote-download (remote->pointer rem))
         (remote-stats rem))
        (else
         (remote-connect! rem)
         (remote-download! rem)
         (remote-disconnect! rem)
         (remote-stats rem))))

(define (create-remote repo name url)
  (pointer->remote repo (git-remote-create (repository->pointer repo) name url)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Cloning
;;;

(define (clone url path) (pointer->repository (git-clone url path #f)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Configs

(define-git-record-type config
  ((config))
  "#<config>"
  (git-config-free))

(define-git-record-type config-entry
  ((config-entry) name value level)
  (format "#<config-entry ~S>" (config-entry-name config-entry)))

(define (config-path #!optional (type 'user))
  (case type
    ((user)
     (git-config-find-global))
    ((system)
     (git-config-find-system))
    ((xdg)
     (git-config-find-xdg))
    (else
     (git-error 'config-path "Invalid configuration file path type" type))))

(define (config-open #!optional target)
  (pointer->config
   (cond ((not target)
          (git-config-open-default))
         ((string? target)
          (git-config-open-ondisk target))
         ((symbol? target)
          (git-config-open-ondisk (config-path target)))
         ((repository? target)
          (git-repository-config
           (repository->pointer target)))
         (else
          (git-error 'config-open "Invalid configuration file source" target)))))

(define (config-get config name #!optional (type 'string))
  ((case type
     ((boolean) git-config-get-bool)
     ((string)  git-config-get-string)
     ((number)  git-config-get-int64)
     (else (git-error 'config-get "Invalid value type specifier" type)))
   (config->pointer config)
   name))

(define (config-set! config name value)
  ((cond
     ((boolean? value) git-config-set-bool)
     ((string? value)  git-config-set-string)
     ((number? value)  git-config-set-int64)
     (else (git-error 'config-set "Invalid value type" value)))
   (config->pointer config)
   name
   value))

(define (config-unset! cfg name)
  (git-config-delete-entry (config->pointer cfg) name)))