-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
libgit2.jl
3067 lines (2653 loc) · 126 KB
/
libgit2.jl
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
# This file is a part of Julia. License is MIT: https://julialang.org/license
module LibGit2Tests
import LibGit2
using Test
using Random, Serialization, Sockets
const BASE_TEST_PATH = joinpath(Sys.BINDIR, "..", "share", "julia", "test")
isdefined(Main, :FakePTYs) || @eval Main include(joinpath($(BASE_TEST_PATH), "testhelpers", "FakePTYs.jl"))
import .Main.FakePTYs: with_fake_pty
function challenge_prompt(code::Expr, challenges; timeout::Integer=60, debug::Bool=true)
input_code = tempname()
open(input_code, "w") do fp
serialize(fp, code)
end
output_file = tempname()
wrapped_code = quote
using Serialization
result = open($input_code) do fp
eval(deserialize(fp))
end
open($output_file, "w") do fp
serialize(fp, result)
end
end
torun = "import LibGit2; $wrapped_code"
cmd = `$(Base.julia_cmd()) --startup-file=no -e $torun`
try
challenge_prompt(cmd, challenges, timeout=timeout, debug=debug)
return open(output_file, "r") do fp
deserialize(fp)
end
finally
isfile(output_file) && rm(output_file)
isfile(input_code) && rm(input_code)
end
return nothing
end
function challenge_prompt(cmd::Cmd, challenges; timeout::Integer=60, debug::Bool=true)
function format_output(output)
!debug && return ""
str = read(seekstart(output), String)
isempty(str) && return ""
return "Process output found:\n\"\"\"\n$str\n\"\"\""
end
out = IOBuffer()
with_fake_pty() do pty_slave, pty_master
p = run(detach(cmd), pty_slave, pty_slave, pty_slave, wait=false)
Base.close_stdio(pty_slave)
# Kill the process if it takes too long. Typically occurs when process is waiting
# for input.
timer = Channel{Symbol}(1)
watcher = @async begin
waited = 0
while waited < timeout && process_running(p)
sleep(1)
waited += 1
end
if process_running(p)
kill(p)
put!(timer, :timeout)
elseif success(p)
put!(timer, :success)
else
put!(timer, :failure)
end
# SIGKILL stubborn processes
if process_running(p)
sleep(3)
process_running(p) && kill(p, Base.SIGKILL)
end
wait(p)
end
for (challenge, response) in challenges
write(out, readuntil(pty_master, challenge, keep=true))
if !isopen(pty_master)
error("Could not locate challenge: \"$challenge\". ",
format_output(out))
end
write(pty_master, response)
end
# Capture output from process until `pty_slave` is closed
try
write(out, pty_master)
catch ex
if !(ex isa Base.IOError && ex.code == Base.UV_EIO)
rethrow() # ignore EIO from master after slave dies
end
end
status = fetch(timer)
close(pty_master)
if status != :success
if status == :timeout
error("Process timed out possibly waiting for a response. ",
format_output(out))
else
error("Failed process. ", format_output(out), "\n", p)
end
end
wait(watcher)
end
nothing
end
const LIBGIT2_MIN_VER = v"0.23.0"
const LIBGIT2_HELPER_PATH = joinpath(@__DIR__, "libgit2-helpers.jl")
const KEY_DIR = joinpath(@__DIR__, "keys")
const HOME = Sys.iswindows() ? "USERPROFILE" : "HOME" # Environment variable name for home
const GIT_INSTALLED = try
success(`git --version`)
catch
false
end
function get_global_dir()
buf = Ref(LibGit2.Buffer())
LibGit2.@check ccall((:git_libgit2_opts, :libgit2), Cint,
(Cint, Cint, Ptr{LibGit2.Buffer}),
LibGit2.Consts.GET_SEARCH_PATH, LibGit2.Consts.CONFIG_LEVEL_GLOBAL, buf)
path = unsafe_string(buf[].ptr)
LibGit2.free(buf)
return path
end
function set_global_dir(dir)
LibGit2.@check ccall((:git_libgit2_opts, :libgit2), Cint,
(Cint, Cint, Cstring),
LibGit2.Consts.SET_SEARCH_PATH, LibGit2.Consts.CONFIG_LEVEL_GLOBAL, dir)
return
end
function with_libgit2_temp_home(f)
mktempdir() do tmphome
oldpath = get_global_dir()
set_global_dir(tmphome)
try
@test get_global_dir() == tmphome
f(tmphome)
finally
set_global_dir(oldpath)
end
return
end
end
#########
# TESTS #
#########
@testset "Check library version" begin
v = LibGit2.version()
@test v.major == LIBGIT2_MIN_VER.major && v.minor >= LIBGIT2_MIN_VER.minor
end
@testset "Check library features" begin
f = LibGit2.features()
@test findfirst(isequal(LibGit2.Consts.FEATURE_SSH), f) !== nothing
@test findfirst(isequal(LibGit2.Consts.FEATURE_HTTPS), f) !== nothing
end
@testset "OID" begin
z = LibGit2.GitHash()
@test LibGit2.iszero(z)
@test z == zero(LibGit2.GitHash)
@test z == LibGit2.GitHash(z)
rs = string(z)
rr = LibGit2.raw(z)
@test z == LibGit2.GitHash(rr)
@test z == LibGit2.GitHash(rs)
@test z == LibGit2.GitHash(pointer(rr))
@test LibGit2.GitShortHash(z, 20) == LibGit2.GitShortHash(rs[1:20])
@test_throws ArgumentError LibGit2.GitHash(Ptr{UInt8}(C_NULL))
@test_throws ArgumentError LibGit2.GitHash(rand(UInt8, 2*LibGit2.OID_RAWSZ))
@test_throws ArgumentError LibGit2.GitHash("a")
end
@testset "StrArrayStruct" begin
p = ["XXX","YYY"]
a = Base.cconvert(Ptr{LibGit2.StrArrayStruct}, p)
b = Base.unsafe_convert(Ptr{LibGit2.StrArrayStruct}, a)
@test p == convert(Vector{String}, unsafe_load(b))
@noinline gcuse(a) = a
gcuse(a)
end
@testset "Signature" begin
sig = LibGit2.Signature("AAA", "[email protected]", round(time(); digits=0), 0)
git_sig = convert(LibGit2.GitSignature, sig)
sig2 = LibGit2.Signature(git_sig)
close(git_sig)
@test sig.name == sig2.name
@test sig.email == sig2.email
@test sig.time == sig2.time
sig3 = LibGit2.Signature("AAA","[email protected]")
@test sig3.name == sig.name
@test sig3.email == sig.email
end
@testset "Default config" begin
with_libgit2_temp_home() do tmphome
cfg = LibGit2.GitConfig()
@test isa(cfg, LibGit2.GitConfig)
@test LibGit2.getconfig("fake.property", "") == ""
LibGit2.set!(cfg, "fake.property", "AAAA")
@test LibGit2.getconfig("fake.property", "") == "AAAA"
end
end
# See #21872 and #21636
LibGit2.version() >= v"0.26.0" && Sys.isunix() && @testset "Default config with symlink" begin
with_libgit2_temp_home() do tmphome
write(joinpath(tmphome, "real_gitconfig"), "[fake]\n\tproperty = BBB")
symlink(joinpath(tmphome, "real_gitconfig"),
joinpath(tmphome, ".gitconfig"))
cfg = LibGit2.GitConfig()
@test isa(cfg, LibGit2.GitConfig)
LibGit2.getconfig("fake.property", "") == "BBB"
LibGit2.set!(cfg, "fake.property", "AAAA")
LibGit2.getconfig("fake.property", "") == "AAAA"
end
end
@testset "Git URL parsing" begin
@testset "HTTPS URL" begin
m = match(LibGit2.URL_REGEX, "https://user:[email protected]:80/org/project.git")
@test m[:scheme] == "https"
@test m[:user] == "user"
@test m[:password] == "pass"
@test m[:host] == "server.com"
@test m[:port] == "80"
@test m[:path] == "org/project.git"
end
@testset "SSH URL" begin
m = match(LibGit2.URL_REGEX, "ssh://user:pass@server:22/project.git")
@test m[:scheme] == "ssh"
@test m[:user] == "user"
@test m[:password] == "pass"
@test m[:host] == "server"
@test m[:port] == "22"
@test m[:path] == "project.git"
end
@testset "SSH URL, scp-like syntax" begin
m = match(LibGit2.URL_REGEX, "user@server:project.git")
@test m[:scheme] === nothing
@test m[:user] == "user"
@test m[:password] === nothing
@test m[:host] == "server"
@test m[:port] === nothing
@test m[:path] == "project.git"
end
# scp-like syntax corner case. The SCP syntax does not support port so everything after
# the colon is part of the path.
@testset "scp-like syntax, no port" begin
m = match(LibGit2.URL_REGEX, "server:1234/repo")
@test m[:scheme] === nothing
@test m[:user] === nothing
@test m[:password] === nothing
@test m[:host] == "server"
@test m[:port] === nothing
@test m[:path] == "1234/repo"
end
@testset "HTTPS URL, realistic" begin
m = match(LibGit2.URL_REGEX, "https://github.com/JuliaLang/Example.jl.git")
@test m[:scheme] == "https"
@test m[:user] === nothing
@test m[:password] === nothing
@test m[:host] == "github.com"
@test m[:port] === nothing
@test m[:path] == "JuliaLang/Example.jl.git"
end
@testset "SSH URL, realistic" begin
m = match(LibGit2.URL_REGEX, "[email protected]:JuliaLang/Example.jl.git")
@test m[:scheme] === nothing
@test m[:user] == "git"
@test m[:password] === nothing
@test m[:host] == "github.com"
@test m[:port] === nothing
@test m[:path] == "JuliaLang/Example.jl.git"
end
@testset "usernames with special characters" begin
m = match(LibGit2.URL_REGEX, "[email protected]")
@test m[:user] == "user-name"
end
@testset "HTTPS URL, no path" begin
m = match(LibGit2.URL_REGEX, "https://user:[email protected]:80")
@test m[:path] === nothing
end
@testset "scp-like syntax, no path" begin
m = match(LibGit2.URL_REGEX, "user@server:")
@test m[:path] == ""
m = match(LibGit2.URL_REGEX, "user@server")
@test m[:path] === nothing
end
@testset "HTTPS URL, invalid path" begin
m = match(LibGit2.URL_REGEX, "https://git@server:repo")
@test m === nothing
end
# scp-like syntax should have a colon separating the hostname from the path
@testset "scp-like syntax, invalid path" begin
m = match(LibGit2.URL_REGEX, "git@server/repo")
@test m === nothing
end
end
@testset "Git URL formatting" begin
@testset "HTTPS URL" begin
url = LibGit2.git_url(
scheme="https",
username="user",
host="server.com",
port=80,
path="org/project.git")
@test url == "https://[email protected]:80/org/project.git"
end
@testset "SSH URL" begin
url = LibGit2.git_url(
scheme="ssh",
username="user",
host="server",
port="22",
path="project.git")
@test url == "ssh://user@server:22/project.git"
end
@testset "SSH URL, scp-like syntax" begin
url = LibGit2.git_url(
username="user",
host="server",
path="project.git")
@test url == "user@server:project.git"
end
@testset "HTTPS URL, realistic" begin
url = LibGit2.git_url(
scheme="https",
host="github.com",
path="JuliaLang/Example.jl.git")
@test url == "https://github.com/JuliaLang/Example.jl.git"
end
@testset "SSH URL, realistic" begin
url = LibGit2.git_url(
username="git",
host="github.com",
path="JuliaLang/Example.jl.git")
@test url == "[email protected]:JuliaLang/Example.jl.git"
end
@testset "HTTPS URL, no path" begin
url = LibGit2.git_url(
scheme="https",
username="user",
host="server.com",
port="80")
@test url == "https://[email protected]:80"
end
@testset "scp-like syntax, no path" begin
url = LibGit2.git_url(
username="user",
host="server.com")
@test url == "[email protected]"
end
@testset "HTTP URL, path includes slash prefix" begin
url = LibGit2.git_url(
scheme="http",
host="server.com",
path="/path")
@test url == "http://server.com/path"
end
@testset "empty" begin
@test_throws ArgumentError LibGit2.git_url()
@test LibGit2.git_url(host="server.com") == "server.com"
url = LibGit2.git_url(
scheme="",
username="",
host="server.com",
port="",
path="")
@test url == "server.com"
end
end
@testset "Passphrase Required" begin
@testset "missing file" begin
@test !LibGit2.is_passphrase_required("")
file = joinpath(KEY_DIR, "foobar")
@test !isfile(file)
@test !LibGit2.is_passphrase_required(file)
end
@testset "not private key" begin
@test !LibGit2.is_passphrase_required(joinpath(KEY_DIR, "invalid.pub"))
end
@testset "private key, with passphrase" begin
@test LibGit2.is_passphrase_required(joinpath(KEY_DIR, "valid-passphrase"))
end
@testset "private key, no passphrase" begin
@test !LibGit2.is_passphrase_required(joinpath(KEY_DIR, "valid"))
end
end
@testset "GitCredential" begin
@testset "missing" begin
str = ""
cred = read!(IOBuffer(str), LibGit2.GitCredential())
@test cred == LibGit2.GitCredential()
@test sprint(write, cred) == str
Base.shred!(cred)
end
@testset "empty" begin
str = """
protocol=
host=
path=
username=
password=
"""
cred = read!(IOBuffer(str), LibGit2.GitCredential())
@test cred == LibGit2.GitCredential("", "", "", "", "")
@test sprint(write, cred) == str
Base.shred!(cred)
end
@testset "input/output" begin
str = """
protocol=https
host=example.com
username=alice
password=*****
"""
expected_cred = LibGit2.GitCredential("https", "example.com", nothing, "alice", "*****")
cred = read!(IOBuffer(str), LibGit2.GitCredential())
@test cred == expected_cred
@test sprint(write, cred) == str
Base.shred!(cred)
Base.shred!(expected_cred)
end
@testset "extra newline" begin
# The "Git for Windows" installer will also install the "Git Credential Manager for
# Windows" (https://github.com/Microsoft/Git-Credential-Manager-for-Windows) (also
# known as "manager" in the .gitconfig files). This credential manager returns an
# additional newline when returning the results.
str = """
protocol=https
host=example.com
path=
username=bob
password=*****
"""
expected_cred = LibGit2.GitCredential("https", "example.com", "", "bob", "*****")
cred = read!(IOBuffer(str), LibGit2.GitCredential())
@test cred == expected_cred
@test sprint(write, cred) * "\n" == str
Base.shred!(cred)
Base.shred!(expected_cred)
end
@testset "unknown attribute" begin
str = """
protocol=https
host=example.com
attribute=value
username=bob
password=*****
"""
expected_cred = LibGit2.GitCredential("https", "example.com", nothing, "bob", "*****")
expected_log = (:warn, "Unknown git credential attribute found: \"attribute\"")
cred = @test_logs expected_log read!(IOBuffer(str), LibGit2.GitCredential())
@test cred == expected_cred
Base.shred!(cred)
Base.shred!(expected_cred)
end
@testset "use http path" begin
cred = LibGit2.GitCredential("https", "example.com", "dir/file", "alice", "*****")
expected = """
protocol=https
host=example.com
username=alice
password=*****
"""
@test cred.use_http_path
cred.use_http_path = false
@test cred.path == "dir/file"
@test sprint(write, cred) == expected
Base.shred!(cred)
end
@testset "URL input/output" begin
str = """
host=example.com
password=bar
url=https://a@b/c
username=foo
"""
expected_str = """
protocol=https
host=b
path=c
username=foo
"""
expected_cred = LibGit2.GitCredential("https", "b", "c", "foo", nothing)
cred = read!(IOBuffer(str), LibGit2.GitCredential())
@test cred == expected_cred
@test sprint(write, cred) == expected_str
Base.shred!(cred)
Base.shred!(expected_cred)
end
@testset "ismatch" begin
# Equal
cred = LibGit2.GitCredential("https", "github.com")
@test LibGit2.ismatch("https://github.com", cred)
Base.shred!(cred)
# Credential hostname is different
cred = LibGit2.GitCredential("https", "github.com")
@test !LibGit2.ismatch("https://myhost", cred)
Base.shred!(cred)
# Credential is less specific than URL
cred = LibGit2.GitCredential("https")
@test !LibGit2.ismatch("https://github.com", cred)
Base.shred!(cred)
# Credential is more specific than URL
cred = LibGit2.GitCredential("https", "github.com", "path", "user", "pass")
@test LibGit2.ismatch("https://github.com", cred)
Base.shred!(cred)
# Credential needs to have an "" username to match
cred = LibGit2.GitCredential("https", "github.com", nothing, "")
@test LibGit2.ismatch("https://@github.com", cred)
Base.shred!(cred)
cred = LibGit2.GitCredential("https", "github.com", nothing, nothing)
@test !LibGit2.ismatch("https://@github.com", cred)
Base.shred!(cred)
end
@testset "GITHUB_REGEX" begin
github_regex_test = function(url, user, repo)
m = match(LibGit2.GITHUB_REGEX, url)
@test m !== nothing
@test m[1] == "$user/$repo"
@test m[2] == user
@test m[3] == repo
end
user = "User"
repo = "Repo"
github_regex_test("[email protected]/$user/$repo.git", user, repo)
github_regex_test("https://github.com/$user/$repo.git", user, repo)
github_regex_test("https://[email protected]/$user/$repo.git", user, repo)
github_regex_test("ssh://[email protected]/$user/$repo.git", user, repo)
github_regex_test("[email protected]/$user/$repo", user, repo)
github_regex_test("https://github.com/$user/$repo", user, repo)
github_regex_test("https://[email protected]/$user/$repo", user, repo)
github_regex_test("ssh://[email protected]/$user/$repo", user, repo)
@test !occursin(LibGit2.GITHUB_REGEX, "[email protected]/$user/$repo.git")
end
end
mktempdir() do dir
dir = realpath(dir)
# test parameters
repo_url = "https://github.com/JuliaLang/Example.jl"
cache_repo = joinpath(dir, "Example")
test_repo = joinpath(dir, "Example.Test")
test_sig = LibGit2.Signature("TEST", "[email protected]", round(time(); digits=0), 0)
test_dir = "testdir"
test_file = "$(test_dir)/testfile"
config_file = "testconfig"
commit_msg1 = randstring(10)
commit_msg2 = randstring(10)
commit_oid1 = LibGit2.GitHash()
commit_oid2 = LibGit2.GitHash()
commit_oid3 = LibGit2.GitHash()
master_branch = "master"
test_branch = "test_branch"
test_branch2 = "test_branch_two"
tag1 = "tag1"
tag2 = "tag2"
@testset "Configuration" begin
LibGit2.with(LibGit2.GitConfig(joinpath(dir, config_file), LibGit2.Consts.CONFIG_LEVEL_APP)) do cfg
@test_throws LibGit2.Error.GitError LibGit2.get(AbstractString, cfg, "tmp.str")
@test isempty(LibGit2.get(cfg, "tmp.str", "")) == true
LibGit2.set!(cfg, "tmp.str", "AAAA")
LibGit2.set!(cfg, "tmp.int32", Int32(1))
LibGit2.set!(cfg, "tmp.int64", Int64(1))
LibGit2.set!(cfg, "tmp.bool", true)
@test LibGit2.get(cfg, "tmp.str", "") == "AAAA"
@test LibGit2.get(cfg, "tmp.int32", Int32(0)) == Int32(1)
@test LibGit2.get(cfg, "tmp.int64", Int64(0)) == Int64(1)
@test LibGit2.get(cfg, "tmp.bool", false) == true
# Ordering of entries appears random when using `LibGit2.set!`
count = 0
for entry in LibGit2.GitConfigIter(cfg, r"tmp.*")
count += 1
name, value = unsafe_string(entry.name), unsafe_string(entry.value)
if name == "tmp.str"
@test value == "AAAA"
elseif name == "tmp.int32"
@test value == "1"
elseif name == "tmp.int64"
@test value == "1"
elseif name == "tmp.bool"
@test value == "true"
else
error("Found unexpected entry: $name")
end
show_str = sprint(show, entry)
@test show_str == string("ConfigEntry(\"", name, "\", \"", value, "\")")
end
@test count == 4
end
end
@testset "Configuration Iteration" begin
config_path = joinpath(dir, config_file)
# Write config entries with duplicate names
open(config_path, "a") do fp
write(fp, """
[credential]
helper = store
username = julia
[credential]
helper = cache
""")
end
LibGit2.with(LibGit2.GitConfig(config_path, LibGit2.Consts.CONFIG_LEVEL_APP)) do cfg
# Will only see the last entry
@test LibGit2.get(cfg, "credential.helper", "") == "cache"
count = 0
for entry in LibGit2.GitConfigIter(cfg, "credential.helper")
count += 1
name, value = unsafe_string(entry.name), unsafe_string(entry.value)
@test name == "credential.helper"
@test value == (count == 1 ? "store" : "cache")
end
@test count == 2
end
end
@testset "Initializing repository" begin
@testset "with remote branch" begin
LibGit2.with(LibGit2.init(cache_repo)) do repo
@test isdir(cache_repo)
@test LibGit2.path(repo) == LibGit2.posixpath(realpath(cache_repo))
@test isdir(joinpath(cache_repo, ".git"))
# set a remote branch
branch = "upstream"
LibGit2.GitRemote(repo, branch, repo_url) |> close
# test remote's representation in the repo's config
config = joinpath(cache_repo, ".git", "config")
lines = split(open(x->read(x, String), config, "r"), "\n")
@test any(map(x->x == "[remote \"upstream\"]", lines))
LibGit2.with(LibGit2.get(LibGit2.GitRemote, repo, branch)) do remote
# test various remote properties
@test LibGit2.url(remote) == repo_url
@test LibGit2.push_url(remote) == ""
@test LibGit2.name(remote) == "upstream"
@test isa(remote, LibGit2.GitRemote)
# test showing a GitRemote object
@test sprint(show, remote) == "GitRemote:\nRemote name: upstream url: $repo_url"
end
# test setting and getting the remote's URL
@test LibGit2.isattached(repo)
LibGit2.set_remote_url(repo, "upstream", "unknown")
LibGit2.with(LibGit2.get(LibGit2.GitRemote, repo, branch)) do remote
@test LibGit2.url(remote) == "unknown"
@test LibGit2.push_url(remote) == "unknown"
@test sprint(show, remote) == "GitRemote:\nRemote name: upstream url: unknown"
end
LibGit2.set_remote_url(cache_repo, "upstream", repo_url)
LibGit2.with(LibGit2.get(LibGit2.GitRemote, repo, branch)) do remote
@test LibGit2.url(remote) == repo_url
@test LibGit2.push_url(remote) == repo_url
@test sprint(show, remote) == "GitRemote:\nRemote name: upstream url: $repo_url"
LibGit2.add_fetch!(repo, remote, "upstream")
# test setting fetch and push refspecs
@test LibGit2.fetch_refspecs(remote) == String["+refs/heads/*:refs/remotes/upstream/*"]
LibGit2.add_push!(repo, remote, "refs/heads/master")
end
LibGit2.with(LibGit2.get(LibGit2.GitRemote, repo, branch)) do remote
@test LibGit2.push_refspecs(remote) == String["refs/heads/master"]
end
# constructor with a refspec
LibGit2.with(LibGit2.GitRemote(repo, "upstream2", repo_url, "upstream")) do remote
@test sprint(show, remote) == "GitRemote:\nRemote name: upstream2 url: $repo_url"
@test LibGit2.fetch_refspecs(remote) == String["upstream"]
end
LibGit2.with(LibGit2.GitRemoteAnon(repo, repo_url)) do remote
@test LibGit2.url(remote) == repo_url
@test LibGit2.push_url(remote) == ""
@test LibGit2.name(remote) == ""
@test isa(remote, LibGit2.GitRemote)
end
end
end
@testset "bare" begin
path = joinpath(dir, "Example.Bare")
LibGit2.with(LibGit2.init(path, true)) do repo
@test isdir(path)
@test LibGit2.path(repo) == LibGit2.posixpath(realpath(path))
@test isfile(joinpath(path, LibGit2.Consts.HEAD_FILE))
@test LibGit2.isattached(repo)
end
path = joinpath("garbagefakery", "Example.Bare")
try
LibGit2.GitRepo(path)
error("unexpected")
catch e
@test typeof(e) == LibGit2.GitError
@test startswith(
lowercase(sprint(show, e)),
lowercase("GitError(Code:ENOTFOUND, Class:OS, failed to resolve path"))
end
path = joinpath(dir, "Example.BareTwo")
LibGit2.with(LibGit2.init(path, true)) do repo
#just to see if this works
LibGit2.cleanup(repo)
end
end
end
@testset "Cloning repository" begin
function bare_repo_tests(repo, repo_path)
@test isdir(repo_path)
@test LibGit2.path(repo) == LibGit2.posixpath(realpath(repo_path))
@test isfile(joinpath(repo_path, LibGit2.Consts.HEAD_FILE))
@test LibGit2.isattached(repo)
@test LibGit2.remotes(repo) == ["origin"]
end
@testset "bare" begin
repo_path = joinpath(dir, "Example.Bare1")
LibGit2.with(LibGit2.clone(cache_repo, repo_path, isbare = true)) do repo
bare_repo_tests(repo, repo_path)
end
end
@testset "bare with remote callback" begin
repo_path = joinpath(dir, "Example.Bare2")
LibGit2.with(LibGit2.clone(cache_repo, repo_path, isbare = true, remote_cb = LibGit2.mirror_cb())) do repo
bare_repo_tests(repo, repo_path)
LibGit2.with(LibGit2.get(LibGit2.GitRemote, repo, "origin")) do rmt
@test LibGit2.fetch_refspecs(rmt)[1] == "+refs/*:refs/*"
end
end
end
@testset "normal" begin
LibGit2.with(LibGit2.clone(cache_repo, test_repo)) do repo
@test isdir(test_repo)
@test LibGit2.path(repo) == LibGit2.posixpath(realpath(test_repo))
@test isdir(joinpath(test_repo, ".git"))
@test LibGit2.workdir(repo) == LibGit2.path(repo)*"/"
@test LibGit2.isattached(repo)
@test LibGit2.isorphan(repo)
repo_str = sprint(show, repo)
@test repo_str == "LibGit2.GitRepo($(sprint(show,LibGit2.path(repo))))"
end
end
@testset "credentials callback conflict" begin
callbacks = LibGit2.Callbacks(:credentials => (C_NULL, 0))
cred_payload = LibGit2.CredentialPayload()
@test_throws ArgumentError LibGit2.clone(cache_repo, test_repo, callbacks=callbacks, credentials=cred_payload)
end
end
@testset "Update cache repository" begin
@testset "with commits" begin
repo = LibGit2.GitRepo(cache_repo)
repo_dir = joinpath(cache_repo,test_dir)
mkdir(repo_dir)
repo_file = open(joinpath(cache_repo,test_file), "a")
try
# create commits
println(repo_file, commit_msg1)
flush(repo_file)
LibGit2.add!(repo, test_file)
@test LibGit2.iszero(commit_oid1)
commit_oid1 = LibGit2.commit(repo, commit_msg1; author=test_sig, committer=test_sig)
@test !LibGit2.iszero(commit_oid1)
@test LibGit2.GitHash(LibGit2.head(cache_repo)) == commit_oid1
println(repo_file, randstring(10))
flush(repo_file)
LibGit2.add!(repo, test_file)
commit_oid3 = LibGit2.commit(repo, randstring(10); author=test_sig, committer=test_sig)
println(repo_file, commit_msg2)
flush(repo_file)
LibGit2.add!(repo, test_file)
@test LibGit2.iszero(commit_oid2)
commit_oid2 = LibGit2.commit(repo, commit_msg2; author=test_sig, committer=test_sig)
@test !LibGit2.iszero(commit_oid2)
# test getting list of commit authors
auths = LibGit2.authors(repo)
@test length(auths) == 3
for auth in auths
@test auth.name == test_sig.name
@test auth.time == test_sig.time
@test auth.email == test_sig.email
end
# check various commit properties - commit_oid1 happened before
# commit_oid2, so it *is* an ancestor of commit_oid2
@test LibGit2.is_ancestor_of(string(commit_oid1), string(commit_oid2), repo)
@test LibGit2.iscommit(string(commit_oid1), repo)
@test !LibGit2.iscommit(string(commit_oid1)*"fake", repo)
@test LibGit2.iscommit(string(commit_oid2), repo)
# lookup commits
LibGit2.with(LibGit2.GitCommit(repo, commit_oid1)) do cmt
@test LibGit2.Consts.OBJECT(typeof(cmt)) == LibGit2.Consts.OBJ_COMMIT
@test commit_oid1 == LibGit2.GitHash(cmt)
short_oid1 = LibGit2.GitShortHash(string(commit_oid1))
@test string(commit_oid1) == string(short_oid1)
@test cmp(commit_oid1, short_oid1) == 0
@test cmp(short_oid1, commit_oid1) == 0
@test !(short_oid1 < commit_oid1)
# test showing ShortHash
short_str = sprint(show, short_oid1)
@test short_str == "GitShortHash(\"$(string(short_oid1))\")"
short_oid2 = LibGit2.GitShortHash(cmt)
@test startswith(string(commit_oid1), string(short_oid2))
LibGit2.with(LibGit2.GitCommit(repo, short_oid2)) do cmt2
@test commit_oid1 == LibGit2.GitHash(cmt2)
end
# check that the author and committer signatures are correct
auth = LibGit2.author(cmt)
@test isa(auth, LibGit2.Signature)
@test auth.name == test_sig.name
@test auth.time == test_sig.time
@test auth.email == test_sig.email
short_auth = LibGit2.author(LibGit2.GitCommit(repo, short_oid1))
@test short_auth.name == test_sig.name
@test short_auth.time == test_sig.time
@test short_auth.email == test_sig.email
cmtr = LibGit2.committer(cmt)
@test isa(cmtr, LibGit2.Signature)
@test cmtr.name == test_sig.name
@test cmtr.time == test_sig.time
@test cmtr.email == test_sig.email
@test LibGit2.message(cmt) == commit_msg1
# test showing the commit
showstr = split(sprint(show, cmt), "\n")
# the time of the commit will vary so just test the first two parts
@test occursin("Git Commit:", showstr[1])
@test occursin("Commit Author: Name: TEST, Email: [email protected], Time:", showstr[2])
@test occursin("Committer: Name: TEST, Email: [email protected], Time:", showstr[3])
@test occursin("SHA:", showstr[4])
@test showstr[5] == "Message:"
@test showstr[6] == commit_msg1
@test LibGit2.revcount(repo, string(commit_oid1), string(commit_oid3)) == (-1,0)
blame = LibGit2.GitBlame(repo, test_file)
@test LibGit2.counthunks(blame) == 3
@test_throws BoundsError getindex(blame, LibGit2.counthunks(blame)+1)
@test_throws BoundsError getindex(blame, 0)
sig = LibGit2.Signature(blame[1].orig_signature)
@test sig.name == cmtr.name
@test sig.email == cmtr.email
show_strs = split(sprint(show, blame[1]), "\n")
@test show_strs[1] == "GitBlameHunk:"
@test show_strs[2] == "Original path: $test_file"
@test show_strs[3] == "Lines in hunk: 1"
@test show_strs[4] == "Final commit oid: $commit_oid1"
@test show_strs[6] == "Original commit oid: $commit_oid1"
@test length(show_strs) == 7
end
finally
close(repo)
close(repo_file)
end
end
@testset "with branch" begin
LibGit2.with(LibGit2.GitRepo(cache_repo)) do repo
brnch = LibGit2.branch(repo)
LibGit2.with(LibGit2.head(repo)) do brref
# various branch properties
@test LibGit2.isbranch(brref)
@test !LibGit2.isremote(brref)
@test LibGit2.name(brref) == "refs/heads/master"
@test LibGit2.shortname(brref) == master_branch
@test LibGit2.ishead(brref)
@test LibGit2.upstream(brref) === nothing
# showing the GitReference to this branch
show_strs = split(sprint(show, brref), "\n")
@test show_strs[1] == "GitReference:"
@test show_strs[2] == "Branch with name refs/heads/master"
@test show_strs[3] == "Branch is HEAD."
@test repo.ptr == LibGit2.repository(brref).ptr
@test brnch == master_branch
@test LibGit2.headname(repo) == master_branch
# create a branch *without* setting its tip as HEAD
LibGit2.branch!(repo, test_branch, string(commit_oid1), set_head=false)
# null because we are looking for a REMOTE branch
@test LibGit2.lookup_branch(repo, test_branch, true) === nothing
# not nothing because we are now looking for a LOCAL branch
LibGit2.with(LibGit2.lookup_branch(repo, test_branch, false)) do tbref
@test LibGit2.shortname(tbref) == test_branch
@test LibGit2.upstream(tbref) === nothing
end
@test LibGit2.lookup_branch(repo, test_branch2, true) === nothing
# test deleting the branch
LibGit2.branch!(repo, test_branch2; set_head=false)
LibGit2.with(LibGit2.lookup_branch(repo, test_branch2, false)) do tbref
@test LibGit2.shortname(tbref) == test_branch2
LibGit2.delete_branch(tbref)
@test LibGit2.lookup_branch(repo, test_branch2, true) === nothing
end
end
branches = map(b->LibGit2.shortname(b[1]), LibGit2.GitBranchIter(repo))
@test master_branch in branches
@test test_branch in branches
end
end
@testset "with default configuration" begin
LibGit2.with(LibGit2.GitRepo(cache_repo)) do repo
try
LibGit2.Signature(repo)
catch ex
# these test configure repo with new signature
# in case when global one does not exsist
@test isa(ex, LibGit2.Error.GitError) == true
cfg = LibGit2.GitConfig(repo)
LibGit2.set!(cfg, "user.name", "AAAA")
LibGit2.set!(cfg, "user.email", "[email protected]")
sig = LibGit2.Signature(repo)
@test sig.name == "AAAA"
@test sig.email == "[email protected]"
@test LibGit2.getconfig(repo, "user.name", "") == "AAAA"
@test LibGit2.getconfig(cache_repo, "user.name", "") == "AAAA"
end
end
end
@testset "with tags" begin