forked from disruptek/gittyup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgittyup.nim
1817 lines (1611 loc) · 56 KB
/
gittyup.nim
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
import std/macros except error
import std/math
import std/times
import std/logging
import std/sets
import std/options
import std/strformat
import std/bitops
import std/os
import std/strutils
import std/hashes
import std/tables
import std/uri
import hlibgit2/strarray
import hlibgit2/types
import hlibgit2/buffer
import hlibgit2/pathspec
import hlibgit2/diff
import hlibgit2/branch
import hlibgit2/clone
import hlibgit2/status
import hlibgit2/checkout
import hlibgit2/oid
import hlibgit2/tree
import hlibgit2/errors
import hlibgit2/common
import hlibgit2/global
import hlibgit2/commit
import hlibgit2/tag
import "hlibgit2/object"
import hlibgit2/remote
import hlibgit2/refs
import hlibgit2/repository
import hlibgit2/annotated_commit
import hlibgit2/revparse
import hlibgit2/revwalk
import hlibgit2/signature
import badresults
export badresults
const
GIT_DIFF_OPTIONS_VERSION* = 1
GIT_STATUS_OPTIONS_VERSION* = 1
GIT_CLONE_OPTIONS_VERSION* = 1
GIT_CHECKOUT_OPTIONS_VERSION* = 1
GIT_FETCH_OPTIONS_VERSION* = 1
# git_strarray_dispose replaces git_strarray_free in >v1.0.1
when not compiles(git_strarray_dispose):
template git_strarray_dispose(arr: ptr git_strarray) =
git_strarray_free(arr)
type
# separating out stuff we free via routines from libgit2
GitHeapGits = git_repository | git_reference | git_remote | git_tag |
git_object | git_commit | git_status_list |
git_annotated_commit | git_tree_entry | git_revwalk | git_buf |
git_pathspec | git_tree | git_diff | git_pathspec_match_list |
git_branch_iterator | git_signature
# or stuff we alloc and pass to libgit2, and then free later ourselves
NimHeapGits = git_clone_options | git_status_options | git_checkout_options |
git_oid | git_diff_options
GitTreeWalkCallback* = proc (root: cstring; entry: ptr git_tree_entry;
payload: pointer): cint
GitObjectKind* = git_object_t
GitThing* = ref object
o*: GitObject
# we really don't have anything else to say about these just yet
case kind*: GitObjectKind
of GIT_OBJECT_TAG:
discard
of GIT_OBJECT_REF_DELTA:
discard
of GIT_OBJECT_TREE:
discard
else:
discard
# if it's on this list, the semantics should be pretty consistent
GitBuf* = ptr git_buf
GitDiff* = ptr git_diff
GitPathSpec* = ptr git_pathspec
GitRevWalker* = ptr git_revwalk
GitTreeEntry* = ptr git_tree_entry
GitTreeEntries* = seq[GitTreeEntry]
GitObject* = ptr git_object
GitOid* = ptr git_oid
GitOids* = seq[GitOid]
GitRemote* = ptr git_remote
GitReference* = ptr git_reference
GitRepository* = ptr git_repository
GitStrArray* = distinct git_strarray ## strings freed by libgit2
GittyStrArray* = distinct git_strarray ## strings freed by nim
GitTag* = ptr git_tag
GitCommit* = ptr git_commit
GitStatus* = ptr git_status_entry
GitStatusList* = ptr git_status_list
GitTree* = ptr git_tree
GitSignature* = ptr git_signature
GitTagTable* = OrderedTableRef[string, GitThing]
GitResult*[T] = Result[T, GitResultCode]
GitResultCode* = git_error_code
GitRepoState* = git_repository_state_t
GitCheckoutNotify* = git_checkout_notify_t
GitTreeWalkMode* = git_treewalk_mode
GitStatusShow* = git_status_show_t
GitStatusFlag* = git_status_t
GitCheckoutStrategy* = git_checkout_strategy_t
GitErrorClass* = git_error_t
GitStatusOption* = git_status_opt_t
GitBranchType* = git_branch_t
GitPathSpecFlag* = git_pathspec_flag_t
export git_error_code
export git_repository_state_t
export git_checkout_notify_t
export git_treewalk_mode
export git_status_show_t
export git_status_t
export git_checkout_strategy_t
export git_error_t
export git_status_opt_t
export git_branch_t
export git_pathspec_flag_t
# these just cast some cints into appropriate enums
template grc(code: cint): GitResultCode =
to_git_error_code(cast[c_git_error_code](code))
template grc(code: GitResultCode): GitResultCode = code
template gec(code: cint): GitErrorClass =
to_git_error_t(cast[c_git_error_t](code))
proc hash*(gcs: GitCheckoutStrategy): Hash =
## too large an enum for native sets
gcs.ord.hash
macro enumValues(e: typed): untyped =
newNimNode(nnkCurly).add(e.getType[1][1..^1])
const
validGitStatusFlags = enumValues(GitStatusFlag)
validGitObjectKinds = enumValues(GitObjectKind)
defaultCheckoutStrategy = [
GIT_CHECKOUT_SAFE,
GIT_CHECKOUT_RECREATE_MISSING,
GIT_CHECKOUT_SKIP_LOCKED_DIRECTORIES,
GIT_CHECKOUT_DONT_OVERWRITE_IGNORED,
].toHashSet
commonDefaultStatusFlags = {
GIT_STATUS_OPT_INCLUDE_UNTRACKED,
GIT_STATUS_OPT_INCLUDE_IGNORED,
GIT_STATUS_OPT_INCLUDE_UNMODIFIED,
GIT_STATUS_OPT_EXCLUDE_SUBMODULES,
GIT_STATUS_OPT_DISABLE_PATHSPEC_MATCH,
GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX,
GIT_STATUS_OPT_RENAMES_INDEX_TO_WORKDIR,
GIT_STATUS_OPT_RENAMES_FROM_REWRITES,
GIT_STATUS_OPT_UPDATE_INDEX,
GIT_STATUS_OPT_INCLUDE_UNREADABLE,
}
defaultStatusFlags =
when FileSystemCaseSensitive:
commonDefaultStatusFlags + {GIT_STATUS_OPT_SORT_CASE_SENSITIVELY}
else:
commonDefaultStatusFlags + {GIT_STATUS_OPT_SORT_CASE_INSENSITIVELY}
proc dumpError*(code: GitResultCode): string =
## retrieves the last git error message
let err = git_error_last()
if not err.isNil:
result = $gec(err.klass) & " error: " & $err.message
when defined(gitErrorsAreFatal):
raise Defect.newException result
template dumpError() =
let emsg = GIT_OK.dumpError
if emsg != "":
error emsg
template gitFail*(code: GitResultCode; body: untyped) =
## a version of gitTrap that expects failure; no error messages!
if code != GIT_OK:
body
template gitFail*(allocd: typed; code: GitResultCode; body: untyped) =
## a version of gitTrap that expects failure; no error messages!
defer:
if code == GIT_OK:
free(allocd)
gitFail(code, body)
template gitTrap*(code: GitResultCode; body: untyped) =
## trap an api result code, dump it via logging,
## run the body as an error handler
if code != GIT_OK:
dumpError()
body
template gitTrap*(allocd: typed; code: GitResultCode; body: untyped) =
## trap an api result code, dump it via logging,
## run the body as an error handler
defer:
if code == GIT_OK:
free(allocd)
gitTrap(code, body)
# set a result variable `self` to value/error
template ok*[T](self: var Result[T, GitResultCode]; x: T): auto =
badresults.ok(self.Result, x)
template err*[T](self: var Result[T, GitResultCode]; x: GitResultCode): auto =
badresults.err(self.Result, x)
# create a new result (eg. for an iterator)
template ok*[T](x: T): auto =
#results.ok(Result[T, GitResultCode], x)
results.ok(GitResult[T], x)
template err*[T](x: GitResultCode): auto =
#results.err(Result[T, GitResultCode], x)
badresults.err(Result[T, GitResultCode], x)
template `:=`*[T](v: untyped{nkIdent}; vv: Result[T, GitResultCode];
body: untyped): untyped =
var vr = vv
template v: auto {.used.} = unsafeGet(vr)
defer:
if isOk(vr):
when defined(debugGit):
debug "auto-free of " & $typeof(unsafeGet(vr))
free(unsafeGet(vr))
if not isOk(vr):
var code {.used, inject.} = vr.error
when defined(debugGit):
debug "failure: " & $code
body
proc normalizeUrl(uri: Uri): Uri =
## turn a git@github.com: url into an ssh url with username, hostname
const
ghPrefix = "git@github.com:"
result = uri
if result.scheme == "" and result.path.startsWith ghPrefix:
result.path = result.path[ghPrefix.len .. ^1]
result.username = "git"
result.hostname = "github.com"
result.scheme = "ssh"
proc loadCerts(): bool =
# https://github.com/wildart/julia/commit/2a59c5fcb579c76715f0015784b6a0a8ebda0c0c
var
file = getEnv("SSL_CERT_FILE")
dir = getEnv("SSL_CERT_DIR")
if not fileExists(file):
file = ""
if not dirExists(dir):
dir = ""
# try to set a default for linux
when defined(posix):
if (file, dir) == ("", ""):
file = "/etc/ssl/certs/ca-certificates.crt"
if not fileExists(file):
return true
# this seems to be helpful for git builds on linux, at least
if file != "" and dir == "":
dir = parentDir file
result = git_libgit2_opts(
GIT_OPT_SET_SSL_CERT_LOCATIONS.cint,
file.cstring, dir.cstring) >= 0
# this is a little heavy-handed, but it might save someone some time
if not result:
dumpError()
proc initGit(): bool =
let code = git_libgit2_init()
result = code > 0
when defined(debugGit):
debug "git init"
when not defined(windows):
result = result and loadCerts()
proc init*(): bool =
## initialize the library to prepare for git operations;
## returns true if libgit2 was initialized
when defined(gitShutsDown):
return initGit()
else:
block:
once:
return initGit()
result = true
proc shutdown*(): bool =
## shutdown the library, freeing any libgit2 data;
## returns true if shutdown was successful
when defined(gitShutsDown):
result = git_libgit2_shutdown() >= 0
when defined(debugGit):
debug "git shut"
else:
result = true
template withGit(body: untyped) =
## convenience to ensure git is initialized and shutdown
if not init():
raise newException(OSError, "unable to init git")
defer:
if not shutdown():
raise newException(OSError, "unable to shut git")
body
template setResultAsError(result: typed; code: cint | GitResultCode) =
## given a git result code, assign it to the result to indicate error;
## this is adaptive to different return types
when defined(debugGit):
debug "git said " & $grc(code)
when result is GitResultCode:
result = grc(code)
elif result is GitResult:
result.err grc(code)
template withResultOf(gitsaid: cint | GitResultCode; body: untyped) =
## when git said there was an error, set the result code;
## else, run the body
if grc(gitsaid) == GIT_OK:
when defined(debugGit):
debug "git said " & $grc(gitsaid)
body
else:
setResultAsError(result, gitsaid)
proc free*[T: GitHeapGits](point: ptr T) =
## perform a free of a git-managed pointer
withGit:
if point.isNil:
when not defined(release) and not defined(danger):
raise Defect.newException "attempt to free nil git heap object"
else:
when defined(debugGit):
debug "\t~> freeing git " & $typeof(point)
when T is git_repository:
git_repository_free(point)
elif T is git_reference:
git_reference_free(point)
elif T is git_remote:
git_remote_free(point)
elif T is git_tag:
git_tag_free(point)
elif T is git_commit:
git_commit_free(point)
elif T is git_object:
git_object_free(point)
elif T is git_tree:
git_tree_free(point)
elif T is git_tree_entry:
git_tree_entry_free(point)
elif T is git_revwalk:
git_revwalk_free(point)
elif T is git_status_list:
git_status_list_free(point)
elif T is git_annotated_commit:
git_annotated_commit_free(point)
elif T is git_pathspec:
git_pathspec_free(point)
elif T is git_pathspec_match_list:
git_pathspec_match_list_free(point)
elif T is git_diff:
git_diff_free(point)
elif T is git_buf:
git_buf_dispose(point)
elif T is git_branch_iterator:
git_branch_iterator_free(point)
elif T is git_signature:
git_signature_free(point)
else:
{.error: "missing a free definition for " & $typeof(T).}
when defined(debugGit):
debug "\t~> freed git " & $typeof(point)
proc free*[T: NimHeapGits](point: ptr T) =
## perform a free of a nim-alloced pointer to git data
if point.isNil:
when not defined(release) or not defined(danger):
raise Defect.newException "attempt to free nil nim heap git object"
else:
when defined(debugGit):
debug "\t~> freeing nim " & $typeof(point)
dealloc(point)
when defined(debugGit):
debug "\t~> freed nim " & $typeof(point)
proc free*(thing: sink GitThing) =
## free a git thing and its gitobject contents appropriately
assert not thing.isNil
case thing.kind:
of GIT_OBJECT_COMMIT:
free(cast[GitCommit](thing.o))
of GIT_OBJECT_TREE:
free(cast[GitTree](thing.o))
of GIT_OBJECT_TAG:
free(cast[GitTag](thing.o))
of GIT_OBJECT_ANY, GIT_OBJECT_INVALID, GIT_OBJECT_BLOB,
GIT_OBJECT_OFS_DELTA, GIT_OBJECT_REF_DELTA:
free(cast[GitObject](thing.o))
#disarm thing
proc free*(entries: sink GitTreeEntries) =
## git tree entries need a special free
for entry in entries.items:
free(entry)
proc free*(s: string) =
## for template compatability only
discard
template addr(gstrings: GitStrArray | GittyStrArray): ptr git_strarray =
## convenience for passing git_strarray-like values
(ptr git_strarray)(unsafeAddr gstrings.git_strarray)
proc free*(gstrings: var GitStrArray) =
## free a git_strarray allocated by libgit2
template gstrs: git_strarray = cast[git_strarray](gstrings)
if not gstrs.strings.isNil:
git_strarray_dispose(addr gstrings)
assert gstrs.strings.isNil
proc free*(gstrings: var GittyStrArray) =
## free a git_strarray allocated by nim
template gstrs: git_strarray = gstrings.git_strarray
if not gstrs.strings.isNil:
dealloc gstrs.strings
gstrs.strings = nil
iterator items(gstrings: GitStrArray | GittyStrArray): string =
## emit the members of a string array
assert not gstrings.git_strarray.strings.isNil
for index in 0..<gstrings.git_strarray.count:
yield $gstrings.git_strarray.strings[index]
proc toStrArray*(values: openArray[string]): GittyStrArray =
## future converter (?) to nim-alloc'd string array
template gstrs: git_strarray = result.git_strarray
gstrs.count = values.len.cuint
if gstrs.count > 0:
gstrs.strings = cast[ptr cstring](allocCStringArray values)
proc toStringSeq*(gstrings: GitStrArray | GittyStrArray): seq[string] =
## future converter (?) from nim-or-libgit-alloc'd string arrays
template gstrs: git_strarray = gstrings.git_strarray
if gstrs.count > 0:
assert not gstrs.strings.isNil
result = cstringArrayToSeq(cast[cstringArray](gstrs.strings),
gstrs.count.int)
proc kind(obj: GitObject | GitCommit | GitTag): GitObjectKind =
git_object_type(cast[GitObject](obj))
proc newThing(obj: GitObject | GitCommit | GitTag): GitThing =
## turn a git object into a thing
assert not obj.isNil
GitThing(kind: obj.kind, o: cast[GitObject](obj))
proc newThing(thing: GitThing): GitThing =
## turning a thing into a thing involves no change
when false:
# crash
result = thing
else:
result = newThing(thing.o)
proc short*(oid: GitOid; size: int): GitResult[string] =
## shorten an oid to a string of the given length
assert not oid.isNil
var
output: cstring
withGit:
output = cast[cstring](alloc(size + 1))
output[size] = '\0'
withResultOf git_oid_nfmt(output, size.uint, oid):
result.ok $output
dealloc output
proc url*(remote: GitRemote): Uri =
## retrieve the url of a remote
assert not remote.isNil
withGit:
result = parseUri($git_remote_url(remote)).normalizeUrl
proc oid*(entry: GitTreeEntry): GitOid =
## retrieve the oid of the input
assert not entry.isNil
result = git_tree_entry_id(entry)
assert not result.isNil
proc oid*(got: GitReference): GitOid =
## retrieve the oid of the input
assert not got.isNil
result = git_reference_target(got)
assert not result.isNil
proc oid*(obj: GitObject): GitOid =
## retrieve the oid of the input
assert not obj.isNil
result = git_object_id(obj)
assert not result.isNil
proc oid*(thing: GitThing): GitOid =
## retrieve the oid of the input
assert not thing.isNil
assert not thing.o.isNil
result = thing.o.oid
assert not result.isNil
proc oid*(tag: GitTag): GitOid =
## retrieve the oid of the input
assert not tag.isNil
result = git_tag_id(tag)
assert not result.isNil
func name*(got: GitReference): string =
## retrieve the name of the input
assert not got.isNil
result = $git_reference_name(got)
func name*(entry: GitTreeEntry): string =
## retrieve the name of the input
assert not entry.isNil
result = $git_tree_entry_name(entry)
func name*(remote: GitRemote): string =
## retrieve the name of the input
assert not remote.isNil
result = $git_remote_name(remote)
func isTag*(got: GitReference): bool =
## true if the supplied reference is a tag
assert not got.isNil
result = git_reference_is_tag(got) == 1
proc flags*(status: GitStatus): set[GitStatusFlag] =
## produce the set of flags indicating the status of the file
assert not status.isNil
for flag in validGitStatusFlags.items:
if flag.ord.uint == bitand(status.status.uint, flag.ord.uint):
result.incl flag
proc repositoryPath*(repo: GitRepository): string =
## the path of the .git folder, or the repo itself if it's bare
result = $git_repository_path(repo)
func `$`*(tags: GitTagTable): string =
assert not tags.isNil
result = "{poorly-rendered tagtable}"
func `$`*(ps: GitPathSpec): string =
assert not ps.isNil
result = "{poorly-rendered pathspec}"
func `$`*(walker: GitRevWalker): string =
assert not walker.isNil
result = "{poorly-rendered revwalker}"
func `$`*(remote: GitRemote): string =
assert not remote.isNil
result = remote.name
func `$`*(repo: GitRepository): string =
assert not repo.isNil
result = repositoryPath(repo)
func `$`*(buffer: git_buf): string =
result = $cast[cstring](buffer)
func `$`*(buffer: ptr git_buf): string =
assert not buffer.isNil
result = $cast[cstring](buffer[])
func `$`*(annotated: ptr git_annotated_commit): string =
assert not annotated.isNil
result = $git_annotated_commit_ref(annotated)
func `$`*(oid: GitOid): string =
assert not oid.isNil
result = $git_oid_tostr_s(oid)
func `$`*(tag: GitTag): string =
assert not tag.isNil
let
name = git_tag_name(tag)
if name.isNil:
result = $name
func `$`*(reference: GitReference): string =
assert not reference.isNil
if reference.isTag:
result = reference.name
else:
result = $reference.oid
func `$`*(entry: GitTreeEntry): string =
assert not entry.isNil
result = entry.name
func `$`*(obj: GitObject): string =
## string representation of git object
assert not obj.isNil
let
kind = obj.kind
case kind:
of GIT_OBJECT_INVALID:
result = "{invalid}"
else:
result = $kind & "-" & $obj.git_object_id
func `$`*(commit: GitCommit): string =
assert not commit.isNil
result = $cast[GitObject](commit)
func `$`*(thing: GitThing): string =
assert not thing.isNil
assert not thing.o.isNil
result = $thing.o
func `$`*(status: GitStatus): string =
assert not status.isNil
for flag in status.flags.items:
if result != "":
result &= ","
result &= $flag
proc copy*(commit: GitCommit): GitResult[GitCommit] =
## create a copy of the commit; free it with free
assert not commit.isNil
var
dupe: GitCommit
withResultOf git_commit_dup(addr dupe, commit):
assert not dupe.isNil
result.ok dupe
proc copy*(thing: GitThing): GitResult[GitThing] =
## create a copy of the thing; free it with free
assert not thing.isNil
assert not thing.o.isNil
case thing.kind:
of GIT_OBJECT_INVALID:
result.err GIT_EINVALID
of GIT_OBJECT_COMMIT:
var
dupe: GitCommit
withResultOf git_commit_dup(addr dupe, cast[GitCommit](thing.o)):
result.ok newThing(dupe)
of GIT_OBJECT_TAG:
var
dupe: GitTag
withResultOf git_tag_dup(addr dupe, cast[GitTag](thing.o)):
result.ok newThing(dupe)
else:
var
dupe: GitObject
withResultOf git_object_dup(addr dupe, cast[GitObject](thing.o)):
result.ok newThing(dupe)
proc copy*(oid: GitOid): GitResult[GitOid] =
## create a copy of the oid; free it with dealloc
assert not oid.isNil
var
copied = cast[GitOid](sizeof(git_oid).alloc)
withResultOf git_oid_cpy(copied, oid):
result.ok copied
proc branchName*(got: GitReference): string =
## fetch a branch name assuming the reference is a branch
assert not got.isNil
withGit:
# we're going to assume that the reference name is
# no longer than the branch_name; we're using this
# assumption to create a name: cstring of the right
# size so we can branc_name into it safely...
var
name = git_reference_name(got)
block:
gitTrap git_branch_name(addr name, got).grc:
dumpError()
break
result = $name
proc isBranch*(got: GitReference): bool =
## true if the supplied reference is a branch
assert not got.isNil
withGit:
result = git_reference_is_branch(got) == 1
proc owner*(thing: GitThing): GitRepository =
## retrieve the repository that owns this thing
assert not thing.isNil
assert not thing.o.isNil
result = git_object_owner(thing.o)
assert not result.isNil
proc owner*(commit: GitCommit): GitRepository =
## retrieve the repository that owns this commit
assert not commit.isNil
result = git_commit_owner(commit)
assert not result.isNil
proc owner*(reference: GitReference): GitRepository =
## retrieve the repository that owns this reference
assert not reference.isNil
result = git_reference_owner(reference)
assert not result.isNil
proc setFlags[T](flags: seq[T] | set[T] | HashSet[T]): cuint =
for flag in flags.items:
result = bitor(result, flag.ord.cuint).cuint
proc message*(commit: GitCommit): string =
## retrieve the message associated with a git commit
assert not commit.isNil
withGit:
result = $git_commit_message(commit)
proc message*(tag: GitTag): string =
## retrieve the message associated with a git tag
assert not tag.isNil
withGit:
result = $git_tag_message(tag)
proc message*(thing: GitThing): string =
## retrieve the message associated with a git thing
assert not thing.isNil
assert not thing.o.isNil
case thing.kind:
of GIT_OBJECT_TAG:
result = cast[GitTag](thing.o).message
of GIT_OBJECT_COMMIT:
result = cast[GitCommit](thing.o).message
else:
raise ValueError.newException:
"Cannot get message for git object " &
$thing & " (kind was '" & $thing.kind & "')"
proc summary*(commit: GitCommit): string =
## produce a summary for a given commit
withGit:
assert not commit.isNil
result = $git_commit_summary(commit)
proc summary*(thing: GitThing): string =
## produce a summary for a git thing
assert not thing.isNil
assert not thing.o.isNil
case thing.kind:
of GIT_OBJECT_TAG:
result = cast[GitTag](thing.o).message
of GIT_OBJECT_COMMIT:
result = cast[GitCommit](thing.o).summary
else:
raise ValueError.newException:
"Cannot get summary for git object " &
$thing & " (kind was '" & $thing.kind & "')"
result = result.strip
proc free*(table: sink GitTagTable) =
## free a tag table
assert not table.isNil
withGit:
when defined(debugGit):
debug "\t~> freeing nim " & $typeof(table)
for tag, obj in table.mpairs:
when tag is GitTag:
tag.free
obj.free
disarm tag
disarm obj
elif tag is string:
obj.free
disarm obj
elif tag is GitThing:
let
same = tag == obj
tag.free
disarm tag
# make sure we don't free the same object twice
if not same:
obj.free
disarm obj
# working around nim-1.0 vs. nim-1.1
when (NimMajor, NimMinor) <= (1, 1):
var t = table
t.clear
else:
table.clear
#disarm table
proc hash*(oid: GitOid): Hash =
## the hash of a git oid is a function of its string representation
assert not oid.isNil
var h: Hash = 0
h = h !& hash($oid)
result = !$h
proc hash*(tag: GitTag): Hash =
## two tags are the same if they have the same name
assert not tag.isNil
var h: Hash = 0
h = h !& hash($tag)
result = !$h
proc hash*(thing: GitThing): Hash =
## two git things are unique unless they share the same oid
assert not thing.isNil
var h: Hash = 0
h = h !& hash(thing.oid)
result = !$h
proc commit*(thing: GitThing): GitCommit =
## turn a thing into its commit
assert not thing.isNil and thing.kind == GIT_OBJECT_COMMIT
result = cast[GitCommit](thing.o)
assert not result.isNil
proc committer*(thing: GitThing): GitSignature =
## get the committer of a thing that's a commit
assert not thing.isNil and thing.kind == GIT_OBJECT_COMMIT
result = git_commit_committer(cast[GitCommit](thing.o))
assert not result.isNil
proc author*(thing: GitThing): GitSignature =
## get the author of a thing that's a commit
assert not thing.isNil and thing.kind == GIT_OBJECT_COMMIT
result = git_commit_author(cast[GitCommit](thing.o))
assert not result.isNil
proc clone*(uri: Uri; path: string; branch = ""): GitResult[GitRepository] =
## clone a repository
withGit:
var
options = cast[ptr git_clone_options](sizeof(git_clone_options).alloc)
try:
withResultOf git_clone_options_init(options, GIT_CLONE_OPTIONS_VERSION):
if branch != "":
options.checkout_branch = branch
var
repo: GitRepository
withResultOf git_clone(addr repo, cstring($uri), path, options):
assert not repo.isNil
result.ok repo
finally:
dealloc options
proc setHeadDetached*(repo: GitRepository; oid: GitOid): GitResultCode =
## detach the HEAD and point it at the given OID
withGit:
result = git_repository_set_head_detached(repo, oid).grc
proc setHeadDetached*(repo: GitRepository; reference: string): GitResultCode =
## point the repo's head at the given reference
withGit:
var
oid: GitOid = cast[GitOid](sizeof(git_oid).alloc)
try:
withResultOf git_oid_fromstr(oid, reference):
assert not oid.isNil
result = repo.setHeadDetached(oid)
finally:
free oid
proc repositoryOpen*(path: string): GitResult[GitRepository] =
## open a repository by path; the repository must be freed
withGit:
var repo: GitRepository
withResultOf git_repository_open(addr repo, path):
assert not repo.isNil
result.ok repo
proc openRepository*(path: string): GitResult[GitRepository]
{.deprecated: "use repositoryOpen".} =
## alias for `repositoryOpen`
result = repositoryOpen(path)
proc fetchRemote*(repo: GitRepository; remoteName: string; refSpecs: GittyStrArray): GitResultCode =
## fetch from repo at `remoteName` using provided `refSpecs`
withGit:
var
fetchOpts: git_fetch_options
remote: GitRemote
withResultOf git_fetch_options_init(addr fetchOpts, GIT_FETCH_OPTIONS_VERSION):
withResultOf git_remote_lookup(addr remote, repo, remoteName.cstring):
assert not remote.isNil
try:
result = git_remote_fetch(remote, addr refSpecs, addr fetchOpts, "fetch").grc
finally:
free remote
proc fetchRemote*(repo: GitRepository; remoteName: string): GitResultCode =
## fetch from repo at given remoteName
var
refSpecs: GittyStrArray
fetchRemote(repo, remoteName, refSpecs)
proc repositoryHead*(repo: GitRepository): GitResult[GitReference] =
## fetch the reference for the repository's head; the reference must be freed
withGit:
var
head: GitReference
withResultOf git_repository_head(addr head, repo):
assert not head.isNil
result.ok head
proc headReference*(repo: GitRepository): GitResult[GitReference] =
## alias for repositoryHead
result = repositoryHead(repo)
proc getRemoteNames*(repo: GitRepository): GitResult[seq[string]] =
## get names of all remotes
withGit:
var
list: GitStrArray
try:
withResultOf git_remote_list(addr list, repo):
result.ok list.toStringSeq()
finally:
free list
proc fetchRemotes*(repo: GitRepository, remoteNames: seq[string]): seq[GitResultCode] =
## fetch from repo at given remoteNames
withGit:
for remoteName in remoteNames.items:
result.add:
fetchRemote(repo, remoteName)
proc remoteLookup*(repo: GitRepository; name: string): GitResult[GitRemote] =
## get the remote by name; the remote must be freed
withGit:
var
remote: GitRemote
withResultOf git_remote_lookup(addr remote, repo, name):
assert not remote.isNil
result.ok remote
proc remoteRename*(repo: GitRepository; prior: string;
next: string): GitResult[seq[string]] =
## rename a remote
withGit:
var
problems: GitStrArray
try:
withResultOf git_remote_rename(addr problems, repo, prior, next):
result.ok problems.toStringSeq()
finally:
free problems
proc remoteDelete*(repo: GitRepository; name: string): GitResultCode =
## delete a remote from the repository
withGit:
result = git_remote_delete(repo, name).grc
proc remoteCreate*(repo: GitRepository; name: string;
url: Uri): GitResult[GitRemote] =
## create a new remote in the repository
withGit:
var
remote: GitRemote
withResultOf git_remote_create(addr remote, repo, name.cstring, cstring($url)):
assert not remote.isNil
result.ok remote
proc `==`*(a, b: GitOid): bool =
## compare two oids using libgit2's special method
withGit:
if a.isNil or b.isNil:
result = false
elif 1 in [git_oid_is_zero(a), git_oid_is_zero(b)]:
result = false
else:
result = 1 == git_oid_equal(a, b)
# sanity
assert result == ($a == $b)
proc targetId*(thing: GitThing): GitOid =
## find the target oid to which a tag points
assert not thing.isNil
assert not thing.o.isNil
withGit:
result = git_tag_target_id(cast[GitTag](thing.o))
assert not result.isNil
proc target*(thing: GitThing): GitResult[GitThing] =
## find the thing to which a tag points
assert not thing.isNil
assert not thing.o.isNil