Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork966
Expand file tree
/
Copy pathtest_submodule.py
More file actions
1377 lines (1170 loc) · 55.2 KB
/
test_submodule.py
File metadata and controls
1377 lines (1170 loc) · 55.2 KB
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 module is part of GitPython and is released under the
# 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
importcontextlib
importgc
importos
importos.pathasosp
frompathlibimportPath
importshutil
importsys
importtempfile
fromunittestimportmock,skipUnless
importpytest
importgit
fromgit.cmdimportGit
fromgit.configimportGitConfigParser,cp
fromgit.excimport (
GitCommandError,
InvalidGitRepositoryError,
RepositoryDirtyError,
UnsafeOptionError,
UnsafeProtocolError,
)
fromgit.objects.submodule.baseimportSubmodule
fromgit.objects.submodule.rootimportRootModule,RootUpdateProgress
fromgit.repo.funimportfind_submodule_git_dir,touch
fromgit.utilimportHIDE_WINDOWS_KNOWN_ERRORS,join_path_native,to_native_path_linux
fromtest.libimportTestBase,with_rw_directory,with_rw_repo,PathLikeMock
@contextlib.contextmanager
def_patch_git_config(name,value):
"""Temporarily add a git config name-value pair, using environment variables."""
pair_index=int(os.getenv("GIT_CONFIG_COUNT","0"))
# This is recomputed each time the context is entered, for compatibility with
# existing GIT_CONFIG_* environment variables, even if changed in this process.
patcher=mock.patch.dict(
os.environ,
{
"GIT_CONFIG_COUNT":str(pair_index+1),
f"GIT_CONFIG_KEY_{pair_index}":name,
f"GIT_CONFIG_VALUE_{pair_index}":value,
},
)
withpatcher:
yield
classTestRootProgress(RootUpdateProgress):
"""Just prints messages, for now without checking the correctness of the states"""
defupdate(self,op,cur_count,max_count,message=""):
print(op,cur_count,max_count,message)
TestRootProgress.__test__=False
prog=TestRootProgress()
classTestSubmodule(TestBase):
deftearDown(self):
gc.collect()
k_subm_current="c15a6e1923a14bc760851913858a3942a4193cdb"
k_subm_changed="394ed7006ee5dc8bddfd132b64001d5dfc0ffdd3"
k_no_subm_tag="0.1.6"
def_do_base_tests(self,rwrepo):
"""Perform all tests in the given repository, it may be bare or nonbare"""
# Manual instantiation.
smm=Submodule(rwrepo,"\0"*20)
# Name needs to be set in advance.
self.assertRaises(AttributeError,getattr,smm,"name")
# Iterate - 1 submodule.
sms=Submodule.list_items(rwrepo,self.k_subm_current)
assertlen(sms)==1
sm=sms[0]
# At a different time, there is None.
assertlen(Submodule.list_items(rwrepo,self.k_no_subm_tag))==0
assertsm.path=="git/ext/gitdb"
assertsm.path!=sm.name# In our case, we have ids there, which don't equal the path.
assertsm.url.endswith("github.com/gitpython-developers/gitdb.git")
assertsm.branch_path=="refs/heads/master"# the default ...
assertsm.branch_name=="master"
assertsm.parent_commit==rwrepo.head.commit
# Size is always 0.
assertsm.size==0
# The module is not checked-out yet.
self.assertRaises(InvalidGitRepositoryError,sm.module)
# ...which is why we can't get the branch either - it points into the module()
# repository.
self.assertRaises(InvalidGitRepositoryError,getattr,sm,"branch")
# branch_path works, as it's just a string.
assertisinstance(sm.branch_path,str)
# Some commits earlier we still have a submodule, but it's at a different
# commit.
smold=next(Submodule.iter_items(rwrepo,self.k_subm_changed))
assertsmold.binsha!=sm.binsha
assertsmold!=sm# the name changed
# Force it to reread its information.
delsmold._url
smold.url==sm.url# noqa: B015 # FIXME: Should this be an assertion?
# Test config_reader/writer methods.
sm.config_reader()
new_smclone_path=None# Keep custom paths for later.
new_csmclone_path=None#
ifrwrepo.bare:
withself.assertRaises(InvalidGitRepositoryError):
withsm.config_writer()ascw:
pass
else:
withsm.config_writer()aswriter:
# For faster checkout, set the url to the local path.
new_smclone_path=Git.polish_url(osp.join(self.rorepo.working_tree_dir,sm.path))
writer.set_value("url",new_smclone_path)
writer.release()
assertsm.config_reader().get_value("url")==new_smclone_path
assertsm.url==new_smclone_path
# END handle bare repo
smold.config_reader()
# Cannot get a writer on historical submodules.
ifnotrwrepo.bare:
withself.assertRaises(ValueError):
withsmold.config_writer():
pass
# END handle bare repo
# Make the old into a new - this doesn't work as the name changed.
self.assertRaises(ValueError,smold.set_parent_commit,self.k_subm_current)
# the sha is properly updated
smold.set_parent_commit(self.k_subm_changed+"~1")
assertsmold.binsha!=sm.binsha
# Raises if the sm didn't exist in new parent - it keeps its parent_commit
# unchanged.
self.assertRaises(ValueError,smold.set_parent_commit,self.k_no_subm_tag)
# TODO: Test that, if a path is in the .gitmodules file, but not in the index,
# then it raises.
# TEST UPDATE
##############
# Module retrieval is not always possible.
ifrwrepo.bare:
self.assertRaises(InvalidGitRepositoryError,sm.module)
self.assertRaises(InvalidGitRepositoryError,sm.remove)
self.assertRaises(InvalidGitRepositoryError,sm.add,rwrepo,"here","there")
else:
# It's not checked out in our case.
self.assertRaises(InvalidGitRepositoryError,sm.module)
assertnotsm.module_exists()
# Currently there is only one submodule.
assertlen(list(rwrepo.iter_submodules()))==1
assertsm.binsha!="\0"*20
# TEST ADD
###########
# Preliminary tests.
# Adding existing returns exactly the existing.
sma=Submodule.add(rwrepo,sm.name,sm.path)
assertsma.path==sm.path
# Adding existing as pathlike
sma=Submodule.add(rwrepo,sm.name,PathLikeMock(sm.path))
assertsma.path==sm.path
# No url and no module at path fails.
self.assertRaises(ValueError,Submodule.add,rwrepo,"newsubm","pathtorepo",url=None)
# CONTINUE UPDATE
#################
# Let's update it - it's a recursive one too.
newdir=osp.join(sm.abspath,"dir")
os.makedirs(newdir)
# Update fails if the path already exists non-empty.
self.assertRaises(OSError,sm.update)
os.rmdir(newdir)
# Dry-run does nothing.
sm.update(dry_run=True,progress=prog)
assertnotsm.module_exists()
assertsm.update()issm
sm_repopath=sm.path# Cache for later.
assertsm.module_exists()
assertisinstance(sm.module(),git.Repo)
assertsm.module().working_tree_dir==sm.abspath
# INTERLEAVE ADD TEST
#####################
# url must match the one in the existing repository (if submodule name
# suggests a new one) or we raise.
self.assertRaises(
ValueError,
Submodule.add,
rwrepo,
"newsubm",
sm.path,
"git://someurl/repo.git",
)
# CONTINUE UPDATE
#################
# We should have setup a tracking branch, which is also active.
assertsm.module().head.ref.tracking_branch()isnotNone
# Delete the whole directory and re-initialize.
assertlen(sm.children())!=0
# shutil.rmtree(sm.abspath)
sm.remove(force=True,configuration=False)
assertlen(sm.children())==0
# Dry-run does nothing.
sm.update(dry_run=True,recursive=False,progress=prog)
assertlen(sm.children())==0
sm.update(recursive=False)
assertlen(list(rwrepo.iter_submodules()))==2
assertlen(sm.children())==1# It's not checked out yet.
csm=sm.children()[0]
assertnotcsm.module_exists()
csm_repopath=csm.path
# Adjust the path of the submodules module to point to the local
# destination.
new_csmclone_path=Git.polish_url(osp.join(self.rorepo.working_tree_dir,sm.path,csm.path))
withcsm.config_writer()aswriter:
writer.set_value("url",new_csmclone_path)
assertcsm.url==new_csmclone_path
# Dry-run does nothing.
assertnotcsm.module_exists()
sm.update(recursive=True,dry_run=True,progress=prog)
assertnotcsm.module_exists()
# Update recursively again.
sm.update(recursive=True)
assertcsm.module_exists()
# Tracking branch once again.
assertcsm.module().head.ref.tracking_branch()isnotNone
# This flushed in a sub-submodule.
assertlen(list(rwrepo.iter_submodules()))==2
# Reset both heads to the previous version, verify that to_latest_revision
# works.
smods= (sm.module(),csm.module())
forrepoinsmods:
repo.head.reset("HEAD~2",working_tree=1)
# END for each repo to reset
# Dry-run does nothing.
self.assertRaises(
RepositoryDirtyError,
sm.update,
recursive=True,
dry_run=True,
progress=prog,
)
sm.update(recursive=True,dry_run=True,progress=prog,force=True)
forrepoinsmods:
assertrepo.head.commit!=repo.head.ref.tracking_branch().commit
# END for each repo to check
self.assertRaises(RepositoryDirtyError,sm.update,recursive=True,to_latest_revision=True)
sm.update(recursive=True,to_latest_revision=True,force=True)
forrepoinsmods:
assertrepo.head.commit==repo.head.ref.tracking_branch().commit
# END for each repo to check
delsmods
# If the head is detached, it still works (but warns).
smref=sm.module().head.ref
sm.module().head.ref="HEAD~1"
# If there is no tracking branch, we get a warning as well.
csm_tracking_branch=csm.module().head.ref.tracking_branch()
csm.module().head.ref.set_tracking_branch(None)
sm.update(recursive=True,to_latest_revision=True)
# to_latest_revision changes the child submodule's commit, it needs an
# update now.
csm.set_parent_commit(csm.repo.head.commit)
# Undo the changes.
sm.module().head.ref=smref
csm.module().head.ref.set_tracking_branch(csm_tracking_branch)
# REMOVAL OF REPOSITORY
#######################
# Must delete something.
self.assertRaises(ValueError,csm.remove,module=False,configuration=False)
# module() is supposed to point to gitdb, which has a child-submodule whose
# URL is still pointing to GitHub. To save time, we will change it to:
csm.set_parent_commit(csm.repo.head.commit)
withcsm.config_writer()ascw:
cw.set_value("url",self._small_repo_url())
csm.repo.index.commit("adjusted URL to point to local source, instead of the internet")
# We have modified the configuration, hence the index is dirty, and the
# deletion will fail.
# NOTE: As we did a few updates in the meanwhile, the indices were reset.
# Hence we create some changes.
csm.set_parent_commit(csm.repo.head.commit)
withsm.config_writer()aswriter:
writer.set_value("somekey","somevalue")
withcsm.config_writer()aswriter:
writer.set_value("okey","ovalue")
self.assertRaises(InvalidGitRepositoryError,sm.remove)
# If we remove the dirty index, it would work.
sm.module().index.reset()
# Still, we have the file modified.
self.assertRaises(InvalidGitRepositoryError,sm.remove,dry_run=True)
sm.module().index.reset(working_tree=True)
# Enforce the submodule to be checked out at the right spot as well.
csm.update()
assertcsm.module_exists()
assertcsm.exists()
assertosp.isdir(csm.module().working_tree_dir)
# This would work.
assertsm.remove(force=True,dry_run=True)issm
assertsm.module_exists()
sm.remove(force=True,dry_run=True)
assertsm.module_exists()
# But... we have untracked files in the child submodule.
fn=join_path_native(csm.module().working_tree_dir,"newfile")
withopen(fn,"w")asfd:
fd.write("hi")
self.assertRaises(InvalidGitRepositoryError,sm.remove)
# Forcibly delete the child repository.
prev_count=len(sm.children())
self.assertRaises(ValueError,csm.remove,force=True)
# We removed sm, which removed all submodules. However, the instance we
# have still points to the commit prior to that, where it still existed.
csm.set_parent_commit(csm.repo.commit(),check=False)
assertnotcsm.exists()
assertnotcsm.module_exists()
assertlen(sm.children())==prev_count
# Now we have a changed index, as configuration was altered.
# Fix this.
sm.module().index.reset(working_tree=True)
# Now delete only the module of the main submodule.
assertsm.module_exists()
sm.remove(configuration=False,force=True)
assertsm.exists()
assertnotsm.module_exists()
assertsm.config_reader().get_value("url")
# Delete the rest.
sm_path=sm.path
sm.remove()
assertnotsm.exists()
assertnotsm.module_exists()
self.assertRaises(ValueError,getattr,sm,"path")
assertlen(rwrepo.submodules)==0
# ADD NEW SUBMODULE
###################
# Add a simple remote repo - trailing slashes are no problem.
smid="newsub"
osmid="othersub"
nsm=Submodule.add(
rwrepo,
smid,
sm_repopath,
new_smclone_path+"/",
None,
no_checkout=True,
)
assertnsm.name==smid
assertnsm.module_exists()
assertnsm.exists()
# It's not checked out.
assertnotosp.isfile(join_path_native(nsm.module().working_tree_dir,Submodule.k_modules_file))
assertlen(rwrepo.submodules)==1
# Add another submodule, but into the root, not as submodule.
osm=Submodule.add(rwrepo,osmid,csm_repopath,new_csmclone_path,Submodule.k_head_default)
assertosm!=nsm
assertosm.module_exists()
assertosm.exists()
assertosp.isfile(join_path_native(osm.module().working_tree_dir,"setup.py"))
assertlen(rwrepo.submodules)==2
# Commit the changes, just to finalize the operation.
rwrepo.index.commit("my submod commit")
assertlen(rwrepo.submodules)==2
# Needs update, as the head changed.
# It thinks it's in the history of the repo otherwise.
nsm.set_parent_commit(rwrepo.head.commit)
osm.set_parent_commit(rwrepo.head.commit)
# MOVE MODULE
#############
# Invalid input.
self.assertRaises(ValueError,nsm.move,"doesntmatter",module=False,configuration=False)
# Renaming to the same path does nothing.
assertnsm.move(sm_path)isnsm
# Rename a module.
nmp=join_path_native("new","module","dir")+"/"# New module path.
pmp=nsm.path
assertnsm.move(nmp)isnsm
nmp=nmp[:-1]# Cut last /
nmpl=to_native_path_linux(nmp)
assertnsm.path==nmpl
assertrwrepo.submodules[0].path==nmpl
mpath="newsubmodule"
absmpath=join_path_native(rwrepo.working_tree_dir,mpath)
open(absmpath,"w").write("")
self.assertRaises(ValueError,nsm.move,mpath)
os.remove(absmpath)
# Now it works, as we just move it back.
nsm.move(pmp)
assertnsm.path==pmp
assertrwrepo.submodules[0].path==pmp
# REMOVE 'EM ALL
################
# If a submodule's repo has no remotes, it can't be added without an
# explicit url.
osmod=osm.module()
osm.remove(module=False)
forremoteinosmod.remotes:
remote.remove(osmod,remote.name)
assertnotosm.exists()
self.assertRaises(ValueError,Submodule.add,rwrepo,osmid,csm_repopath,url=None)
# END handle bare mode
# Error if there is no submodule file here.
self.assertRaises(
IOError,
Submodule._config_parser,
rwrepo,
rwrepo.commit(self.k_no_subm_tag),
True,
)
# ACTUALLY skipped by git.util.rmtree (in local onerror function), called via
# git.objects.submodule.base.Submodule.remove at "method(mp)", line 1011.
#
# @skipIf(HIDE_WINDOWS_KNOWN_ERRORS,
# "FIXME: fails with: PermissionError: [WinError 32] The process cannot access the file because"
# "it is being used by another process: "
# "'C:\\Users\\ankostis\\AppData\\Local\\Temp\\tmp95c3z83bnon_bare_test_base_rw\\git\\ext\\gitdb\\gitdb\\ext\\smmap'") # noqa: E501
@with_rw_repo(k_subm_current)
deftest_base_rw(self,rwrepo):
self._do_base_tests(rwrepo)
@with_rw_repo(k_subm_current,bare=True)
deftest_base_bare(self,rwrepo):
self._do_base_tests(rwrepo)
@pytest.mark.xfail(
sys.platform=="cygwin",
reason="Cygwin GitPython can't find submodule SHA",
raises=ValueError,
)
@pytest.mark.xfail(
HIDE_WINDOWS_KNOWN_ERRORS,
reason=(
'"The process cannot access the file because it is being used by another process"'
+" on first call to rm.update"
),
raises=PermissionError,
)
@with_rw_repo(k_subm_current,bare=False)
deftest_root_module(self,rwrepo):
# Can query everything without problems.
rm=RootModule(self.rorepo)
assertrm.module()isself.rorepo
# Try attributes.
rm.binsha
rm.mode
rm.path
assertrm.name==rm.k_root_name
assertrm.parent_commit==self.rorepo.head.commit
rm.url
rm.branch
assertlen(rm.list_items(rm.module()))==1
rm.config_reader()
withrm.config_writer():
pass
# Deep traversal gitdb / async.
rsmsp= [sm.pathforsminrm.traverse()]
assertlen(rsmsp)>=2# gitdb and async [and smmap], async being a child of gitdb.
# Cannot set the parent commit as root module's path didn't exist.
self.assertRaises(ValueError,rm.set_parent_commit,"HEAD")
# TEST UPDATE
#############
# Set up a commit that removes existing, adds new and modifies existing
# submodules.
rm=RootModule(rwrepo)
assertlen(rm.children())==1
# Modify path without modifying the index entry.
# (Which is what the move method would do properly.)
# ==================================================
sm=rm.children()[0]
pp="path/prefix"
fp=join_path_native(pp,sm.path)
prep=sm.path
assertnotsm.module_exists()# It was never updated after rwrepo's clone.
# Ensure we clone from a local source.
withsm.config_writer()aswriter:
writer.set_value("url",Git.polish_url(osp.join(self.rorepo.working_tree_dir,sm.path)))
# Dry-run does nothing.
sm.update(recursive=False,dry_run=True,progress=prog)
assertnotsm.module_exists()
sm.update(recursive=False)
assertsm.module_exists()
withsm.config_writer()aswriter:
# Change path to something with prefix AFTER url change.
writer.set_value("path",fp)
# Update doesn't fail, because list_items ignores the wrong path in such
# situations.
rm.update(recursive=False)
# Move it properly - doesn't work as it its path currently points to an
# indexentry which doesn't exist (move it to some path, it doesn't matter here).
self.assertRaises(InvalidGitRepositoryError,sm.move,pp)
# Reset the path(cache) to where it was, now it works.
sm.path=prep
sm.move(fp,module=False)# Leave it at the old location.
assertnotsm.module_exists()
cpathchange=rwrepo.index.commit("changed sm path")# Finally we can commit.
# Update puts the module into place.
rm.update(recursive=False,progress=prog)
sm.set_parent_commit(cpathchange)
assertsm.module_exists()
# Add submodule.
# ==============
nsmn="newsubmodule"
nsmp="submrepo"
subrepo_url=Git.polish_url(osp.join(self.rorepo.working_tree_dir,rsmsp[0],rsmsp[1]))
nsm=Submodule.add(rwrepo,nsmn,nsmp,url=subrepo_url)
csmadded=rwrepo.index.commit("Added submodule").hexsha# Make sure we don't keep the repo reference.
nsm.set_parent_commit(csmadded)
assertnsm.module_exists()
# In our case, the module should not exist, which happens if we update a parent
# repo and a new submodule comes into life.
nsm.remove(configuration=False,module=True)
assertnotnsm.module_exists()andnsm.exists()
# Dry-run does nothing.
rm.update(recursive=False,dry_run=True,progress=prog)
# Otherwise it will work.
rm.update(recursive=False,progress=prog)
assertnsm.module_exists()
# Remove submodule - the previous one.
# ====================================
sm.set_parent_commit(csmadded)
smp=sm.abspath
assertnotsm.remove(module=False).exists()
assertosp.isdir(smp)# Module still exists.
csmremoved=rwrepo.index.commit("Removed submodule")
# An update will remove the module.
# Not in dry_run.
rm.update(recursive=False,dry_run=True,force_remove=True)
assertosp.isdir(smp)
# When removing submodules, we may get new commits as nested submodules are
# auto-committing changes to allow deletions without force, as the index would
# be dirty otherwise.
# QUESTION: Why does this seem to work in test_git_submodule_compatibility() ?
self.assertRaises(InvalidGitRepositoryError,rm.update,recursive=False,force_remove=False)
rm.update(recursive=False,force_remove=True)
assertnotosp.isdir(smp)
# 'Apply work' to the nested submodule and ensure this is not removed/altered
# during updates. We need to commit first, otherwise submodule.update wouldn't
# have a reason to change the head.
touch(osp.join(nsm.module().working_tree_dir,"new-file"))
# We cannot expect is_dirty to even run as we wouldn't reset a head to the same
# location.
assertnsm.module().head.commit.hexsha==nsm.hexsha
nsm.module().index.add([nsm])
nsm.module().index.commit("added new file")
rm.update(recursive=False,dry_run=True,progress=prog)# Would not change head, and thus doesn't fail.
# Everything we can do from now on will trigger the 'future' check, so no
# is_dirty() check will even run. This would only run if our local branch is in
# the past and we have uncommitted changes.
prev_commit=nsm.module().head.commit
rm.update(recursive=False,dry_run=False,progress=prog)
assertprev_commit==nsm.module().head.commit,"head shouldn't change, as it is in future of remote branch"
# this kills the new file
rm.update(recursive=True,progress=prog,force_reset=True)
assertprev_commit!=nsm.module().head.commit,"head changed, as the remote url and its commit changed"
# Change url...
# =============
# ...to the first repository. This way we have a fast checkout, and a completely
# different repository at the different url.
nsm.set_parent_commit(csmremoved)
nsmurl=Git.polish_url(osp.join(self.rorepo.working_tree_dir,rsmsp[0]))
withnsm.config_writer()aswriter:
writer.set_value("url",nsmurl)
csmpathchange=rwrepo.index.commit("changed url")
nsm.set_parent_commit(csmpathchange)
# Now nsm head is in the future of the tracked remote branch.
prev_commit=nsm.module().head.commit
# dry-run does nothing
rm.update(recursive=False,dry_run=True,progress=prog)
assertnsm.module().remotes.origin.url!=nsmurl
rm.update(recursive=False,progress=prog,force_reset=True)
assertnsm.module().remotes.origin.url==nsmurl
assertprev_commit!=nsm.module().head.commit,"Should now point to gitdb"
assertlen(rwrepo.submodules)==1
assertnotrwrepo.submodules[0].children()[0].module_exists(),"nested submodule should not be checked out"
# Add the submodule's changed commit to the index, which is what the user would
# do. Beforehand, update our instance's binsha with the new one.
nsm.binsha=nsm.module().head.commit.binsha
rwrepo.index.add([nsm])
# Change branch.
# ==============
# We only have one branch, so we switch to a virtual one, and back to the
# current one to trigger the difference.
cur_branch=nsm.branch
nsmm=nsm.module()
prev_commit=nsmm.head.commit
forbranchin ("some_virtual_branch",cur_branch.name):
withnsm.config_writer()aswriter:
writer.set_value(Submodule.k_head_option,git.Head.to_full_path(branch))
csmbranchchange=rwrepo.index.commit("changed branch to %s"%branch)
nsm.set_parent_commit(csmbranchchange)
# END for each branch to change
# Let's remove our tracking branch to simulate some changes.
nsmmh=nsmm.head
assertnsmmh.ref.tracking_branch()isNone# Never set it up until now.
assertnotnsmmh.is_detached
# Dry-run does nothing.
rm.update(recursive=False,dry_run=True,progress=prog)
assertnsmmh.ref.tracking_branch()isNone
# The real thing does.
rm.update(recursive=False,progress=prog)
assertnsmmh.ref.tracking_branch()isnotNone
assertnotnsmmh.is_detached
# Recursive update.
# =================
# Finally we recursively update a module, just to run the code at least once
# remove the module so that it has more work.
assertlen(nsm.children())>=1# Could include smmap.
assertnsm.exists()andnsm.module_exists()andlen(nsm.children())>=1
# Ensure we pull locally only.
nsmc=nsm.children()[0]
withnsmc.config_writer()aswriter:
writer.set_value("url",subrepo_url)
rm.update(recursive=True,progress=prog,dry_run=True)# Just to run the code.
rm.update(recursive=True,progress=prog)
# gitdb: has either 1 or 2 submodules depending on the version.
assertlen(nsm.children())>=1andnsmc.module_exists()
deftest_iter_items_from_nonexistent_hash(self):
it=Submodule.iter_items(self.rorepo,"b4ecbfaa90c8be6ed6d9fb4e57cc824663ae15b4")
withself.assertRaisesRegex(ValueError,r"\bcould not be resolved\b"):
next(it)
deftest_iter_items_from_invalid_hash(self):
"""Check legacy behavaior on BadName (also applies to IOError, i.e. OSError)."""
it=Submodule.iter_items(self.rorepo,"xyz")
withself.assertRaises(StopIteration)asctx:
next(it)
self.assertIsNone(ctx.exception.value)
@with_rw_repo(k_no_subm_tag,bare=False)
deftest_first_submodule(self,rwrepo):
assertlen(list(rwrepo.iter_submodules()))==0
forsm_name,sm_pathin (
("first","submodules/first"),
("second",osp.join(rwrepo.working_tree_dir,"submodules/second")),
):
sm=rwrepo.create_submodule(sm_name,sm_path,rwrepo.git_dir,no_checkout=True)
assertsm.exists()andsm.module_exists()
rwrepo.index.commit("Added submodule "+sm_name)
# END for each submodule path to add
self.assertRaises(ValueError,rwrepo.create_submodule,"fail",osp.expanduser("~"))
self.assertRaises(
ValueError,
rwrepo.create_submodule,
"fail-too",
rwrepo.working_tree_dir+osp.sep,
)
@with_rw_directory
deftest_add_empty_repo(self,rwdir):
empty_repo_dir=osp.join(rwdir,"empty-repo")
parent=git.Repo.init(osp.join(rwdir,"parent"))
git.Repo.init(empty_repo_dir)
forcheckout_modeinrange(2):
name="empty"+str(checkout_mode)
self.assertRaises(
ValueError,
parent.create_submodule,
name,
name,
url=empty_repo_dir,
no_checkout=checkout_modeandTrueorFalse,
)
# END for each checkout mode
@with_rw_directory
@_patch_git_config("protocol.file.allow","always")
deftest_update_submodule_with_relative_path(self,rwdir):
repo_path=osp.join(rwdir,"parent")
repo=git.Repo.init(repo_path)
module_repo_path=osp.join(rwdir,"module")
module_repo=git.Repo.init(module_repo_path)
module_repo.git.commit(m="test",allow_empty=True)
repo.git.submodule("add","../module","module")
repo.index.commit("add submodule")
cloned_repo_path=osp.join(rwdir,"cloned_repo")
cloned_repo=git.Repo.clone_from(repo_path,cloned_repo_path)
cloned_repo.submodule_update(init=True,recursive=True)
@with_rw_directory
@_patch_git_config("protocol.file.allow","always")
deftest_list_only_valid_submodules(self,rwdir):
repo_path=osp.join(rwdir,"parent")
repo=git.Repo.init(repo_path)
repo.git.submodule("add",self._small_repo_url(),"module")
repo.index.commit("add submodule")
assertlen(repo.submodules)==1
# Delete the directory from submodule.
submodule_path=osp.join(repo_path,"module")
shutil.rmtree(submodule_path)
repo.git.add([submodule_path])
repo.index.commit("remove submodule")
repo=git.Repo(repo_path)
assertlen(repo.submodules)==0
@pytest.mark.xfail(
HIDE_WINDOWS_KNOWN_ERRORS,
reason=(
'"The process cannot access the file because it is being used by another process"'
+" on first call to sm.move"
),
raises=PermissionError,
)
@with_rw_directory
@_patch_git_config("protocol.file.allow","always")
deftest_git_submodules_and_add_sm_with_new_commit(self,rwdir):
parent=git.Repo.init(osp.join(rwdir,"parent"))
parent.git.submodule("add",self._small_repo_url(),"module")
parent.index.commit("added submodule")
assertlen(parent.submodules)==1
sm=parent.submodules[0]
assertsm.exists()andsm.module_exists()
clone=git.Repo.clone_from(
self._small_repo_url(),
osp.join(parent.working_tree_dir,"existing-subrepository"),
)
sm2=parent.create_submodule("nongit-file-submodule",clone.working_tree_dir)
assertlen(parent.submodules)==2
for_inrange(2):
forinitin (False,True):
sm.update(init=init)
sm2.update(init=init)
# END for each init state
# END for each iteration
sm.move(sm.path+"_moved")
sm2.move(sm2.path+"_moved")
parent.index.commit("moved submodules")
withsm.config_writer()aswriter:
writer.set_value("user.email","example@example.com")
writer.set_value("user.name","me")
smm=sm.module()
fp=osp.join(smm.working_tree_dir,"empty-file")
withopen(fp,"w"):
pass
smm.git.add(Git.polish_url(fp))
smm.git.commit(m="new file added")
# Submodules are retrieved from the current commit's tree, therefore we can't
# really get a new submodule object pointing to the new submodule commit.
sm_too=parent.submodules["module_moved"]
assertparent.head.commit.tree[sm.path].binsha==sm.binsha
assertsm_too.binsha==sm.binsha,"cached submodule should point to the same commit as updated one"
added_bies=parent.index.add([sm])# Added base-index-entries.
assertlen(added_bies)==1
parent.index.commit("add same submodule entry")
commit_sm=parent.head.commit.tree[sm.path]
assertcommit_sm.binsha==added_bies[0].binsha
assertcommit_sm.binsha==sm.binsha
sm_too.binsha=sm_too.module().head.commit.binsha
added_bies=parent.index.add([sm_too])
assertlen(added_bies)==1
parent.index.commit("add new submodule entry")
commit_sm=parent.head.commit.tree[sm.path]
assertcommit_sm.binsha==added_bies[0].binsha
assertcommit_sm.binsha==sm_too.binsha
assertsm_too.binsha!=sm.binsha
@pytest.mark.xfail(
HIDE_WINDOWS_KNOWN_ERRORS,
reason='"The process cannot access the file because it is being used by another process" on call to sm.move',
raises=PermissionError,
)
@with_rw_directory
deftest_git_submodule_compatibility(self,rwdir):
parent=git.Repo.init(osp.join(rwdir,"parent"))
sm_path=join_path_native("submodules","intermediate","one")
sm=parent.create_submodule("mymodules/myname",sm_path,url=self._small_repo_url())
parent.index.commit("added submodule")
defassert_exists(sm,value=True):
assertsm.exists()==value
assertsm.module_exists()==value
# END assert_exists
# As git is backwards compatible itself, it would still recognize what we do
# here... unless we really muss it up. That's the only reason why the test is
# still here...
assertlen(parent.git.submodule().splitlines())==1
module_repo_path=osp.join(sm.module().working_tree_dir,".git")
assertmodule_repo_path.startswith(osp.join(parent.working_tree_dir,sm_path))
ifnotsm._need_gitfile_submodules(parent.git):
assertosp.isdir(module_repo_path)
assertnotsm.module().has_separate_working_tree()
else:
assertosp.isfile(module_repo_path)
assertsm.module().has_separate_working_tree()
assertfind_submodule_git_dir(module_repo_path)isnotNone,"module pointed to by .git file must be valid"
# END verify submodule 'style'
# Test move.
new_sm_path=join_path_native("submodules","one")
sm.move(new_sm_path)
assert_exists(sm)
# Add additional submodule level.
csm=sm.module().create_submodule(
"nested-submodule",
join_path_native("nested-submodule","working-tree"),
url=self._small_repo_url(),
)
sm.module().index.commit("added nested submodule")
sm_head_commit=sm.module().commit()
assert_exists(csm)
# Fails because there are new commits, compared to the remote we cloned from.
self.assertRaises(InvalidGitRepositoryError,sm.remove,dry_run=True)
assert_exists(sm)
assertsm.module().commit()==sm_head_commit
assert_exists(csm)
# Rename nested submodule.
# This name would move itself one level deeper - needs special handling
# internally.
new_name=csm.name+"/mine"
assertcsm.rename(new_name).name==new_name
assert_exists(csm)
assertcsm.repo.is_dirty(index=True,working_tree=False),"index must contain changed .gitmodules file"
csm.repo.index.commit("renamed module")
# keep_going evaluation.
rsm=parent.submodule_update()
assert_exists(sm)
assert_exists(csm)
withcsm.config_writer().set_value("url","bar"):
pass
csm.repo.index.commit("Have to commit submodule change for algorithm to pick it up")
assertcsm.url=="bar"
self.assertRaises(# noqa: B017
Exception,
rsm.update,
recursive=True,
to_latest_revision=True,
progress=prog,
)
assert_exists(csm)
rsm.update(recursive=True,to_latest_revision=True,progress=prog,keep_going=True)
# remove
sm_module_path=sm.module().git_dir
fordry_runin (True,False):
sm.remove(dry_run=dry_run,force=True)
assert_exists(sm,value=dry_run)
assertosp.isdir(sm_module_path)==dry_run
# END for each dry-run mode
@with_rw_directory
deftest_ignore_non_submodule_file(self,rwdir):
parent=git.Repo.init(rwdir)
smp=osp.join(rwdir,"module")
os.mkdir(smp)
withopen(osp.join(smp,"a"),"w",encoding="utf-8")asf:
f.write("test\n")
withopen(osp.join(rwdir,".gitmodules"),"w",encoding="utf-8")asf:
f.write('[submodule "a"]\n')
f.write(" path = module\n")
f.write(" url = https://github.com/chaconinc/DbConnector\n")
parent.git.add(Git.polish_url(osp.join(smp,"a")))
parent.git.add(Git.polish_url(osp.join(rwdir,".gitmodules")))
parent.git.commit(message="test")
assertlen(parent.submodules)==0
@with_rw_directory
deftest_remove_norefs(self,rwdir):
parent=git.Repo.init(osp.join(rwdir,"parent"))
sm_name="mymodules/myname"
sm=parent.create_submodule(sm_name,sm_name,url=self._small_repo_url())
assertsm.exists()
parent.index.commit("Added submodule")
assertsm.repoisparent# yoh was surprised since expected sm repo!!
# So created a new instance for submodule.
smrepo=git.Repo(osp.join(rwdir,"parent",sm.path))
# Adding a remote without fetching so would have no references.
smrepo.create_remote("special","git@server-shouldnotmatter:repo.git")
# And we should be able to remove it just fine.
sm.remove()
assertnotsm.exists()
@with_rw_directory
deftest_rename(self,rwdir):