KiCad PCB EDA Suite
Loading...
Searching...
No Matches
test_libgit_backend.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.TXT for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 3
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26
28
30#include <git/git_backend.h>
31#include <git/libgit_backend.h>
43#include <git/kigit_transport.h>
45
46#include <git2.h>
47
48#include <project.h>
51
52#ifndef __WINDOWS__
53#include <sys/stat.h>
54#include <unistd.h>
55#endif
56
57#include <fstream>
58#include <future>
59#include <set>
60#include <thread>
61
62#include <wx/ffile.h>
63#include <wx/file.h>
64#include <wx/filename.h>
65#include <wx/filesys.h>
66#include <wx/textfile.h>
67
68
69static const char* TEST_AUTHOR_NAME = "Test Author";
71
72
79{
81 {
82 m_repoPath = TempPath() + wxFileName::GetPathSeparator() + wxT( "repo" );
83 m_remotePath = TempPath() + wxFileName::GetPathSeparator() + wxT( "remote.git" );
85 }
86
87
88 bool ready() const { return m_ready; }
89 const wxString& repoPath() const { return m_repoPath; }
90 const wxString& tempBase() const { return TempPath(); }
91 const wxString& remotePath() const { return m_remotePath; }
92
93
96 {
97 git_repository* repo = nullptr;
98 git_repository_open( &repo, m_repoPath.ToUTF8().data() );
99 return repo;
100 }
101
102
104 git_oid createCommit( git_repository* aRepo, const wxString& aFile, const wxString& aContent,
105 const wxString& aMessage )
106 {
107 KI_TEST::WriteGitFile( m_repoPath, aFile, aContent.utf8_string() );
108 return KI_TEST::CommitGitFile( aRepo, aFile, aMessage );
109 }
110
111
113 git_oid createDetachedCommit( git_repository* aRepo, const git_oid& aParentOid, const wxString& aFile,
114 const std::string& aContent, const char* aMessage )
115 {
116 git_oid result = {};
117
118 git_commit* parentCommit = nullptr;
119 BOOST_REQUIRE_EQUAL( git_commit_lookup( &parentCommit, aRepo, &aParentOid ), GIT_OK );
120
121 git_oid blobOid;
122 BOOST_REQUIRE_EQUAL( git_blob_create_from_buffer( &blobOid, aRepo, aContent.data(), aContent.size() ), GIT_OK );
123
124 git_tree* parentTree = nullptr;
125 BOOST_REQUIRE_EQUAL( git_commit_tree( &parentTree, parentCommit ), GIT_OK );
126
127 git_treebuilder* builder = nullptr;
128 BOOST_REQUIRE_EQUAL( git_treebuilder_new( &builder, aRepo, parentTree ), GIT_OK );
130 git_treebuilder_insert( nullptr, builder, aFile.ToUTF8().data(), &blobOid, GIT_FILEMODE_BLOB ),
131 GIT_OK );
132
133 git_oid treeOid;
134 BOOST_REQUIRE_EQUAL( git_treebuilder_write( &treeOid, builder ), GIT_OK );
135 git_treebuilder_free( builder );
136 git_tree_free( parentTree );
137
138 git_tree* tree = nullptr;
139 BOOST_REQUIRE_EQUAL( git_tree_lookup( &tree, aRepo, &treeOid ), GIT_OK );
140
141 git_signature* sig = nullptr;
142 BOOST_REQUIRE_EQUAL( git_signature_now( &sig, TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL ), GIT_OK );
143
144 const git_commit* parents[1] = { parentCommit };
146 git_commit_create( &result, aRepo, nullptr, sig, sig, nullptr, aMessage, tree, 1, parents ), GIT_OK );
147
148 git_signature_free( sig );
149 git_tree_free( tree );
150 git_commit_free( parentCommit );
151 return result;
152 }
153
155 void writeFetchHead( const git_oid& aOid )
156 {
157 char hex[GIT_OID_HEXSZ + 1] = { 0 };
158 git_oid_tostr( hex, sizeof( hex ), &aOid );
159
160 wxString fetchHead = repoPath() + wxFileName::GetPathSeparator() + wxT( ".git" )
161 + wxFileName::GetPathSeparator() + wxT( "FETCH_HEAD" );
162 std::ofstream f( fetchHead.ToStdString() );
163 f << hex << "\t\tbranch 'master' of test\n";
164 }
165
168 {
169 git_remote* remote = nullptr;
170 int rc = git_remote_create( &remote, aRepo, "origin", m_remotePath.ToUTF8().data() );
171
172 if( remote )
173 git_remote_free( remote );
174
175 return rc == 0;
176 }
177
178
181 bool clearUpstreamConfig( git_repository* aRepo, const wxString& aBranch )
182 {
183 git_config* cfg = nullptr;
184
185 if( git_repository_config( &cfg, aRepo ) != 0 )
186 return false;
187
188 wxString remoteKey = wxString::Format( "branch.%s.remote", aBranch );
189 wxString mergeKey = wxString::Format( "branch.%s.merge", aBranch );
190
191 git_config_delete_entry( cfg, remoteKey.ToUTF8().data() );
192 git_config_delete_entry( cfg, mergeKey.ToUTF8().data() );
193
194 git_config_free( cfg );
195 return true;
196 }
197
198
200 bool setUpstreamConfig( git_repository* aRepo, const wxString& aBranch )
201 {
202 git_config* cfg = nullptr;
203
204 if( git_repository_config( &cfg, aRepo ) != 0 )
205 return false;
206
207 wxString remoteKey = wxString::Format( "branch.%s.remote", aBranch );
208 wxString mergeKey = wxString::Format( "branch.%s.merge", aBranch );
209 wxString mergeVal = wxString::Format( "refs/heads/%s", aBranch );
210
211 git_config_set_string( cfg, remoteKey.ToUTF8().data(), "origin" );
212 git_config_set_string( cfg, mergeKey.ToUTF8().data(), mergeVal.ToUTF8().data() );
213 git_config_free( cfg );
214 return true;
215 }
216
217
219 wxString readConfig( git_repository* aRepo, const wxString& aKey )
220 {
221 git_config* cfg = nullptr;
222
223 if( git_repository_config( &cfg, aRepo ) != 0 )
224 return wxEmptyString;
225
226 git_buf buf = { nullptr, 0, 0 };
227 wxString result;
228
229 if( git_config_get_string_buf( &buf, cfg, aKey.ToUTF8().data() ) == 0 && buf.ptr )
230 result = wxString::FromUTF8( buf.ptr );
231
232 git_buf_dispose( &buf );
233 git_config_free( cfg );
234 return result;
235 }
236
237
239 {
240 KI_TEST::WriteGitFile( tempBase(), wxS( "global-ignore" ), "" );
241 const wxString path = tempBase() + wxS( "/global-ignore" );
242 git_config* rawConfig = nullptr;
243 BOOST_REQUIRE_EQUAL( git_repository_config( &rawConfig, aRepo ), GIT_OK );
244 KIGIT::GitConfigPtr config( rawConfig );
245 BOOST_REQUIRE_EQUAL( git_config_set_string( config.get(), "core.excludesfile", path.utf8_str() ), GIT_OK );
246 }
247
248
249private:
251 {
254
255 git_config* cfg = nullptr;
256 BOOST_REQUIRE_EQUAL( git_repository_config( &cfg, repo.get() ), GIT_OK );
258 BOOST_REQUIRE_EQUAL( git_config_set_bool( cfg, "pull.rebase", 0 ), GIT_OK );
259
260 createCommit( repo.get(), wxT( "file.txt" ), wxT( "initial\n" ), wxT( "Initial commit" ) );
261 return true;
262 }
263
264
266 {
267 git_clone_options opts;
268 git_clone_init_options( &opts, GIT_CLONE_OPTIONS_VERSION );
269 opts.bare = 1;
270
271 git_repository* bare = nullptr;
272 int rc = git_clone( &bare, m_repoPath.ToUTF8().data(), m_remotePath.ToUTF8().data(), &opts );
273
274 if( bare )
275 git_repository_free( bare );
276
277 return rc == 0;
278 }
279
280
281 wxString m_repoPath;
282 wxString m_remotePath;
284};
285
286
287BOOST_FIXTURE_TEST_SUITE( LibgitBackend, GIT_BACKEND_FIXTURE )
288
289
290// The single scope predicate behind every checklist, so a file elsewhere in the repository
291// cannot leak into a project commit (issue #15910).
292// Getting changes keeps whichever FETCH_HEAD entry libgit2 marked to merge, without reading
293// its name. That is only sound while at most one entry is ever marked, so the assumption is
294// checked here rather than left for a reader to take on trust.
295BOOST_AUTO_TEST_CASE( FetchHeadMarksAtMostOneBranchToMerge )
296{
297 BOOST_TEST_REQUIRE( ready() );
298
299 git_repository* repo = openRepo();
300 BOOST_TEST_REQUIRE( repo );
301 KIGIT::GitRepositoryPtr repoPtr( repo );
302 BOOST_REQUIRE( addOrigin( repo ) );
303
304 // Two more branches on the remote, named either side of the current one alphabetically.
305 {
306 git_repository* bare = nullptr;
307 BOOST_REQUIRE_EQUAL( git_repository_open( &bare, remotePath().ToUTF8().data() ), GIT_OK );
308 KIGIT::GitRepositoryPtr barePtr( bare );
309
310 git_oid head;
311 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &head, bare, "HEAD" ), GIT_OK );
312
313 for( const char* name : { "refs/heads/aaa", "refs/heads/zzz" } )
314 {
315 git_reference* ref = nullptr;
316 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, bare, name, &head, 1, nullptr ), GIT_OK );
317 git_reference_free( ref );
318 }
319 }
320
321 struct MARKED
322 {
323 int total = 0;
324 std::vector<std::string> names;
325 };
326
327 auto collect = []( git_repository* aRepo )
328 {
329 MARKED marked;
330
331 auto cb = []( const char* aName, const char*, const git_oid*, unsigned int aIsMerge, void* aPayload ) -> int
332 {
333 MARKED* m = static_cast<MARKED*>( aPayload );
334 m->total++;
335
336 if( aIsMerge )
337 m->names.push_back( std::string( aName ? aName : "" ) );
338
339 return 0;
340 };
341
342 BOOST_REQUIRE_EQUAL( git_repository_fetchhead_foreach( aRepo, cb, &marked ), GIT_OK );
343 return marked;
344 };
345
346 KIGIT_COMMON common( repo );
347
348 // Add Version Control wires up origin without per-branch tracking. Nothing is marked, so the
349 // by-name fallback below the callback is what chooses the branch.
350 {
351 BOOST_REQUIRE( clearUpstreamConfig( repo, wxT( "master" ) ) );
352
353 GIT_PULL_HANDLER handler( &common );
354 BOOST_REQUIRE_MESSAGE( handler.PerformFetch(), handler.GetErrorString() );
355
356 MARKED marked = collect( repo );
357 BOOST_CHECK_EQUAL( marked.total, 3 );
358 BOOST_CHECK_EQUAL( marked.names.size(), 0u );
359 }
360
361 // With tracking configured exactly one is marked, and it is the branch being tracked, so
362 // keeping the last one keeps the right one.
363 {
364 BOOST_REQUIRE( setUpstreamConfig( repo, wxT( "master" ) ) );
365
366 GIT_PULL_HANDLER handler( &common );
367 BOOST_REQUIRE_MESSAGE( handler.PerformFetch(), handler.GetErrorString() );
368
369 MARKED marked = collect( repo );
370 BOOST_CHECK_EQUAL( marked.total, 3 );
371 BOOST_REQUIRE_EQUAL( marked.names.size(), 1u );
372 BOOST_CHECK_EQUAL( marked.names[0], "refs/heads/master" );
373 }
374}
375
376
377// KiCad cannot read or write Git LFS, so an operation that would put a pointer file where a
378// design file belongs is refused. The remote can start using LFS at any time, so the commit
379// being merged has to be judged, not the one already held.
380BOOST_AUTO_TEST_CASE( PerformPull_RefusesACommitThatBringsGitLfs )
381{
382 BOOST_TEST_REQUIRE( ready() );
383
384 git_repository* repo = openRepo();
385 BOOST_TEST_REQUIRE( repo );
386 KIGIT::GitRepositoryPtr repoPtr( repo );
387 BOOST_REQUIRE( addOrigin( repo ) );
388 BOOST_REQUIRE( setUpstreamConfig( repo, wxT( "master" ) ) );
389
390 // The remote starts keeping design files in LFS, and moves master on to that commit.
391 {
392 git_repository* bare = nullptr;
393 BOOST_REQUIRE_EQUAL( git_repository_open( &bare, remotePath().ToUTF8().data() ), GIT_OK );
394 KIGIT::GitRepositoryPtr barePtr( bare );
395
396 git_oid base;
397 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &base, bare, "refs/heads/master" ), GIT_OK );
398
399 git_oid attrs = createDetachedCommit( bare, base, wxT( ".gitattributes" ), "*.kicad_pcb filter=lfs -text\n",
400 "Track boards with LFS" );
401
402 git_oid board =
403 createDetachedCommit( bare, attrs, wxT( "board.kicad_pcb" ),
404 "version https://git-lfs.github.com/spec/v1\n"
405 "oid sha256:0000000000000000000000000000000000000000000000000000000000000000\n"
406 "size 1\n",
407 "Add the board" );
408
409 git_reference* ref = nullptr;
410 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, bare, "refs/heads/master", &board, 1, nullptr ), GIT_OK );
411 git_reference_free( ref );
412 }
413
414 KIGIT_COMMON common( repo, repoPath() );
415 GIT_PULL_HANDLER handler( &common );
416
417 PullResult result = handler.PerformPull();
418
419 BOOST_CHECK_MESSAGE( result != PullResult::Success && result != PullResult::FastForward,
420 "the pull should refuse a commit that brings Git LFS in" );
421 const wxString error = handler.GetErrorString();
422
423 BOOST_CHECK_MESSAGE( error.Upper().Contains( wxS( "LFS" ) ),
424 "the refusal should name Git LFS, got: " + error.ToStdString() );
425
426 // Above all, the pointer text must not have been written where the board belongs.
427 BOOST_CHECK( !wxFileName::FileExists( repoPath() + wxFileName::GetPathSeparator() + wxT( "board.kicad_pcb" ) ) );
428}
429
430
431// Cancel has to reach a push that is already writing objects, as it does a fetch that is
432// already receiving them. libgit2 abandons the transfer when the progress callback refuses.
433BOOST_AUTO_TEST_CASE( PushProgressStopsWhenTheOperationIsCancelled )
434{
435 BOOST_TEST_REQUIRE( ready() );
436
437 git_repository* repo = openRepo();
438 BOOST_TEST_REQUIRE( repo );
439 KIGIT::GitRepositoryPtr repoPtr( repo );
440
441 BOOST_REQUIRE( addOrigin( repo ) );
442
443 git_oid local = createCommit( repo, wxT( "pushed.txt" ), wxT( "new\n" ), wxT( "Push me" ) );
444 wxString refspec = wxString::FromUTF8( git_oid_tostr_s( &local ) ) + wxS( ":refs/heads/master" );
445
446 git_remote* remote = nullptr;
447 BOOST_REQUIRE_EQUAL( git_remote_lookup( &remote, repo, "origin" ), GIT_OK );
448 KIGIT::GitRemotePtr remotePtr( remote );
449
450 KIGIT_COMMON common( repo );
451 GIT_PUSH_HANDLER handler( &common );
452 KIGIT::REMOTE_TRANSPORT transport( &handler, remote );
453
454 // Cancelled once connected, so only a transfer tick is left to notice
455 BOOST_CHECK_MESSAGE( transport.Push(
456 [&]()
457 {
458 handler.CancelThisOperation();
459 return refspec;
460 } )
461 != GIT_OK,
462 "a cancelled push should stop at its next progress tick" );
463
464 git_repository* bare = nullptr;
465 BOOST_REQUIRE_EQUAL( git_repository_open( &bare, remotePath().ToUTF8().data() ), GIT_OK );
466 KIGIT::GitRepositoryPtr barePtr( bare );
467
468 git_oid remoteHead;
469 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &remoteHead, bare, "refs/heads/master" ), GIT_OK );
470 BOOST_CHECK( !git_oid_equal( &remoteHead, &local ) );
471}
472
473
474BOOST_AUTO_TEST_CASE( IsWithinProjectPath_ScopesToProjectDirectory )
475{
476 const wxString project = wxT( "/repo/proj/" );
477
478 // Files inside the project directory are in scope.
479 BOOST_CHECK( KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "/repo/proj/proj.kicad_sch" ), project ) );
480 BOOST_CHECK( KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "/repo/proj/sub/board.kicad_pcb" ), project ) );
481
482 // Files elsewhere in the repository are not.
483 BOOST_CHECK( !KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "/repo/outside.txt" ), project ) );
484 BOOST_CHECK( !KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "/repo/other/f.txt" ), project ) );
485
486 // A sibling whose name merely shares the project's prefix must not match.
487 BOOST_CHECK( !KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "/repo/proj-extra/f.txt" ), project ) );
488
489 // The predicate normalizes a missing trailing separator before comparing, so the
490 // prefix collision above is still rejected when the caller omits the separator.
491 BOOST_CHECK( KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "/repo/proj/f.txt" ), wxT( "/repo/proj" ) ) );
492 BOOST_CHECK( !KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "/repo/proj-extra/f.txt" ),
493 wxT( "/repo/proj" ) ) );
494
495#ifdef __WINDOWS__
496 BOOST_CHECK( KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "C:\\repo\\proj/file.kicad_sch" ),
497 wxT( "C:\\repo\\proj\\" ) ) );
498 BOOST_CHECK( !KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "C:\\repo\\proj-extra/file.kicad_sch" ),
499 wxT( "C:\\repo\\proj\\" ) ) );
500#endif
501
502 // An empty project path matches nothing rather than the whole repository.
503 BOOST_CHECK( !KIGIT::PROJECT_GIT_UTILS::IsWithinProjectPath( wxT( "/repo/proj/f.txt" ), wxEmptyString ) );
504}
505
506
507// A message-only amend leaves HEAD and upstream at different OIDs with identical trees. Without
508// the content-aware filter every file touched since the merge-base showed a clock icon.
509BOOST_AUTO_TEST_CASE( GetDifferentFiles_SameTreeAmendHidesAheadFiles )
510{
511 BOOST_TEST_REQUIRE( ready() );
512
513 git_repository* repo = openRepo();
514 BOOST_TEST_REQUIRE( repo );
515
516 // Add a second commit so the merge-base in GetDifferentFiles isn't the root.
517 git_oid c1 = createCommit( repo, wxT( "file.txt" ), wxT( "edited\n" ), wxT( "Edit file" ) );
518
519 // Simulate "pushed": create the remote-tracking ref pointing at C1.
520 git_reference* trackingRef = nullptr;
521 git_reference_create( &trackingRef, repo, "refs/remotes/origin/master", &c1, 1, nullptr );
522
523 if( trackingRef )
524 git_reference_free( trackingRef );
525
526 addOrigin( repo );
527 setUpstreamConfig( repo, wxT( "master" ) );
528
529 // Amend C1 message-only. Same tree, different commit OID.
530 git_reference* headRef = nullptr;
531 git_repository_head( &headRef, repo );
532
533 git_commit* headCommit = nullptr;
534 git_reference_peel( (git_object**) &headCommit, headRef, GIT_OBJECT_COMMIT );
535
536 git_tree* tree = nullptr;
537 git_commit_tree( &tree, headCommit );
538
539 git_signature* sig = nullptr;
540 git_signature_now( &sig, TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
541
542 git_oid amendedOid;
543 int rc = git_commit_amend( &amendedOid, headCommit, "HEAD", sig, sig, nullptr, "Edit file (message-only amend)",
544 tree );
545 BOOST_TEST_REQUIRE( rc == 0 );
546
547 git_tree_free( tree );
548 git_commit_free( headCommit );
549 git_reference_free( headRef );
550 git_signature_free( sig );
551
552 // Now: HEAD points at C1', upstream still at C1, both have the same tree.
553 // Pre-filter: AHEAD = { file.txt } (touched in C1 relative to root).
554 // Post-filter (the fix under test): AHEAD = {} because HEAD's blob == upstream's blob.
555 KIGIT_COMMON common( repo );
556 auto [ahead, behind] = common.GetDifferentFiles();
557
558 BOOST_CHECK_MESSAGE( ahead.empty(), "Message-only amend should not report any AHEAD files; got "
559 + std::to_string( ahead.size() ) );
560 BOOST_CHECK_MESSAGE( behind.empty(), "Message-only amend should not report any BEHIND files; got "
561 + std::to_string( behind.size() ) );
562
563 git_repository_free( repo );
564}
565
566
567// Positive control for the content-aware filter, which must not over-filter.
568BOOST_AUTO_TEST_CASE( GetDifferentFiles_DifferentTreeAmendKeepsAheadFile )
569{
570 BOOST_TEST_REQUIRE( ready() );
571
572 git_repository* repo = openRepo();
573 BOOST_TEST_REQUIRE( repo );
574
575 git_oid c1 = createCommit( repo, wxT( "file.txt" ), wxT( "edited\n" ), wxT( "Edit file" ) );
576
577 git_reference* trackingRef = nullptr;
578 git_reference_create( &trackingRef, repo, "refs/remotes/origin/master", &c1, 1, nullptr );
579
580 if( trackingRef )
581 git_reference_free( trackingRef );
582
583 addOrigin( repo );
584 setUpstreamConfig( repo, wxT( "master" ) );
585
586 // Make a new commit on top with different content (replacing C1 effectively).
587 // Use the same path so the file remains "the same file" to the diff.
588 createCommit( repo, wxT( "file.txt" ), wxT( "edited again\n" ), wxT( "Re-edit file" ) );
589
590 KIGIT_COMMON common( repo );
591 auto [ahead, behind] = common.GetDifferentFiles();
592
593 BOOST_CHECK_MESSAGE( ahead.count( wxT( "file.txt" ) ) == 1,
594 "AHEAD should contain file.txt when content differs from upstream" );
595
596 git_repository_free( repo );
597}
598
599
600// origin without per-branch tracking leaves FETCH_HEAD unmarked, which used to fail (#24332).
601BOOST_AUTO_TEST_CASE( PerformPull_NoUpstreamConfig_FallbackSucceedsAndWritesUpstream )
602{
603 BOOST_TEST_REQUIRE( ready() );
604
605 git_repository* repo = openRepo();
606 BOOST_TEST_REQUIRE( repo );
607
608 addOrigin( repo );
609 clearUpstreamConfig( repo, wxT( "master" ) );
610
611 KIGIT_COMMON common( repo );
612 GIT_PULL_HANDLER handler( &common );
613
614 PullResult result = handler.PerformPull();
615
616 // Without the fallback, this would be PullResult::Error with "Could not lookup commit".
617 BOOST_CHECK_MESSAGE( result == PullResult::UpToDate || result == PullResult::Success
619 "Pull without upstream config should succeed via fallback; got "
620 + std::to_string( static_cast<int>( result ) ) + ", err='"
621 + handler.GetErrorString().ToStdString() + "'" );
622
623 // The fallback also wires up tracking so subsequent pulls take the normal path.
624 BOOST_CHECK_EQUAL( readConfig( repo, wxT( "branch.master.remote" ) ), wxString( "origin" ) );
625 BOOST_CHECK_EQUAL( readConfig( repo, wxT( "branch.master.merge" ) ), wxString( "refs/heads/master" ) );
626
627 git_repository_free( repo );
628}
629
630
635BOOST_AUTO_TEST_CASE( PerformPull_RebaseConfigReplaysLocalCommit )
636{
637 BOOST_TEST_REQUIRE( ready() );
638
639 git_repository* repo = openRepo();
640 BOOST_TEST_REQUIRE( repo );
641
642 addOrigin( repo );
643 setUpstreamConfig( repo, wxT( "master" ) );
644
645 git_object* initial = nullptr;
646 BOOST_TEST_REQUIRE( git_revparse_single( &initial, repo, "HEAD" ) == 0 );
647
648 KIGIT_COMMON common( repo );
649 git_oid remoteOid = createCommit( repo, wxT( "remote.txt" ), wxT( "remote\n" ), wxT( "Remote commit" ) );
650
651 {
652 GIT_PUSH_HANDLER pushHandler( &common );
653 BOOST_TEST_REQUIRE( static_cast<int>( pushHandler.PerformPush() ) == static_cast<int>( PushResult::Success ) );
654 }
655
656 BOOST_TEST_REQUIRE( git_reset( repo, initial, GIT_RESET_HARD, nullptr ) == 0 );
657 git_object_free( initial );
658
659 createCommit( repo, wxT( "local.txt" ), wxT( "local\n" ), wxT( "Local commit" ) );
660
661 git_config* cfg = nullptr;
662 BOOST_TEST_REQUIRE( git_repository_config( &cfg, repo ) == 0 );
663 git_config_set_bool( cfg, "pull.rebase", 1 );
664 git_config_free( cfg );
665
666 GIT_PULL_HANDLER handler( &common );
667 PullResult result = handler.PerformPull();
668
669 BOOST_CHECK_MESSAGE( result == PullResult::Success,
670 "Rebase pull failed: " + handler.GetErrorString().ToStdString() );
671 BOOST_CHECK_EQUAL( git_repository_state( repo ), static_cast<int>( GIT_REPOSITORY_STATE_NONE ) );
672
673 git_commit* head = nullptr;
674 BOOST_TEST_REQUIRE( git_revparse_single( (git_object**) &head, repo, "HEAD" ) == 0 );
675 BOOST_CHECK( git_oid_equal( git_commit_parent_id( head, 0 ), &remoteOid ) );
676 git_commit_free( head );
677
678 git_repository_free( repo );
679}
680
681
682// Tracking config is what lets later operations take the FETCH_HEAD path.
683BOOST_AUTO_TEST_CASE( Push_FirstPushSetsUpstreamTracking )
684{
685 BOOST_TEST_REQUIRE( ready() );
686
687 git_repository* repo = openRepo();
688 BOOST_TEST_REQUIRE( repo );
689
690 // Add a new local commit so there is something to actually push beyond the
691 // initial state shared with the bare remote.
692 createCommit( repo, wxT( "file.txt" ), wxT( "second\n" ), wxT( "Second commit" ) );
693
694 addOrigin( repo );
695 clearUpstreamConfig( repo, wxT( "master" ) );
696
697 KIGIT_COMMON common( repo );
698 GIT_PUSH_HANDLER handler( &common );
699
700 PushResult result = handler.PerformPush();
701 BOOST_TEST_REQUIRE( static_cast<int>( result ) == static_cast<int>( PushResult::Success ) );
702
703 BOOST_CHECK_EQUAL( readConfig( repo, wxT( "branch.master.remote" ) ), wxString( "origin" ) );
704 BOOST_CHECK_EQUAL( readConfig( repo, wxT( "branch.master.merge" ) ), wxString( "refs/heads/master" ) );
705
706 git_repository_free( repo );
707}
708
709
710// A detached HEAD is not a branch, so its name is the literal "HEAD" and there is no branch on
711// the remote for it to go to.
712BOOST_AUTO_TEST_CASE( Push_RefusesOnADetachedHead )
713{
714 BOOST_TEST_REQUIRE( ready() );
715
716 git_repository* repo = openRepo();
717 BOOST_TEST_REQUIRE( repo );
718
719 createCommit( repo, wxT( "file.txt" ), wxT( "second\n" ), wxT( "Second commit" ) );
720 addOrigin( repo );
721
722 git_oid headOid;
723 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
724 BOOST_REQUIRE_EQUAL( git_repository_set_head_detached( repo, &headOid ), GIT_OK );
725
726 KIGIT_COMMON common( repo );
727 GIT_PUSH_HANDLER handler( &common );
728
729 BOOST_CHECK_EQUAL( static_cast<int>( handler.PerformPush() ), static_cast<int>( PushResult::Error ) );
730 const wxString error = handler.GetErrorString();
731
732 BOOST_CHECK_MESSAGE( error.Contains( wxS( "branch" ) ),
733 "the refusal should say the project is not on a branch, got: " + error.ToStdString() );
734
735 git_repository_free( repo );
736}
737
738
739// Behind the upstream. libgit2 reports it through the return code, not the message.
740BOOST_AUTO_TEST_CASE( Push_ReportsNonFastForwardWhenRemoteIsAhead )
741{
742 BOOST_TEST_REQUIRE( ready() );
743
744 git_repository* repo = openRepo();
745 BOOST_TEST_REQUIRE( repo );
746
747 {
748 git_repository* remote = nullptr;
749 BOOST_REQUIRE_EQUAL( git_repository_open( &remote, remotePath().ToUTF8().data() ), GIT_OK );
750
751 git_oid remoteHead;
752 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &remoteHead, remote, "refs/heads/master" ), GIT_OK );
753
754 git_oid ahead = createDetachedCommit( remote, remoteHead, wxT( "theirs.txt" ), "theirs\n", "Remote commit" );
755
756 git_reference* ref = nullptr;
757 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, remote, "refs/heads/master", &ahead, 1, nullptr ), GIT_OK );
758 git_reference_free( ref );
759 git_repository_free( remote );
760 }
761
762 createCommit( repo, wxT( "file.txt" ), wxT( "second\n" ), wxT( "Local commit" ) );
763 addOrigin( repo );
764
765 KIGIT_COMMON common( repo );
766 GIT_PUSH_HANDLER handler( &common );
767
768 PushResult result = handler.PerformPush();
769
770 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PushResult::NonFastForward ) );
771
772 git_repository_free( repo );
773}
774
775
776// A refusal the client-side check let through arrives only on the per-reference callback. A
777// read-only refs directory provokes one, which directory permissions cannot do on Windows.
778#ifndef __WINDOWS__
779BOOST_AUTO_TEST_CASE( Push_ReportsErrorWhenRemoteRefusesTheUpdate )
780{
781 BOOST_TEST_REQUIRE( ready() );
782
783 git_repository* repo = openRepo();
784 BOOST_TEST_REQUIRE( repo );
785
786 createCommit( repo, wxT( "file.txt" ), wxT( "second\n" ), wxT( "Local commit" ) );
787 addOrigin( repo );
788
789 wxString headsDir = remotePath() + wxFileName::GetPathSeparator() + wxT( "refs" ) + wxFileName::GetPathSeparator()
790 + wxT( "heads" );
791
792 BOOST_REQUIRE( wxFileName::DirExists( headsDir ) );
793
794 // Directory permissions do not bind root, so there the refusal cannot be staged.
795 if( geteuid() == 0 )
796 return;
797
798 // Put the permissions back however the test ends, or the fixture cannot remove its directory.
799 struct WRITABLE_AGAIN
800 {
801 wxString dir;
802 ~WRITABLE_AGAIN() { chmod( dir.fn_str(), 0755 ); }
803 } restore{ headsDir };
804
805 chmod( headsDir.fn_str(), 0555 );
806
807 KIGIT_COMMON common( repo );
808 GIT_PUSH_HANDLER handler( &common );
809
810 PushResult result = handler.PerformPush();
811
812 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PushResult::Error ) );
813
814 // A reason that went missing reads back as the words "No error".
815 const std::vector<wxString>& errors = handler.GetErrorStrings();
816
817 BOOST_REQUIRE_EQUAL( errors.size(), 1u );
818 BOOST_CHECK_MESSAGE( !errors.front().EndsWith( wxS( "No error" ) ),
819 "the refusal lost git's reason: " + errors.front().ToStdString() );
820
821 git_repository_free( repo );
822}
823#endif
824
825
826// Left mid-rebase, every later commit is refused until it is finished from the command line.
827BOOST_AUTO_TEST_CASE( PerformPull_RebaseConflictLeavesRepositoryAsItWas )
828{
829 BOOST_TEST_REQUIRE( ready() );
830
831 git_repository* repo = openRepo();
832 BOOST_TEST_REQUIRE( repo );
833
834 {
835 git_repository* remote = nullptr;
836 BOOST_REQUIRE_EQUAL( git_repository_open( &remote, remotePath().ToUTF8().data() ), GIT_OK );
837
838 git_oid remoteHead;
839 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &remoteHead, remote, "refs/heads/master" ), GIT_OK );
840
841 git_oid ahead = createDetachedCommit( remote, remoteHead, wxT( "file.txt" ), "remote\n", "Remote change" );
842
843 git_reference* ref = nullptr;
844 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, remote, "refs/heads/master", &ahead, 1, nullptr ), GIT_OK );
845 git_reference_free( ref );
846 git_repository_free( remote );
847 }
848
849 git_oid localHead = createCommit( repo, wxT( "file.txt" ), wxT( "local\n" ), wxT( "Local change" ) );
850
851 addOrigin( repo );
852 setUpstreamConfig( repo, wxT( "master" ) );
853
854 {
855 git_config* cfg = nullptr;
856 BOOST_REQUIRE_EQUAL( git_repository_config( &cfg, repo ), GIT_OK );
857 git_config_set_bool( cfg, "pull.rebase", 1 );
858 git_config_free( cfg );
859 }
860
861 KIGIT_COMMON common( repo );
862 GIT_PULL_HANDLER handler( &common );
863
864 PullResult result = handler.PerformPull();
865
866 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PullResult::Conflict ) );
867 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_NONE );
868
869 git_oid headNow;
870 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headNow, repo, "HEAD" ), GIT_OK );
871 BOOST_CHECK( git_oid_equal( &headNow, &localHead ) );
872
873 wxTextFile file( repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" ) );
874 BOOST_REQUIRE( file.Open() );
875 BOOST_CHECK_EQUAL( file.GetFirstLine(), wxString( "local" ) );
876
877 git_repository_free( repo );
878}
879
880
881// The fast-forward must follow branch.<name>.merge, not a remote branch of the same name.
882BOOST_AUTO_TEST_CASE( PerformPull_FastForwardFollowsConfiguredUpstreamBranch )
883{
884 BOOST_TEST_REQUIRE( ready() );
885
886 git_repository* repo = openRepo();
887 BOOST_TEST_REQUIRE( repo );
888
889 git_oid ahead;
890
891 {
892 git_repository* remote = nullptr;
893 BOOST_REQUIRE_EQUAL( git_repository_open( &remote, remotePath().ToUTF8().data() ), GIT_OK );
894
895 // The remote's branch is called main, while the local one stays master.
896 git_reference* masterRef = nullptr;
897 BOOST_REQUIRE_EQUAL( git_reference_lookup( &masterRef, remote, "refs/heads/master" ), GIT_OK );
898
899 git_reference* mainRef = nullptr;
900 BOOST_REQUIRE_EQUAL( git_reference_rename( &mainRef, masterRef, "refs/heads/main", 0, nullptr ), GIT_OK );
901 git_reference_free( masterRef );
902 BOOST_REQUIRE_EQUAL( git_repository_set_head( remote, "refs/heads/main" ), GIT_OK );
903
904 git_oid remoteHead = *git_reference_target( mainRef );
905 git_reference_free( mainRef );
906
907 ahead = createDetachedCommit( remote, remoteHead, wxT( "theirs.txt" ), "theirs\n", "Remote commit" );
908
909 git_reference* ref = nullptr;
910 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, remote, "refs/heads/main", &ahead, 1, nullptr ), GIT_OK );
911 git_reference_free( ref );
912 git_repository_free( remote );
913 }
914
915 addOrigin( repo );
916
917 {
918 git_config* cfg = nullptr;
919 BOOST_REQUIRE_EQUAL( git_repository_config( &cfg, repo ), GIT_OK );
920 git_config_set_string( cfg, "branch.master.remote", "origin" );
921 git_config_set_string( cfg, "branch.master.merge", "refs/heads/main" );
922 git_config_free( cfg );
923 }
924
925 KIGIT_COMMON common( repo );
926 GIT_PULL_HANDLER handler( &common );
927
928 PullResult result = handler.PerformPull();
929
930 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PullResult::FastForward ) );
931
932 git_oid headNow;
933 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headNow, repo, "HEAD" ), GIT_OK );
934 BOOST_CHECK( git_oid_equal( &headNow, &ahead ) );
935
936 git_repository_free( repo );
937}
938
939
940// Files are written before the branch moves, so a branch that cannot move must not leave the
941// tree holding a commit HEAD does not point at.
942BOOST_AUTO_TEST_CASE( PerformPull_FastForwardRollsBackWhenBranchCannotMove )
943{
944 BOOST_TEST_REQUIRE( ready() );
945
946 git_repository* repo = openRepo();
947 BOOST_TEST_REQUIRE( repo );
948
949 git_oid before;
950 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &before, repo, "HEAD" ), GIT_OK );
951
952 wxString trackedPath = repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" );
953 wxString contentBefore;
954 {
955 wxFFile f( trackedPath, wxT( "rb" ) );
956 f.ReadAll( &contentBefore );
957 }
958
959 git_oid ahead;
960 {
961 git_repository* remote = nullptr;
962 BOOST_REQUIRE_EQUAL( git_repository_open( &remote, remotePath().ToUTF8().data() ), GIT_OK );
963
964 git_oid remoteHead;
965 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &remoteHead, remote, "refs/heads/master" ), GIT_OK );
966
967 ahead = createDetachedCommit( remote, remoteHead, wxT( "file.txt" ), "changed by remote\n", "Remote edit" );
968
969 git_reference* ref = nullptr;
970 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, remote, "refs/heads/master", &ahead, 1, nullptr ), GIT_OK );
971 git_reference_free( ref );
972 git_repository_free( remote );
973 }
974
975 addOrigin( repo );
976
977 // Sits outside the paths the pull touches. Rolling back must leave it exactly as it is.
978 wxString bystanderPath = repoPath() + wxFileName::GetPathSeparator() + wxT( "bystander.txt" );
979 {
980 wxFFile bystander( bystanderPath, wxT( "wb" ) );
981 BOOST_TEST_REQUIRE( bystander.IsOpened() );
982 bystander.Write( wxT( "written by something else\n" ) );
983 }
984
985 // A real reference lock, so the update fails after the checkout, with no production seam.
986 wxString refLock = repoPath() + wxFileName::GetPathSeparator() + wxT( ".git" ) + wxFileName::GetPathSeparator()
987 + wxT( "refs" ) + wxFileName::GetPathSeparator() + wxT( "heads" )
988 + wxFileName::GetPathSeparator() + wxT( "master.lock" );
989 {
990 wxFFile lock( refLock, wxT( "wb" ) );
991 BOOST_TEST_REQUIRE( lock.IsOpened() );
992 lock.Write( wxT( "locked\n" ) );
993 }
994
995 KIGIT_COMMON common( repo );
996 GIT_PULL_HANDLER handler( &common );
997
998 PullResult result = handler.PerformPull();
999
1000 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PullResult::Error ) );
1001
1002 wxRemoveFile( refLock );
1003 git_repository_free( repo );
1004
1005 // Reopen so nothing is answered from a cached index or reference.
1006 git_repository* fresh = nullptr;
1007 BOOST_REQUIRE_EQUAL( git_repository_open( &fresh, repoPath().ToUTF8().data() ), GIT_OK );
1008
1009 git_oid headAfter;
1010 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headAfter, fresh, "HEAD" ), GIT_OK );
1011 BOOST_CHECK_MESSAGE( git_oid_equal( &headAfter, &before ), "HEAD must not have moved" );
1012
1013 wxString contentAfter;
1014 {
1015 wxFFile f( trackedPath, wxT( "rb" ) );
1016 f.ReadAll( &contentAfter );
1017 }
1018
1019 BOOST_CHECK_MESSAGE( contentAfter == contentBefore, "the working file must be back at the commit HEAD points at" );
1020
1021 // A tree left at the incoming commit would show up here as an uncommitted change.
1022 git_status_options opts;
1023 git_status_init_options( &opts, GIT_STATUS_OPTIONS_VERSION );
1024 opts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
1025
1026 git_status_list* list = nullptr;
1027 BOOST_REQUIRE_EQUAL( git_status_list_new( &list, fresh, &opts ), GIT_OK );
1028 size_t dirty = git_status_list_entrycount( list );
1029 git_status_list_free( list );
1030
1031 BOOST_CHECK_MESSAGE( dirty == 0, "the rollback must leave no phantom local changes" );
1032
1033 // Only the paths the pull wrote. Widening it would delete files it never touched.
1034 BOOST_CHECK_MESSAGE( wxFileName::FileExists( bystanderPath ),
1035 "the rollback must not remove a file outside the paths the pull wrote" );
1036
1037 git_repository_free( fresh );
1038}
1039
1040
1041// An untracked directory where the incoming commit wants a file blocks the checkout, and the
1042// rollback must not take the directory with it.
1043BOOST_AUTO_TEST_CASE( PerformPull_RollbackKeepsAnUntrackedDirectoryItCannotIdentify )
1044{
1045 BOOST_TEST_REQUIRE( ready() );
1046
1047 git_repository* repo = openRepo();
1048 BOOST_TEST_REQUIRE( repo );
1049
1050 // The remote adds a file called "notes".
1051 {
1052 git_repository* remote = nullptr;
1053 BOOST_REQUIRE_EQUAL( git_repository_open( &remote, remotePath().ToUTF8().data() ), GIT_OK );
1054
1055 git_oid remoteHead;
1056 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &remoteHead, remote, "refs/heads/master" ), GIT_OK );
1057
1058 git_oid ahead = createDetachedCommit( remote, remoteHead, wxT( "notes" ), "from the remote\n", "Add notes" );
1059
1060 git_reference* ref = nullptr;
1061 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, remote, "refs/heads/master", &ahead, 1, nullptr ), GIT_OK );
1062 git_reference_free( ref );
1063 git_repository_free( remote );
1064 }
1065
1066 addOrigin( repo );
1067
1068 // An untracked directory does not make the tree dirty, and the collision check names the
1069 // file inside it, so the pull reaches the checkout.
1070 wxString notesDir = repoPath() + wxFileName::GetPathSeparator() + wxT( "notes" );
1071 BOOST_REQUIRE( wxFileName::Mkdir( notesDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) );
1072
1073 wxString keptFile = notesDir + wxFileName::GetPathSeparator() + wxT( "keep.txt" );
1074 {
1075 wxFFile f( keptFile, wxT( "wb" ) );
1076 BOOST_TEST_REQUIRE( f.IsOpened() );
1077 f.Write( wxT( "the only copy\n" ) );
1078 }
1079
1080 KIGIT_COMMON common( repo );
1081 GIT_PULL_HANDLER handler( &common );
1082
1083 PullResult result = handler.PerformPull();
1084
1085 // Every failure code is negative, and a checkout over a directory can only fail.
1086 BOOST_CHECK_MESSAGE( static_cast<int>( result ) < 0, "the checkout cannot succeed over a directory" );
1087
1088 git_repository_free( repo );
1089
1090 BOOST_CHECK_MESSAGE( wxFileName::DirExists( notesDir ),
1091 "the rollback must not remove an untracked directory it did not write" );
1092 BOOST_REQUIRE_MESSAGE( wxFileName::FileExists( keptFile ), "the file inside it must survive" );
1093
1094 wxString after;
1095 {
1096 wxFFile f( keptFile, wxT( "rb" ) );
1097 f.ReadAll( &after );
1098 }
1099
1100 BOOST_CHECK_EQUAL( after.ToStdString(), std::string( "the only copy\n" ) );
1101}
1102
1103
1104BOOST_AUTO_TEST_CASE( PerformPull_AdoptRemoteHistoryLeavesUnbornBranchOnFailedCheckout )
1105{
1106 BOOST_TEST_REQUIRE( ready() );
1107
1108 wxString emptyDir = tempBase() + wxFileName::GetPathSeparator() + wxT( "unborn_rollback" );
1109 wxFileName::Mkdir( emptyDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
1110
1111 git_repository* fresh = nullptr;
1112 BOOST_REQUIRE_EQUAL( git_repository_init( &fresh, emptyDir.ToUTF8().data(), 0 ), GIT_OK );
1113
1114 {
1115 git_remote* remote = nullptr;
1116 BOOST_REQUIRE_EQUAL( git_remote_create( &remote, fresh, "origin", remotePath().ToUTF8().data() ), GIT_OK );
1117 git_remote_free( remote );
1118 }
1119
1120 // The checkout refuses, which this path must survive without leaving a branch behind.
1121 wxString collide = emptyDir + wxFileName::GetPathSeparator() + wxT( "file.txt" );
1122 {
1123 wxFFile f( collide, wxT( "wb" ) );
1124 f.Write( wxT( "mine\n" ) );
1125 }
1126
1127 KIGIT_COMMON common( fresh );
1128 GIT_PULL_HANDLER handler( &common );
1129
1130 PullResult result = handler.PerformPull();
1131
1132 BOOST_CHECK_MESSAGE( result != PullResult::Success && result != PullResult::FastForward,
1133 "a colliding untracked file must not be overwritten" );
1134
1135 git_repository_free( fresh );
1136
1137 git_repository* reopened = nullptr;
1138 BOOST_REQUIRE_EQUAL( git_repository_open( &reopened, emptyDir.ToUTF8().data() ), GIT_OK );
1139
1140 BOOST_CHECK_MESSAGE( git_repository_head_unborn( reopened ) == 1,
1141 "the branch must still be unborn after a refused checkout" );
1142
1143 wxString kept;
1144 {
1145 wxFFile f( collide, wxT( "rb" ) );
1146 f.ReadAll( &kept );
1147 }
1148
1149 BOOST_CHECK_EQUAL( kept.ToStdString(), std::string( "mine\n" ) );
1150
1151 git_repository_free( reopened );
1152
1153 if( wxFileName::DirExists( emptyDir ) )
1154 wxFileName::Rmdir( emptyDir, wxPATH_RMDIR_RECURSIVE );
1155}
1156
1157
1158BOOST_AUTO_TEST_CASE( PerformPull_ExplainsWhenActionLockHeld )
1159{
1160 BOOST_TEST_REQUIRE( ready() );
1161
1162 git_repository* repo = openRepo();
1163 BOOST_TEST_REQUIRE( repo );
1164
1165 addOrigin( repo );
1166
1167 KIGIT_COMMON common( repo );
1168 GIT_PULL_HANDLER handler( &common );
1169
1170 std::unique_lock<std::mutex> held = common.LockAction();
1171
1172 PullResult result = std::async( std::launch::async,
1173 [&handler]()
1174 {
1175 return handler.PerformPull();
1176 } )
1177 .get();
1178
1179 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PullResult::Error ) );
1180 BOOST_CHECK( !handler.GetErrorStrings().empty() );
1181
1182 held.unlock();
1183 git_repository_free( repo );
1184}
1185
1186
1187// The user has to be told which file, since the checklist may not even show it.
1188BOOST_AUTO_TEST_CASE( PerformPull_NamesUntrackedFileBlockingFastForward )
1189{
1190 BOOST_TEST_REQUIRE( ready() );
1191
1192 git_repository* repo = openRepo();
1193 BOOST_TEST_REQUIRE( repo );
1194
1195 {
1196 git_repository* remote = nullptr;
1197 BOOST_REQUIRE_EQUAL( git_repository_open( &remote, remotePath().ToUTF8().data() ), GIT_OK );
1198
1199 git_oid remoteHead;
1200 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &remoteHead, remote, "refs/heads/master" ), GIT_OK );
1201
1202 git_oid ahead = createDetachedCommit( remote, remoteHead, wxT( "theirs.txt" ), "theirs\n", "Remote adds" );
1203
1204 git_reference* ref = nullptr;
1205 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, remote, "refs/heads/master", &ahead, 1, nullptr ), GIT_OK );
1206 git_reference_free( ref );
1207 git_repository_free( remote );
1208 }
1209
1210 wxString collidingPath = repoPath() + wxFileName::GetPathSeparator() + wxT( "theirs.txt" );
1211 {
1212 std::ofstream f( collidingPath.ToStdString() );
1213 f << "mine, never committed\n";
1214 }
1215
1216 addOrigin( repo );
1217 setUpstreamConfig( repo, wxT( "master" ) );
1218
1219 git_oid headBefore;
1220 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headBefore, repo, "HEAD" ), GIT_OK );
1221
1222 KIGIT_COMMON common( repo );
1223 GIT_PULL_HANDLER handler( &common );
1224
1225 PullResult result = handler.PerformPull();
1226
1227 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PullResult::DirtyWorkdir ) );
1228 BOOST_CHECK( handler.GetErrorString().Contains( wxT( "theirs.txt" ) ) );
1229
1230 git_oid headAfter;
1231 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headAfter, repo, "HEAD" ), GIT_OK );
1232 BOOST_CHECK( git_oid_equal( &headBefore, &headAfter ) );
1233
1234 wxTextFile file( collidingPath );
1235 BOOST_REQUIRE( file.Open() );
1236 BOOST_CHECK_EQUAL( file.GetFirstLine(), wxString( "mine, never committed" ) );
1237
1238 git_repository_free( repo );
1239}
1240
1241
1242// The same collision when the branches have diverged, which takes the merge path.
1243BOOST_AUTO_TEST_CASE( PerformPull_NamesUntrackedFileBlockingMerge )
1244{
1245 BOOST_TEST_REQUIRE( ready() );
1246
1247 git_repository* repo = openRepo();
1248 BOOST_TEST_REQUIRE( repo );
1249
1250 {
1251 git_repository* remote = nullptr;
1252 BOOST_REQUIRE_EQUAL( git_repository_open( &remote, remotePath().ToUTF8().data() ), GIT_OK );
1253
1254 git_oid remoteHead;
1255 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &remoteHead, remote, "refs/heads/master" ), GIT_OK );
1256
1257 git_oid ahead = createDetachedCommit( remote, remoteHead, wxT( "theirs.txt" ), "theirs\n", "Remote adds" );
1258
1259 git_reference* ref = nullptr;
1260 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, remote, "refs/heads/master", &ahead, 1, nullptr ), GIT_OK );
1261 git_reference_free( ref );
1262 git_repository_free( remote );
1263 }
1264
1265 git_oid localHead = createCommit( repo, wxT( "other.txt" ), wxT( "local\n" ), wxT( "Local change" ) );
1266
1267 wxString collidingPath = repoPath() + wxFileName::GetPathSeparator() + wxT( "theirs.txt" );
1268 {
1269 std::ofstream f( collidingPath.ToStdString() );
1270 f << "mine, never committed\n";
1271 }
1272
1273 addOrigin( repo );
1274 setUpstreamConfig( repo, wxT( "master" ) );
1275
1276 KIGIT_COMMON common( repo );
1277 GIT_PULL_HANDLER handler( &common );
1278
1279 PullResult result = handler.PerformPull();
1280
1281 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PullResult::DirtyWorkdir ) );
1282 BOOST_CHECK( handler.GetErrorString().Contains( wxT( "theirs.txt" ) ) );
1283 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_NONE );
1284
1285 git_oid headAfter;
1286 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headAfter, repo, "HEAD" ), GIT_OK );
1287 BOOST_CHECK( git_oid_equal( &localHead, &headAfter ) );
1288
1289 git_repository_free( repo );
1290}
1291
1292
1293// With no commit of its own to merge from, getting changes adopts the remote history.
1294BOOST_AUTO_TEST_CASE( PerformPull_UnbornBranchAdoptsRemoteHistory )
1295{
1296 BOOST_TEST_REQUIRE( ready() );
1297
1298 wxString freshPath = tempBase() + wxFileName::GetPathSeparator() + wxT( "fresh" );
1299
1300 git_repository* repo = nullptr;
1301 git_repository_init_options initOpts;
1302 git_repository_init_options_init( &initOpts, GIT_REPOSITORY_INIT_OPTIONS_VERSION );
1303 initOpts.flags = GIT_REPOSITORY_INIT_MKPATH;
1304 initOpts.initial_head = "master";
1305 BOOST_REQUIRE_EQUAL( git_repository_init_ext( &repo, freshPath.ToUTF8().data(), &initOpts ), GIT_OK );
1306 BOOST_REQUIRE_EQUAL( git_repository_head_unborn( repo ), 1 );
1307
1308 addOrigin( repo );
1309
1310 KIGIT_COMMON common( repo );
1311 GIT_PULL_HANDLER handler( &common );
1312
1313 PullResult result = handler.PerformPull();
1314
1315 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PullResult::FastForward ) );
1316 BOOST_CHECK_EQUAL( git_repository_head_unborn( repo ), 0 );
1317 BOOST_CHECK_EQUAL( git_repository_head_detached( repo ), 0 );
1318 BOOST_CHECK( wxFileName::FileExists( freshPath + wxFileName::GetPathSeparator() + wxT( "file.txt" ) ) );
1319
1320 git_repository_free( repo );
1321}
1322
1323
1324BOOST_AUTO_TEST_CASE( AbandonOperation_ClearsInterruptedMerge )
1325{
1326 BOOST_TEST_REQUIRE( ready() );
1327
1328 git_repository* repo = openRepo();
1329 BOOST_TEST_REQUIRE( repo );
1330
1331 git_oid base;
1332 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &base, repo, "HEAD" ), GIT_OK );
1333
1334 git_oid side = createDetachedCommit( repo, base, wxT( "file.txt" ), "side\n", "Side change" );
1335 git_oid localHead = createCommit( repo, wxT( "file.txt" ), wxT( "local\n" ), wxT( "Local change" ) );
1336
1337 {
1338 git_annotated_commit* sideCommit = nullptr;
1339 BOOST_REQUIRE_EQUAL( git_annotated_commit_lookup( &sideCommit, repo, &side ), GIT_OK );
1340
1341 const git_annotated_commit* heads[1] = { sideCommit };
1342 git_checkout_options checkoutOpts = GIT_CHECKOUT_OPTIONS_INIT;
1343 checkoutOpts.checkout_strategy = GIT_CHECKOUT_SAFE | GIT_CHECKOUT_ALLOW_CONFLICTS;
1344
1345 BOOST_REQUIRE_EQUAL( git_merge( repo, heads, 1, nullptr, &checkoutOpts ), GIT_OK );
1346 git_annotated_commit_free( sideCommit );
1347 }
1348
1349 BOOST_REQUIRE_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_MERGE );
1350
1351 KIGIT_COMMON common( repo );
1352 wxString error;
1353
1354 // The panel names the operation it offers to abandon, so the session has to tell which it is.
1357 BOOST_CHECK( common.AbandonOperation( error ) );
1360 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_NONE );
1361
1362 git_index* index = nullptr;
1363 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
1364 BOOST_CHECK( !git_index_has_conflicts( index ) );
1365 git_index_free( index );
1366
1367 git_oid headNow;
1368 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headNow, repo, "HEAD" ), GIT_OK );
1369 BOOST_CHECK( git_oid_equal( &headNow, &localHead ) );
1370
1371 wxTextFile file( repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" ) );
1372 BOOST_REQUIRE( file.Open() );
1373 BOOST_CHECK_EQUAL( file.GetFirstLine(), wxString( "local" ) );
1374
1375 git_repository_free( repo );
1376}
1377
1378
1379// An interrupted rebase also leaves HEAD detached. Abandoning it must put the branch back.
1380// A bisect is a search, not a half-finished change. Resetting and clearing its bookkeeping
1381// leaves the project on whichever commit the search had reached, with no way back to where it
1382// started.
1383// Abandoning goes back to the last commit for the files the operation touched. Uncommitted work
1384// in a file it never went near is somebody's own, and a repository can hold several projects.
1385BOOST_AUTO_TEST_CASE( AbandonOperation_KeepsWorkTheOperationDidNotTouch )
1386{
1387 BOOST_TEST_REQUIRE( ready() );
1388
1389 git_repository* repo = openRepo();
1390 BOOST_TEST_REQUIRE( repo );
1391
1392 // A second tracked file, committed before the branch point so neither side changes it.
1393 createCommit( repo, wxT( "bystander.txt" ), wxT( "keep\n" ), wxT( "Add bystander" ) );
1394
1395 git_oid base;
1396 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &base, repo, "HEAD" ), GIT_OK );
1397
1398 git_oid sideEdit = createDetachedCommit( repo, base, wxT( "file.txt" ), "side\n", "Side change" );
1399
1400 // The side also brings a file of its own, which the merge stages as an addition.
1401 git_oid side = createDetachedCommit( repo, sideEdit, wxT( "fromside.txt" ), "new\n", "Side addition" );
1402
1403 createCommit( repo, wxT( "file.txt" ), wxT( "local\n" ), wxT( "Local change" ) );
1404
1405 // The user's own edit, in a file the merge has no business in.
1406 wxString bystanderPath = repoPath() + wxFileName::GetPathSeparator() + wxT( "bystander.txt" );
1407 {
1408 std::ofstream f( bystanderPath.ToStdString() );
1409 f << "my own work\n";
1410 }
1411
1412 {
1413 git_annotated_commit* sideCommit = nullptr;
1414 BOOST_REQUIRE_EQUAL( git_annotated_commit_lookup( &sideCommit, repo, &side ), GIT_OK );
1415
1416 const git_annotated_commit* heads[1] = { sideCommit };
1417 git_checkout_options checkoutOpts = GIT_CHECKOUT_OPTIONS_INIT;
1418 checkoutOpts.checkout_strategy = GIT_CHECKOUT_SAFE | GIT_CHECKOUT_ALLOW_CONFLICTS;
1419
1420 BOOST_REQUIRE_EQUAL( git_merge( repo, heads, 1, nullptr, &checkoutOpts ), GIT_OK );
1421 git_annotated_commit_free( sideCommit );
1422 }
1423
1424 BOOST_REQUIRE_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_MERGE );
1425
1426 KIGIT_COMMON common( repo );
1427 wxString error;
1428
1429 BOOST_REQUIRE_MESSAGE( common.AbandonOperation( error ), error );
1430
1431 // The merge is gone and its file is back.
1432 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_NONE );
1433
1434 git_index* index = nullptr;
1435 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
1436 KIGIT::GitIndexPtr indexPtr( index );
1437 BOOST_CHECK( !git_index_has_conflicts( index ) );
1438
1439 {
1440 std::ifstream f( ( repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" ) ).ToStdString() );
1441 std::string content( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
1442 BOOST_CHECK_EQUAL( content, "local\n" );
1443 }
1444
1445 // The file the merge brought in is gone again, as git's own abort leaves it.
1446 BOOST_CHECK( !wxFileName::FileExists( repoPath() + wxFileName::GetPathSeparator() + wxT( "fromside.txt" ) ) );
1447
1448 // And the edit the merge never touched is still there.
1449 {
1450 std::ifstream f( bystanderPath.ToStdString() );
1451 std::string content( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
1452 BOOST_CHECK_EQUAL( content, "my own work\n" );
1453 }
1454
1455 git_repository_free( repo );
1456}
1457
1458
1459BOOST_AUTO_TEST_CASE( AbandonOperation_RefusesDuringABisect )
1460{
1461 BOOST_TEST_REQUIRE( ready() );
1462
1463 git_repository* repo = openRepo();
1464 BOOST_TEST_REQUIRE( repo );
1465
1466 git_oid head;
1467 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &head, repo, "HEAD" ), GIT_OK );
1468
1469 // What `git bisect start` leaves behind, which is how git itself recognises the state.
1470 wxString gitDir = repoPath() + wxFileName::GetPathSeparator() + wxT( ".git" ) + wxFileName::GetPathSeparator();
1471
1472 {
1473 std::ofstream log( ( gitDir + wxT( "BISECT_LOG" ) ).ToStdString() );
1474 log << "git bisect start\n";
1475 }
1476
1477 {
1478 std::ofstream start( ( gitDir + wxT( "BISECT_START" ) ).ToStdString() );
1479 start << "master\n";
1480 }
1481
1482 BOOST_REQUIRE_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_BISECT );
1483
1484 KIGIT_COMMON common( repo );
1485 wxString error;
1486
1487 BOOST_CHECK_MESSAGE( !common.AbandonOperation( error ), "a bisect must not be abandoned from here" );
1488 BOOST_CHECK( !error.IsEmpty() );
1489 BOOST_CHECK_MESSAGE( wxFileName::FileExists( gitDir + wxT( "BISECT_LOG" ) ),
1490 "the bisect bookkeeping must survive" );
1491
1492 wxRemoveFile( gitDir + wxT( "BISECT_LOG" ) );
1493 wxRemoveFile( gitDir + wxT( "BISECT_START" ) );
1494 git_repository_free( repo );
1495}
1496
1497
1498BOOST_AUTO_TEST_CASE( AbandonOperation_RefusesAnInteractiveRebaseInOurWords )
1499{
1500 BOOST_TEST_REQUIRE( ready() );
1501
1502 git_repository* repo = openRepo();
1503 BOOST_TEST_REQUIRE( repo );
1504
1505 const wxString sep = wxFileName::GetPathSeparator();
1506
1507 // What `git rebase -i` leaves behind. libgit2 cannot open one, so the abort fails.
1508 const wxString rebaseDir = repoPath() + sep + wxT( ".git" ) + sep + wxT( "rebase-merge" );
1509
1510 BOOST_REQUIRE( wxFileName::Mkdir( rebaseDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) );
1511
1512 git_oid head;
1513 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &head, repo, "HEAD" ), GIT_OK );
1514
1515 const std::string headHash = git_oid_tostr_s( &head );
1516
1517 auto writeRebaseFile = [&]( const wxString& aName, const std::string& aText )
1518 {
1519 std::ofstream out( ( rebaseDir + sep + aName ).ToStdString() );
1520 out << aText << "\n";
1521 };
1522
1523 writeRebaseFile( wxT( "interactive" ), "" );
1524 writeRebaseFile( wxT( "head-name" ), "refs/heads/master" );
1525 writeRebaseFile( wxT( "onto" ), headHash );
1526 writeRebaseFile( wxT( "orig-head" ), headHash );
1527
1528 BOOST_REQUIRE_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_REBASE_INTERACTIVE );
1529
1530 KIGIT_COMMON common( repo );
1531 wxString error;
1532
1533 BOOST_CHECK( !common.AbandonOperation( error ) );
1534 BOOST_CHECK_MESSAGE( error.Contains( wxT( "another program" ) ), error );
1535 BOOST_CHECK_MESSAGE( !error.Lower().Contains( wxT( "not supported" ) ), error );
1536
1537 for( const wxString& name : { wxT( "interactive" ), wxT( "head-name" ), wxT( "onto" ), wxT( "orig-head" ) } )
1538 wxRemoveFile( rebaseDir + sep + name );
1539
1540 wxFileName::Rmdir( rebaseDir );
1541 git_repository_free( repo );
1542}
1543
1544
1545BOOST_AUTO_TEST_CASE( AbandonOperation_ClearsInterruptedRebase )
1546{
1547 BOOST_TEST_REQUIRE( ready() );
1548
1549 git_repository* repo = openRepo();
1550 BOOST_TEST_REQUIRE( repo );
1551
1552 git_oid base;
1553 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &base, repo, "HEAD" ), GIT_OK );
1554
1555 git_oid side = createDetachedCommit( repo, base, wxT( "file.txt" ), "side\n", "Side change" );
1556 git_oid localHead = createCommit( repo, wxT( "file.txt" ), wxT( "local\n" ), wxT( "Local change" ) );
1557
1558 {
1559 git_annotated_commit* upstream = nullptr;
1560 BOOST_REQUIRE_EQUAL( git_annotated_commit_lookup( &upstream, repo, &side ), GIT_OK );
1561
1562 git_rebase* rebase = nullptr;
1563 BOOST_REQUIRE_EQUAL( git_rebase_init( &rebase, repo, nullptr, upstream, nullptr, nullptr ), GIT_OK );
1564
1565 git_rebase_operation* op = nullptr;
1566 BOOST_REQUIRE_EQUAL( git_rebase_next( &op, rebase ), GIT_OK );
1567
1568 // Walk away mid-rebase, as a crash would.
1569 git_rebase_free( rebase );
1570 git_annotated_commit_free( upstream );
1571 }
1572
1573 BOOST_REQUIRE_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_REBASE_MERGE );
1574 BOOST_REQUIRE_EQUAL( git_repository_head_detached( repo ), 1 );
1575
1576 KIGIT_COMMON common( repo );
1577 wxString error;
1578
1579 BOOST_CHECK( common.AbandonOperation( error ) );
1580 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_NONE );
1581 BOOST_CHECK_EQUAL( git_repository_head_detached( repo ), 0 );
1582
1583 git_oid headNow;
1584 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headNow, repo, "HEAD" ), GIT_OK );
1585 BOOST_CHECK( git_oid_equal( &headNow, &localHead ) );
1586
1587 wxTextFile file( repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" ) );
1588 BOOST_REQUIRE( file.Open() );
1589 BOOST_CHECK_EQUAL( file.GetFirstLine(), wxString( "local" ) );
1590
1591 git_repository_free( repo );
1592}
1593
1594
1595// A fast-forward over a locally modified file must refuse, not move the branch past a change
1596// it could not apply. Otherwise the local edit reads as reverting the remote change.
1597BOOST_AUTO_TEST_CASE( PerformPull_FastForwardRefusesOverDirtyTrackedFile )
1598{
1599 BOOST_TEST_REQUIRE( ready() );
1600
1601 git_repository* repo = openRepo();
1602 BOOST_TEST_REQUIRE( repo );
1603
1604 {
1605 git_repository* remote = nullptr;
1606 BOOST_REQUIRE_EQUAL( git_repository_open( &remote, remotePath().ToUTF8().data() ), GIT_OK );
1607
1608 git_oid remoteHead;
1609 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &remoteHead, remote, "refs/heads/master" ), GIT_OK );
1610
1611 git_oid ahead = createDetachedCommit( remote, remoteHead, wxT( "file.txt" ), "remote\n", "Remote change" );
1612
1613 git_reference* ref = nullptr;
1614 BOOST_REQUIRE_EQUAL( git_reference_create( &ref, remote, "refs/heads/master", &ahead, 1, nullptr ), GIT_OK );
1615 git_reference_free( ref );
1616 git_repository_free( remote );
1617 }
1618
1619 wxString filePath = repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" );
1620 {
1621 std::ofstream f( filePath.ToStdString() );
1622 f << "local edit\n";
1623 }
1624
1625 addOrigin( repo );
1626 setUpstreamConfig( repo, wxT( "master" ) );
1627
1628 git_oid headBefore;
1629 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headBefore, repo, "HEAD" ), GIT_OK );
1630
1631 KIGIT_COMMON common( repo );
1632 GIT_PULL_HANDLER handler( &common );
1633
1634 PullResult result = handler.PerformPull();
1635
1636 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PullResult::DirtyWorkdir ) );
1637
1638 git_oid headAfter;
1639 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headAfter, repo, "HEAD" ), GIT_OK );
1640 BOOST_CHECK( git_oid_equal( &headBefore, &headAfter ) );
1641
1642 wxTextFile file( filePath );
1643 BOOST_REQUIRE( file.Open() );
1644 BOOST_CHECK_EQUAL( file.GetFirstLine(), wxString( "local edit" ) );
1645
1646 git_repository_free( repo );
1647}
1648
1649
1650// Equivalent to git checkout HEAD with a path, so other changes and untracked files stay.
1651BOOST_AUTO_TEST_CASE( DiscardChangesRestoresOnlyTheGivenPaths )
1652{
1653 BOOST_TEST_REQUIRE( ready() );
1654
1655 git_repository* repo = openRepo();
1656 BOOST_TEST_REQUIRE( repo );
1657
1658 createCommit( repo, wxT( "keep.txt" ), wxT( "keep\n" ), wxT( "Add keep" ) );
1659 createCommit( repo, wxT( "gone.txt" ), wxT( "gone\n" ), wxT( "Add gone" ) );
1660
1661 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
1662
1663 auto writeAll = []( const wxString& aPath, const std::string& aContent )
1664 {
1665 std::ofstream f( aPath.ToStdString(), std::ios::binary );
1666 f << aContent;
1667 };
1668
1669 auto readAll = []( const wxString& aPath )
1670 {
1671 std::ifstream in( aPath.ToStdString(), std::ios::binary );
1672 return std::string( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
1673 };
1674
1675 writeAll( workDir + wxT( "file.txt" ), "accidental\n" );
1676 writeAll( workDir + wxT( "keep.txt" ), "still dirty\n" );
1677 writeAll( workDir + wxT( "new.txt" ), "never committed\n" );
1678 BOOST_TEST_REQUIRE( wxRemoveFile( workDir + wxT( "gone.txt" ) ) );
1679
1680 KIGIT_COMMON common( repo );
1681
1682 BOOST_CHECK( common.IsPathInHead( wxT( "file.txt" ) ) );
1683 BOOST_CHECK( !common.IsPathInHead( wxT( "new.txt" ) ) );
1684
1685 wxString error;
1686 BOOST_REQUIRE_MESSAGE( common.DiscardChanges( { wxT( "file.txt" ), wxT( "gone.txt" ) }, error ), error );
1687
1688 BOOST_CHECK_EQUAL( readAll( workDir + wxT( "file.txt" ) ), "initial\n" );
1689 BOOST_CHECK_EQUAL( readAll( workDir + wxT( "gone.txt" ) ), "gone\n" );
1690 BOOST_CHECK_EQUAL( readAll( workDir + wxT( "keep.txt" ) ), "still dirty\n" );
1691 BOOST_CHECK_EQUAL( readAll( workDir + wxT( "new.txt" ) ), "never committed\n" );
1692
1693 git_repository_free( repo );
1694}
1695
1696
1697// libgit2 reads checkout paths as wildmatch patterns, so a name holding a glob character must
1698// be matched literally or the wrong file is restored.
1699BOOST_AUTO_TEST_CASE( DiscardChangesMatchesPathsLiterally )
1700{
1701 BOOST_TEST_REQUIRE( ready() );
1702
1703 git_repository* repo = openRepo();
1704 BOOST_TEST_REQUIRE( repo );
1705
1706 createCommit( repo, wxT( "board[1].txt" ), wxT( "committed\n" ), wxT( "Add bracketed" ) );
1707 createCommit( repo, wxT( "board1.txt" ), wxT( "other committed\n" ), wxT( "Add plain" ) );
1708
1709 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
1710
1711 auto writeAll = []( const wxString& aPath, const std::string& aContent )
1712 {
1713 std::ofstream f( aPath.ToStdString(), std::ios::binary );
1714 f << aContent;
1715 };
1716
1717 auto readAll = []( const wxString& aPath )
1718 {
1719 std::ifstream in( aPath.ToStdString(), std::ios::binary );
1720 return std::string( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
1721 };
1722
1723 writeAll( workDir + wxT( "board[1].txt" ), "edited\n" );
1724 writeAll( workDir + wxT( "board1.txt" ), "edited too\n" );
1725
1726 KIGIT_COMMON common( repo );
1727
1728 wxString error;
1729 BOOST_REQUIRE_MESSAGE( common.DiscardChanges( { wxT( "board[1].txt" ) }, error ), error );
1730
1731 BOOST_CHECK_EQUAL( readAll( workDir + wxT( "board[1].txt" ) ), "committed\n" );
1732 BOOST_CHECK_EQUAL( readAll( workDir + wxT( "board1.txt" ) ), "edited too\n" );
1733
1734 git_repository_free( repo );
1735}
1736
1737
1738// libgit2 reads a status pathspec as a wildmatch pattern, so a folder name holding a glob
1739// character must be matched literally or the wrong folder is listed.
1740BOOST_AUTO_TEST_CASE( GetFileStatusMatchesPathspecLiterally )
1741{
1742 BOOST_TEST_REQUIRE( ready() );
1743
1744 git_repository* repo = openRepo();
1745 BOOST_TEST_REQUIRE( repo );
1746
1747 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
1748
1749 auto writeAll = []( const wxString& aPath, const std::string& aContent )
1750 {
1751 wxFileName fn( aPath );
1752 fn.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
1753
1754 std::ofstream f( aPath.ToStdString(), std::ios::binary );
1755 f << aContent;
1756 };
1757
1758 writeAll( workDir + wxT( "a[1]/x.txt" ), "one\n" );
1759 writeAll( workDir + wxT( "a1/y.txt" ), "two\n" );
1760
1761 KIGIT_COMMON common( repo );
1762 GIT_STATUS_HANDLER handler( &common );
1763
1764 std::map<wxString, FileStatus> status = handler.GetFileStatus( wxT( "a[1]/" ), true );
1765
1766 bool bracketed = false;
1767 bool plain = false;
1768
1769 for( const auto& [path, fileStatus] : status )
1770 {
1771 bracketed |= path.EndsWith( wxT( "a[1]/x.txt" ) );
1772 plain |= path.EndsWith( wxT( "a1/y.txt" ) );
1773 }
1774
1775 BOOST_CHECK_MESSAGE( bracketed, "the folder named in the pathspec was not listed" );
1776 BOOST_CHECK_MESSAGE( !plain, "a folder the pathspec does not name was listed" );
1777
1778 git_repository_free( repo );
1779}
1780
1781
1782// The panel can only say the remote moved on if the session can tell.
1783BOOST_AUTO_TEST_CASE( UpstreamStatusSeesTheRemoteMoveOn )
1784{
1785 BOOST_TEST_REQUIRE( ready() );
1786
1787 git_repository* repo = openRepo();
1788 BOOST_TEST_REQUIRE( repo );
1789
1790 KIGIT_COMMON common( repo );
1791 BOOST_REQUIRE( common.AddRemote( wxT( "origin" ), wxT( "https://example.com/x.git" ) ) );
1792
1793 git_reference* head = nullptr;
1794 BOOST_REQUIRE_EQUAL( git_repository_head( &head, repo ), GIT_OK );
1795
1796 wxString branch = wxString::FromUTF8( git_reference_shorthand( head ) );
1797 std::string trackingRef = ( wxT( "refs/remotes/origin/" ) + branch ).utf8_string();
1798 std::string upstreamName = ( wxT( "origin/" ) + branch ).utf8_string();
1799 git_oid base = *git_reference_target( head );
1800
1801 git_reference* tracking = nullptr;
1802 BOOST_REQUIRE_EQUAL( git_reference_create( &tracking, repo, trackingRef.c_str(), &base, 0, nullptr ), GIT_OK );
1803 git_reference_free( tracking );
1804 BOOST_REQUIRE_EQUAL( git_branch_set_upstream( head, upstreamName.c_str() ), GIT_OK );
1805
1806 // In step with the upstream.
1807 std::optional<KIGIT_UPSTREAM_STATUS> status = common.UpstreamStatus();
1808 BOOST_REQUIRE( status && status->hasUpstream );
1809 BOOST_CHECK_EQUAL( status->divergence.behind, 0u );
1810
1811 // The upstream moves on.
1812 git_oid remoteTip = createDetachedCommit( repo, base, wxT( "file.txt" ), "remote\n", "Remote change" );
1813 BOOST_REQUIRE_EQUAL( git_reference_create( &tracking, repo, trackingRef.c_str(), &remoteTip, 1, nullptr ), GIT_OK );
1814 git_reference_free( tracking );
1815
1816 status = common.UpstreamStatus();
1817 BOOST_REQUIRE( status );
1818 BOOST_CHECK_EQUAL( status->divergence.behind, 1u );
1819
1820 git_reference_free( head );
1821 git_repository_free( repo );
1822}
1823
1824
1825// Rebuilding the index from HEAD would drop the conflict stages before libgit2's unmerged-index
1826// guard could see them, recording the markers as resolved content.
1827BOOST_AUTO_TEST_CASE( Commit_RefusesConflictedRepository )
1828{
1829 BOOST_TEST_REQUIRE( ready() );
1830
1831 git_repository* repo = openRepo();
1832 BOOST_TEST_REQUIRE( repo );
1833
1834 git_oid baseOid;
1835 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &baseOid, repo, "HEAD" ), GIT_OK );
1836
1837 createCommit( repo, wxT( "file.txt" ), wxT( "mine\n" ), wxT( "Local change" ) );
1838
1839 git_oid remoteCommitOid = createDetachedCommit( repo, baseOid, wxT( "file.txt" ), "remote\n", "Remote change" );
1840
1841 git_annotated_commit* theirs = nullptr;
1842 BOOST_REQUIRE_EQUAL( git_annotated_commit_lookup( &theirs, repo, &remoteCommitOid ), GIT_OK );
1843
1844 const git_annotated_commit* heads[1] = { theirs };
1845 BOOST_REQUIRE_EQUAL( git_merge( repo, heads, 1, nullptr, nullptr ), GIT_OK );
1846 git_annotated_commit_free( theirs );
1847
1848 git_index* index = nullptr;
1849 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
1850 BOOST_REQUIRE( git_index_has_conflicts( index ) );
1851 git_index_free( index );
1852
1853 git_oid headBefore;
1854 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headBefore, repo, "HEAD" ), GIT_OK );
1855
1856 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
1857
1858 auto readAll = []( const wxString& aPath )
1859 {
1860 std::ifstream in( aPath.ToStdString(), std::ios::binary );
1861 return std::string( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
1862 };
1863
1864 std::string conflictedBytes = readAll( workDir + wxT( "file.txt" ) );
1865
1866 GIT_COMMIT_HANDLER handler( repo );
1867
1868 BOOST_CHECK( handler.PerformCommit( { wxT( "file.txt" ) }, wxT( "Oops" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL )
1870 BOOST_CHECK( !handler.GetErrorString().IsEmpty() );
1871
1872 BOOST_CHECK( handler.PerformAmend( { wxT( "file.txt" ) }, wxT( "Oops" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL )
1874
1875 // A clean selected file elsewhere must not erase the unrelated conflict either.
1876 {
1877 std::ofstream f( ( workDir + wxT( "other.txt" ) ).ToStdString(), std::ios::binary );
1878 f << "clean\n";
1879 }
1880
1881 BOOST_CHECK( handler.PerformCommit( { wxT( "other.txt" ) }, wxT( "Oops" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL )
1883
1884 git_oid headAfter;
1885 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headAfter, repo, "HEAD" ), GIT_OK );
1886 BOOST_CHECK_EQUAL( git_oid_cmp( &headBefore, &headAfter ), 0 );
1887
1888 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
1889 BOOST_CHECK( git_index_has_conflicts( index ) );
1890 git_index_free( index );
1891
1892 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_MERGE );
1893 BOOST_CHECK_EQUAL( readAll( workDir + wxT( "file.txt" ) ), conflictedBytes );
1894
1895 // An in-progress merge whose conflicts were staged as resolved is still not an ordinary
1896 // commit: the single-parent path would record the wrong parent structure.
1897 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
1898 BOOST_REQUIRE_EQUAL( git_index_add_bypath( index, "file.txt" ), GIT_OK );
1899 BOOST_REQUIRE_EQUAL( git_index_write( index ), GIT_OK );
1900 git_index_free( index );
1901
1902 BOOST_CHECK( handler.PerformCommit( { wxT( "file.txt" ) }, wxT( "Oops" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL )
1904 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_MERGE );
1905
1906 git_repository_free( repo );
1907}
1908
1909
1910// A surviving staged entry would leave a phantom New row in the checklist.
1911BOOST_AUTO_TEST_CASE( DiscardChangesDropsStagedEntryForNeverCommittedFile )
1912{
1913 BOOST_TEST_REQUIRE( ready() );
1914
1915 git_repository* repo = openRepo();
1916 BOOST_TEST_REQUIRE( repo );
1917
1918 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
1919
1920 {
1921 std::ofstream f( ( workDir + wxT( "staged.txt" ) ).ToStdString(), std::ios::binary );
1922 f << "staged outside\n";
1923 }
1924
1925 git_index* index = nullptr;
1926 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
1927 BOOST_REQUIRE_EQUAL( git_index_add_bypath( index, "staged.txt" ), GIT_OK );
1928 BOOST_REQUIRE_EQUAL( git_index_write( index ), GIT_OK );
1929 git_index_free( index );
1930
1931 BOOST_TEST_REQUIRE( wxRemoveFile( workDir + wxT( "staged.txt" ) ) );
1932
1933 KIGIT_COMMON common( repo );
1934 wxString error;
1935
1936 BOOST_REQUIRE_MESSAGE( common.DiscardChanges( { wxT( "staged.txt" ) }, error ), error );
1938
1939 git_repository_free( repo );
1940}
1941
1942
1943// A second operation that cannot get the lock returns Busy without touching the cancellation
1944// of the one holding it, and a cancelled operation leaves none behind for the next.
1945BOOST_AUTO_TEST_CASE( BusyOperationDoesNotConsumeAnotherCancellation )
1946{
1947 BOOST_TEST_REQUIRE( ready() );
1948
1949 git_repository* repo = openRepo();
1950 BOOST_TEST_REQUIRE( repo );
1951
1952 addOrigin( repo );
1953
1954 KIGIT_COMMON common( repo );
1955
1956 GIT_PUSH_HANDLER pushA( &common );
1957 KIGIT_COMMON::CANCEL_TOKEN tokenA = pushA.CancelToken();
1958
1959 BOOST_REQUIRE( tokenA );
1960 BOOST_REQUIRE( !tokenA->load() );
1961
1962 {
1963 // What the backend does for A once it owns the action lock.
1964 KIGIT_COMMON::OPERATION_GUARD operationA( &common, tokenA );
1965
1966 tokenA->store( true );
1967
1968 // A is holding the action lock, so B cannot start.
1969 std::unique_lock<std::mutex> heldByA = common.LockAction();
1970
1971 GIT_PUSH_HANDLER pushB( &common );
1972 KIGIT_COMMON::CANCEL_TOKEN tokenB = pushB.CancelToken();
1973
1974 BOOST_CHECK_MESSAGE( tokenB != tokenA, "each operation must own its own token" );
1975
1976 // From another thread, since trying a lock from the thread that holds it is not defined.
1977 PushResult resultB = std::async( std::launch::async,
1978 [&pushB]()
1979 {
1980 return pushB.PerformPush();
1981 } )
1982 .get();
1983
1984 BOOST_CHECK_EQUAL( static_cast<int>( resultB ), static_cast<int>( PushResult::Busy ) );
1985
1986 BOOST_CHECK_MESSAGE( tokenA->load(), "a Busy operation must not clear another's cancellation" );
1987 BOOST_CHECK_MESSAGE( !tokenB->load(), "a Busy operation must not inherit another's cancellation" );
1988 BOOST_CHECK_MESSAGE( common.GetRecentCommits().empty(),
1989 "a Busy operation must leave the active read cancelled" );
1990 }
1991
1992 BOOST_CHECK_MESSAGE( !common.GetRecentCommits().empty(),
1993 "later reads must not inherit the finished operation's cancellation" );
1994
1995 // A cancelled operation used to leave its token published for the next one to adopt.
1996 GIT_PUSH_HANDLER pushC( &common );
1997
1998 BOOST_CHECK_MESSAGE( pushC.CancelToken() != tokenA, "a later operation must not inherit the retired token" );
1999 BOOST_CHECK_MESSAGE( !pushC.IsThisOperationCancelled(), "a later operation must start uncancelled" );
2000
2001 git_repository_free( repo );
2002}
2003
2004
2005// Cancel from the first progress update.
2007{
2008public:
2009 void SetNumPhases( int ) override {}
2010 void AddPhases( int ) override {}
2011 void BeginPhase( int ) override {}
2012 void AdvancePhase() override {}
2013 void AdvancePhase( const wxString& ) override {}
2014 void Report( const wxString& ) override {}
2015 void SetCurrentProgress( double ) override {}
2016 void SetMaxProgress( int ) override {}
2017 void AdvanceProgress() override {}
2018 void SetTitle( const wxString& ) override {}
2019 bool IsCancelled() const override { return true; }
2020
2021 bool KeepRefreshing( bool = false ) override
2022 {
2023 m_ticks++;
2024 return false;
2025 }
2026
2027 int Ticks() const { return m_ticks; }
2028
2029private:
2030 int m_ticks = 0;
2031};
2032
2033
2034// Cancelling in the progress dialog must stop the clone and remove its partial checkout.
2035BOOST_AUTO_TEST_CASE( Clone_CancelFromProgressReporterStopsTheClone )
2036{
2037 BOOST_TEST_REQUIRE( ready() );
2038
2039 wxString dest = tempBase() + wxFileName::GetPathSeparator() + wxT( "clone_cancelled" );
2040
2041 KIGIT_COMMON common( nullptr );
2042 GIT_CLONE_HANDLER handler( &common );
2043
2044 handler.SetRemote( wxFileSystem::FileNameToURL( wxFileName( remotePath() ) ) );
2045 handler.SetClonePath( dest );
2046
2047 auto reporter = std::make_unique<CLONE_CANCEL_REPORTER>();
2048 CLONE_CANCEL_REPORTER* watcher = reporter.get();
2049
2050 handler.SetProgressReporter( std::move( reporter ) );
2051
2052 bool cloned = handler.PerformClone();
2053
2054 BOOST_REQUIRE_MESSAGE( watcher->Ticks() > 0, "the clone must report progress at least once" );
2055 BOOST_CHECK_MESSAGE( handler.IsThisOperationCancelled(), "the clone must record the cancellation" );
2056 BOOST_CHECK_MESSAGE( !cloned, "a clone cancelled from the progress dialog must not report success" );
2057 BOOST_CHECK_MESSAGE( !wxDirExists( dest ), "a cancelled clone must not leave a directory that blocks a retry" );
2058
2059 if( common.GetRepo() )
2060 {
2061 git_repository_free( common.GetRepo() );
2062 common.SetRepo( nullptr );
2063 }
2064}
2065
2066
2067// Cancel pressed while the task is still queued must stop it before any network work.
2068BOOST_AUTO_TEST_CASE( CancelRequestedWhileQueuedAbortsTransfer )
2069{
2070 BOOST_TEST_REQUIRE( ready() );
2071
2072 git_repository* repo = openRepo();
2073 BOOST_TEST_REQUIRE( repo );
2074
2075 createCommit( repo, wxT( "file.txt" ), wxT( "second\n" ), wxT( "Second commit" ) );
2076 addOrigin( repo );
2077
2078 KIGIT_COMMON common( repo );
2079
2080 // What the panel does: make the token, then cancel it before the worker starts.
2082 token->store( true );
2083
2084 GIT_PULL_HANDLER pullHandler( &common );
2085 pullHandler.SetCancelToken( token );
2086
2087 BOOST_CHECK( !pullHandler.PerformFetch() );
2088 BOOST_CHECK( pullHandler.IsThisOperationCancelled() );
2089
2090 GIT_PUSH_HANDLER pushHandler( &common );
2091 pushHandler.SetCancelToken( token );
2092
2093 BOOST_CHECK_EQUAL( static_cast<int>( pushHandler.PerformPush() ), static_cast<int>( PushResult::Error ) );
2094
2095 // The session was never shutting down, so it must not look like it afterwards.
2096 BOOST_CHECK( !common.IsShuttingDown() );
2097
2098 git_repository_free( repo );
2099}
2100
2101
2102// The session-wide shutdown flag reaches an operation that starts after it was raised.
2103BOOST_AUTO_TEST_CASE( ShutdownRequestAbortsAnOperationThatStartsAfterIt )
2104{
2105 BOOST_TEST_REQUIRE( ready() );
2106
2107 git_repository* repo = openRepo();
2108 BOOST_TEST_REQUIRE( repo );
2109
2110 createCommit( repo, wxT( "file.txt" ), wxT( "second\n" ), wxT( "Second commit" ) );
2111 addOrigin( repo );
2112
2113 KIGIT_COMMON common( repo );
2114
2115 common.SetShuttingDown( true );
2116
2117 GIT_PULL_HANDLER pullHandler( &common );
2118 BOOST_CHECK( !pullHandler.PerformFetch() );
2119
2120 GIT_PUSH_HANDLER pushHandler( &common );
2121 PushResult result = pushHandler.PerformPush();
2122
2123 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( PushResult::Error ) );
2124 BOOST_CHECK( common.IsShuttingDown() );
2125
2126 git_repository_free( repo );
2127}
2128
2129
2130BOOST_AUTO_TEST_CASE( Amend_MessageOnlyRewritesHeadKeepsTree )
2131{
2132 BOOST_TEST_REQUIRE( ready() );
2133
2134 git_repository* repo = openRepo();
2135 BOOST_TEST_REQUIRE( repo );
2136
2137 git_reference* headRefBefore = nullptr;
2138 git_repository_head( &headRefBefore, repo );
2139 git_oid oidBefore = *git_reference_target( headRefBefore );
2140
2141 git_commit* commitBefore = nullptr;
2142 git_reference_peel( (git_object**) &commitBefore, headRefBefore, GIT_OBJECT_COMMIT );
2143 git_oid treeBefore = *git_commit_tree_id( commitBefore );
2144
2145 git_commit_free( commitBefore );
2146 git_reference_free( headRefBefore );
2147
2148 GIT_COMMIT_HANDLER handler( repo );
2149 CommitResult result = handler.PerformAmend( {}, wxT( "Amended message" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
2150 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( CommitResult::Success ) );
2151
2152 git_reference* headRefAfter = nullptr;
2153 git_repository_head( &headRefAfter, repo );
2154 git_oid oidAfter = *git_reference_target( headRefAfter );
2155
2156 git_commit* commitAfter = nullptr;
2157 git_reference_peel( (git_object**) &commitAfter, headRefAfter, GIT_OBJECT_COMMIT );
2158 git_oid treeAfter = *git_commit_tree_id( commitAfter );
2159
2160 BOOST_CHECK( !git_oid_equal( &oidBefore, &oidAfter ) );
2161 BOOST_CHECK( git_oid_equal( &treeBefore, &treeAfter ) );
2162
2163 wxString amendedMsg = wxString::FromUTF8( git_commit_message( commitAfter ) );
2164 BOOST_CHECK_EQUAL( amendedMsg.Trim(), wxString( "Amended message" ) );
2165
2166 git_commit_free( commitAfter );
2167 git_reference_free( headRefAfter );
2168 git_repository_free( repo );
2169}
2170
2171
2172BOOST_AUTO_TEST_CASE( Amend_StagedFileChangesTreeAndKeepsParent )
2173{
2174 BOOST_TEST_REQUIRE( ready() );
2175
2176 git_repository* repo = openRepo();
2177 BOOST_TEST_REQUIRE( repo );
2178
2179 git_reference* headRefBefore = nullptr;
2180 git_repository_head( &headRefBefore, repo );
2181
2182 git_commit* commitBefore = nullptr;
2183 git_reference_peel( (git_object**) &commitBefore, headRefBefore, GIT_OBJECT_COMMIT );
2184 git_oid treeBefore = *git_commit_tree_id( commitBefore );
2185 unsigned int parentCountBefore = git_commit_parentcount( commitBefore );
2186
2187 git_commit_free( commitBefore );
2188 git_reference_free( headRefBefore );
2189
2190 // Add a new file to the working tree so the amend has something to stage.
2191 wxString newFile = repoPath() + wxFileName::GetPathSeparator() + wxT( "new.txt" );
2192 {
2193 std::ofstream f( newFile.ToStdString() );
2194 f << "new content\n";
2195 }
2196
2197 GIT_COMMIT_HANDLER handler( repo );
2198 CommitResult result = handler.PerformAmend( { wxT( "new.txt" ) }, wxT( "Amended with file" ), TEST_AUTHOR_NAME,
2200 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( CommitResult::Success ) );
2201
2202 git_reference* headRefAfter = nullptr;
2203 git_repository_head( &headRefAfter, repo );
2204
2205 git_commit* commitAfter = nullptr;
2206 git_reference_peel( (git_object**) &commitAfter, headRefAfter, GIT_OBJECT_COMMIT );
2207 git_oid treeAfter = *git_commit_tree_id( commitAfter );
2208 unsigned int parentCountAfter = git_commit_parentcount( commitAfter );
2209
2210 BOOST_CHECK( !git_oid_equal( &treeBefore, &treeAfter ) );
2211 BOOST_CHECK_EQUAL( parentCountAfter, parentCountBefore );
2212
2213 // new.txt should now be in HEAD's tree.
2214 git_tree* treeObj = nullptr;
2215 git_commit_tree( &treeObj, commitAfter );
2216
2217 const git_tree_entry* entry = git_tree_entry_byname( treeObj, "new.txt" );
2218 BOOST_CHECK( entry != nullptr );
2219
2220 git_tree_free( treeObj );
2221 git_commit_free( commitAfter );
2222 git_reference_free( headRefAfter );
2223 git_repository_free( repo );
2224}
2225
2226
2227// A repository with no commits yet must fail cleanly rather than crash or write a bogus commit.
2228BOOST_AUTO_TEST_CASE( Amend_UnbornBranchReturnsError )
2229{
2230 BOOST_TEST_REQUIRE( ready() );
2231
2232 wxString unbornDir = repoPath() + wxT( "_unborn" );
2233 wxFileName::Mkdir( unbornDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
2234
2235 git_repository* unbornRepo = nullptr;
2236 BOOST_TEST_REQUIRE( git_repository_init( &unbornRepo, unbornDir.ToUTF8().data(), 0 ) == 0 );
2237
2238 GIT_COMMIT_HANDLER handler( unbornRepo );
2239 CommitResult result = handler.PerformAmend( {}, wxT( "should fail" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
2240
2241 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( CommitResult::Error ) );
2242 BOOST_CHECK( !handler.GetErrorString().IsEmpty() );
2243
2244 git_repository_free( unbornRepo );
2245
2246 if( wxFileName::DirExists( unbornDir ) )
2247 wxFileName::Rmdir( unbornDir, wxPATH_RMDIR_RECURSIVE );
2248}
2249
2250
2251BOOST_AUTO_TEST_CASE( SetupRemote_PreservesSshSchemePortAndUsername )
2252{
2253 BOOST_TEST_REQUIRE( ready() );
2254
2255 KIGIT::GitRepositoryPtr repo( openRepo() );
2256 BOOST_REQUIRE( repo );
2257
2258 KIGIT_COMMON common( repo.get() );
2259 GIT_INIT_HANDLER handler( &common );
2261 config.url = wxS( "ssh://[email protected]:29022/srv/git/repos/l3-auth-30.git" );
2262 config.username = wxS( "saved-user" );
2263 config.password = wxS( "key-passphrase" );
2265
2266 BOOST_REQUIRE( handler.SetupRemote( config ) );
2267 BOOST_CHECK_EQUAL( readConfig( repo.get(), wxS( "remote.origin.url" ) ).ToStdString(), config.url.ToStdString() );
2268 BOOST_CHECK_EQUAL( common.GetRemote().ToStdString(), config.url.ToStdString() );
2269 BOOST_CHECK_EQUAL( common.GetUsername().ToStdString(), "runner" );
2270 BOOST_CHECK_EQUAL( common.GetPassword().ToStdString(), "key-passphrase" );
2272}
2273
2274
2275BOOST_AUTO_TEST_CASE( SetupRemote_UpdatesExistingOriginWithScpAddress )
2276{
2277 BOOST_TEST_REQUIRE( ready() );
2278
2279 KIGIT::GitRepositoryPtr repo( openRepo() );
2280 BOOST_REQUIRE( repo );
2281 BOOST_REQUIRE( addOrigin( repo.get() ) );
2282
2283 KIGIT_COMMON common( repo.get() );
2284 GIT_INIT_HANDLER handler( &common );
2286 config.url = wxS( "runner@host:path/repo" );
2287 config.username = wxS( "saved-user" );
2289
2290 BOOST_REQUIRE( handler.SetupRemote( config ) );
2291 BOOST_CHECK_EQUAL( readConfig( repo.get(), wxS( "remote.origin.url" ) ).ToStdString(), config.url.ToStdString() );
2292 BOOST_CHECK_EQUAL( common.GetRemote().ToStdString(), config.url.ToStdString() );
2293 BOOST_CHECK_EQUAL( common.GetUsername().ToStdString(), "runner" );
2295}
2296
2297
2298BOOST_AUTO_TEST_CASE( SetupRemote_ExtractsHttpCredentialsWithoutPersistingThem )
2299{
2300 BOOST_TEST_REQUIRE( ready() );
2301
2302 KIGIT::GitRepositoryPtr repo( openRepo() );
2303 BOOST_REQUIRE( repo );
2304
2305 KIGIT_COMMON common( repo.get() );
2306 GIT_INIT_HANDLER handler( &common );
2308 config.url = wxS( "https://url-user:pa@ss:[email protected]:8443/x/[email protected]" );
2309 config.username = wxS( "saved-user" );
2311
2312 BOOST_REQUIRE( handler.SetupRemote( config ) );
2313 BOOST_CHECK_EQUAL( readConfig( repo.get(), wxS( "remote.origin.url" ) ).ToStdString(),
2314 "https://example.com:8443/x/[email protected]" );
2315 BOOST_CHECK_EQUAL( common.GetRemote().ToStdString(), "https://example.com:8443/x/[email protected]" );
2316 BOOST_CHECK_EQUAL( common.GetUsername().ToStdString(), "url-user" );
2317 BOOST_CHECK_EQUAL( common.GetPassword().ToStdString(), "pa@ss:word" );
2319
2320 // A password typed separately replaces the one pasted in the URL.
2321 config.password = wxS( "typed@pass:word" );
2322 BOOST_REQUIRE( handler.SetupRemote( config ) );
2323 BOOST_CHECK_EQUAL( readConfig( repo.get(), wxS( "remote.origin.url" ) ).ToStdString(),
2324 "https://example.com:8443/x/[email protected]" );
2325 BOOST_CHECK_EQUAL( common.GetPassword().ToStdString(), "typed@pass:word" );
2326}
2327
2328
2329BOOST_AUTO_TEST_CASE( SetupRemote_KeepsSeparateHttpCredentialsForImmediateFetch )
2330{
2331 BOOST_TEST_REQUIRE( ready() );
2332
2333 KIGIT::GitRepositoryPtr repo( openRepo() );
2334 BOOST_REQUIRE( repo );
2335
2336 KIGIT_COMMON common( repo.get() );
2337 GIT_INIT_HANDLER handler( &common );
2339 config.url = wxS( "http://example.com/repo.git" );
2340 config.username = wxS( "alice" );
2341 config.password = wxS( "typed@pass:word" );
2343
2344 BOOST_REQUIRE( handler.SetupRemote( config ) );
2345 BOOST_CHECK_EQUAL( readConfig( repo.get(), wxS( "remote.origin.url" ) ).ToStdString(), config.url.ToStdString() );
2346 BOOST_CHECK_EQUAL( common.GetRemote().ToStdString(), config.url.ToStdString() );
2347 BOOST_CHECK_EQUAL( common.GetUsername().ToStdString(), "alice" );
2348 BOOST_CHECK_EQUAL( common.GetPassword().ToStdString(), "typed@pass:word" );
2349}
2350
2351
2352BOOST_AUTO_TEST_CASE( InitializeRepository_SeedsGitignoreWithKicadEntries )
2353{
2354 BOOST_TEST_REQUIRE( ready() );
2355
2356 wxString freshDir = repoPath() + wxT( "_fresh" );
2357 wxFileName::Mkdir( freshDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
2358
2359 KIGIT_COMMON common( nullptr );
2360 GIT_INIT_HANDLER handler( &common );
2361
2362 InitResult result = handler.InitializeRepository( freshDir );
2363 BOOST_REQUIRE_EQUAL( static_cast<int>( result ), static_cast<int>( InitResult::Success ) );
2364
2365 wxFileName gitignoreFile( freshDir, wxT( ".gitignore" ) );
2366 BOOST_TEST_REQUIRE( gitignoreFile.FileExists() );
2367
2368 KIGIT::GitRepositoryPtr repo( common.GetRepo() );
2369 common.SetRepo( nullptr );
2370 BOOST_REQUIRE( repo );
2371 useEmptyGlobalIgnore( repo.get() );
2372
2373 const std::pair<const char*, bool> cases[] = {
2374 { "board.kicad_pcb", false },
2375 { "lib.kicad_sym", false },
2376 { "board.kicad_pcb-bak", true },
2377 { "board.lck", true },
2378 { "board.LCK", true },
2379 { "~board.kicad_pcb", true },
2380 { "proj.kicad_prl", true },
2381 { "upper.KiCaD_PrL", true },
2382 { "proj-backups/board.zip", true },
2383 { "data-proj-backups/board.kicad_pcb", true },
2384 { "nested/proj-backups/old/board.zip", true },
2385 { "proj-backups-old/board.kicad_pcb", false },
2386 { ".history/board.kicad_pcb", true },
2387 { ".history/.git/objects/ab/cdef", true },
2388 { ".history-notes/board.kicad_pcb", false },
2389 { "named/.history", false },
2390 { "named/proj-backups", false },
2391 { "_autosave-board.kicad_pcb", true },
2392 { "_autosave-design/board.kicad_pcb", true },
2393 { "fp-info-cache", true },
2394 { "fp-info-cache.kicad_pcb", false },
2395 { "cache.kicad_prl/board.kicad_pcb", true },
2396 { "board.kicad_pcb.mine", true },
2397 { "board.kicad_pcb.theirs", true },
2398 { "board.kicad_pcb.mine.1", true },
2399 { "board.kicad_pcb.theirs.17", true },
2400 { "board.kicad_pcb.mine.99", true },
2401 { "board.kicad_pcb.mine.100", false },
2402 { "board.kicad_pcb.mine.1notes", false },
2403 { "board.kicad_pcb.theirs.notes", false },
2404 { "board.mine.kicad_pcb", false },
2405 { "board.kicad_pcb.1", false },
2406 };
2407
2408 for( const auto& [path, transient] : cases )
2409 {
2411 {
2412 KI_TEST::WriteGitFile( freshDir, wxString::FromUTF8( path ), "test file\n" );
2413 int ignored = 0;
2414 BOOST_REQUIRE_EQUAL( git_ignore_path_is_ignored( &ignored, repo.get(), path ), GIT_OK );
2415 BOOST_CHECK_EQUAL( ignored != 0, transient );
2417 }
2418 }
2419
2420 repo.reset();
2421
2422 if( wxFileName::DirExists( freshDir ) )
2423 wxFileName::Rmdir( freshDir, wxPATH_RMDIR_RECURSIVE );
2424}
2425
2426
2427// A curated .gitignore must not be edited. Appending defaults dirtied a fresh clone.
2428BOOST_AUTO_TEST_CASE( InitializeRepository_LeavesExistingGitignoreUntouched )
2429{
2430 BOOST_TEST_REQUIRE( ready() );
2431
2432 wxString freshDir = repoPath() + wxT( "_existing" );
2433 wxFileName::Mkdir( freshDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
2434
2435 const wxString curated = wxT( "# my custom ignores\n.history/\nbuild/\n" );
2436 wxFileName gitignoreFile( freshDir, wxT( ".gitignore" ) );
2437
2438 {
2439 wxFFile f( gitignoreFile.GetFullPath(), wxT( "wb" ) );
2440 f.Write( curated );
2441 }
2442
2443 KIGIT_COMMON common( nullptr );
2444 GIT_INIT_HANDLER handler( &common );
2445
2446 InitResult result = handler.InitializeRepository( freshDir );
2447 BOOST_CHECK_EQUAL( static_cast<int>( result ), static_cast<int>( InitResult::Success ) );
2448
2449 wxString after;
2450 {
2451 wxFFile f( gitignoreFile.GetFullPath(), wxT( "rb" ) );
2452 f.ReadAll( &after );
2453 }
2454
2455 BOOST_CHECK_EQUAL( after.ToStdString(), curated.ToStdString() );
2456
2457 if( wxFileName::DirExists( freshDir ) )
2458 wxFileName::Rmdir( freshDir, wxPATH_RMDIR_RECURSIVE );
2459}
2460
2461
2462// An empty file is still the team's file, so it stays empty rather than being filled in.
2463BOOST_AUTO_TEST_CASE( InitializeRepository_LeavesEmptyGitignoreEmpty )
2464{
2465 BOOST_TEST_REQUIRE( ready() );
2466
2467 wxString freshDir = repoPath() + wxT( "_emptyignore" );
2468 wxFileName::Mkdir( freshDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
2469
2470 wxFileName gitignoreFile( freshDir, wxT( ".gitignore" ) );
2471
2472 {
2473 wxFFile f( gitignoreFile.GetFullPath(), wxT( "wb" ) );
2474 }
2475
2476 KIGIT_COMMON common( nullptr );
2477 GIT_INIT_HANDLER handler( &common );
2478
2479 BOOST_CHECK_EQUAL( static_cast<int>( handler.InitializeRepository( freshDir ) ),
2480 static_cast<int>( InitResult::Success ) );
2481
2482 BOOST_TEST_REQUIRE( gitignoreFile.FileExists() );
2483 BOOST_CHECK_EQUAL( gitignoreFile.GetSize().GetValue(), 0u );
2484
2485 if( wxFileName::DirExists( freshDir ) )
2486 wxFileName::Rmdir( freshDir, wxPATH_RMDIR_RECURSIVE );
2487}
2488
2489
2490// LoadProject() needs a real project file with a meta section.
2491static wxString seedProjectFile( const wxString& aDir )
2492{
2493 wxString path = aDir + wxFileName::GetPathSeparator() + wxT( "proj.kicad_pro" );
2494
2495 if( !wxFileName::FileExists( path ) )
2496 {
2497 wxFFile f( path, wxT( "w" ) );
2498 f.Write( wxT( "{\"meta\": {\"filename\": \"proj.kicad_pro\", \"version\": 3}}" ) );
2499 }
2500
2501 return path;
2502}
2503
2504
2505BOOST_AUTO_TEST_CASE( ProjectGitCommon_LazyCreateAttachRelease )
2506{
2507 BOOST_TEST_REQUIRE( ready() );
2508
2509 wxString projectPath = seedProjectFile( repoPath() );
2510
2511 SETTINGS_MANAGER mgr;
2512 BOOST_TEST_REQUIRE( mgr.LoadProject( projectPath ) );
2513
2514 PROJECT* project = mgr.GetProject( projectPath );
2515 BOOST_TEST_REQUIRE( project != nullptr );
2516
2517 std::shared_ptr<KIGIT_COMMON> common = project->GetGitCommon();
2518 BOOST_TEST_REQUIRE( common != nullptr );
2519 BOOST_CHECK( common->GetRepo() == nullptr );
2520 BOOST_CHECK( common == project->GetGitCommon() );
2521
2522 BOOST_TEST_REQUIRE( project->AttachGitRepository() );
2523 git_repository* repo = common->GetRepo();
2524 BOOST_TEST_REQUIRE( repo != nullptr );
2525 BOOST_CHECK( !common->GetProjectDir().IsEmpty() );
2526
2527 BOOST_TEST_REQUIRE( project->AttachGitRepository() );
2528 BOOST_CHECK( common->GetRepo() == repo );
2529
2530 project->ReleaseGitCommon();
2531
2532 std::shared_ptr<KIGIT_COMMON> fresh = project->GetGitCommon();
2533 BOOST_TEST_REQUIRE( fresh != nullptr );
2534 BOOST_CHECK( fresh != common );
2535 BOOST_CHECK( fresh->GetRepo() == nullptr );
2536 BOOST_CHECK( common->GetRepo() == nullptr );
2537
2538 // Unloading with the repository still attached exercises the destructor release path.
2539 BOOST_TEST_REQUIRE( project->AttachGitRepository() );
2540 BOOST_CHECK( mgr.UnloadProject( project, false ) );
2541}
2542
2543
2544BOOST_AUTO_TEST_CASE( ProjectGitCommon_ReleaseSkipsFreeWhenBackendGone )
2545{
2546 BOOST_TEST_REQUIRE( ready() );
2547
2548 wxString projectPath = seedProjectFile( repoPath() );
2549
2550 SETTINGS_MANAGER mgr;
2551 BOOST_TEST_REQUIRE( mgr.LoadProject( projectPath ) );
2552
2553 PROJECT* project = mgr.GetProject( projectPath );
2554 BOOST_TEST_REQUIRE( project != nullptr );
2555 BOOST_TEST_REQUIRE( project->AttachGitRepository() );
2556
2557 git_repository* repo = project->GetGitCommon()->GetRepo();
2558 BOOST_TEST_REQUIRE( repo != nullptr );
2559
2560 // Simulate the process-exit ordering where the backend is torn down before the
2561 // last project. The release must clear the handle without freeing it, since a free
2562 // would call into a shut-down libgit2.
2563 GIT_BACKEND* backend = GetGitBackend();
2564 SetGitBackend( nullptr );
2565
2566 project->ReleaseGitCommon();
2567
2568 BOOST_CHECK( project->GetGitCommon()->GetRepo() == nullptr );
2569
2570 SetGitBackend( backend );
2571
2572 // The release skipped the free on purpose, so reclaim the handle now.
2573 git_repository_free( repo );
2574}
2575
2576
2577BOOST_AUTO_TEST_CASE( ProjectGitCommon_AttachOutsideRepositoryFails )
2578{
2579 BOOST_TEST_REQUIRE( ready() );
2580
2581 wxFileName tempBase( repoPath(), wxEmptyString );
2582 tempBase.RemoveLastDir();
2583 wxString outsideDir = tempBase.GetPath() + wxFileName::GetPathSeparator() + wxT( "no_repo_here" );
2584 wxFileName::Mkdir( outsideDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
2585
2586 wxString projectPath = seedProjectFile( outsideDir );
2587
2588 SETTINGS_MANAGER mgr;
2589 BOOST_TEST_REQUIRE( mgr.LoadProject( projectPath ) );
2590
2591 PROJECT* project = mgr.GetProject( projectPath );
2592 BOOST_TEST_REQUIRE( project != nullptr );
2593
2594 BOOST_CHECK( !project->AttachGitRepository() );
2595 BOOST_CHECK( project->GetGitCommon()->GetRepo() == nullptr );
2596}
2597
2598
2599BOOST_AUTO_TEST_CASE( ProjectGitCommon_AttachHonorsDisabledSetting )
2600{
2601 BOOST_TEST_REQUIRE( ready() );
2602
2603 wxString projectPath = seedProjectFile( repoPath() );
2604
2605 SETTINGS_MANAGER mgr;
2606 BOOST_TEST_REQUIRE( mgr.LoadProject( projectPath ) );
2607
2608 PROJECT* project = mgr.GetProject( projectPath );
2609 BOOST_TEST_REQUIRE( project != nullptr );
2610
2611 project->GetLocalSettings().m_GitIntegrationDisabled = true;
2612
2613 BOOST_CHECK( !project->AttachGitRepository() );
2614 BOOST_CHECK( project->GetGitCommon()->GetRepo() == nullptr );
2615
2616 project->GetLocalSettings().m_GitIntegrationDisabled = false;
2617
2618 BOOST_CHECK( project->AttachGitRepository() );
2619 BOOST_CHECK( project->GetGitCommon()->GetRepo() != nullptr );
2620
2621 project->ReleaseGitCommon();
2622}
2623
2624
2625BOOST_AUTO_TEST_CASE( ProjectGitCommon_ReleaseDefersFreeWhileActionMutexHeld )
2626{
2627 BOOST_TEST_REQUIRE( ready() );
2628
2629 wxString projectPath = seedProjectFile( repoPath() );
2630
2631 SETTINGS_MANAGER mgr;
2632 BOOST_TEST_REQUIRE( mgr.LoadProject( projectPath ) );
2633
2634 PROJECT* project = mgr.GetProject( projectPath );
2635 BOOST_TEST_REQUIRE( project != nullptr );
2636
2637 BOOST_TEST_REQUIRE( project->AttachGitRepository() );
2638 std::shared_ptr<KIGIT_COMMON> common = project->GetGitCommon();
2639
2640 std::promise<void> lockHeld;
2641 std::promise<void> allowUnlock;
2642
2643 std::thread worker(
2644 [&]()
2645 {
2646 std::unique_lock<std::mutex> lock = common->LockAction();
2647 lockHeld.set_value();
2648 allowUnlock.get_future().wait();
2649 } );
2650
2651 lockHeld.get_future().wait();
2652
2653 // The worker holds the action mutex, so the release must defer the free to the
2654 // orphan registry instead of blocking. The repo handle must stay valid for the
2655 // running operation until it finishes.
2656 project->ReleaseGitCommon();
2657
2658 BOOST_CHECK( common->GetRepo() != nullptr );
2659
2660 allowUnlock.set_value();
2661 worker.join();
2662
2663 BOOST_REQUIRE_EQUAL( GetGitBackend()->OrphanRegistry().JoinAll( std::chrono::seconds( 5 ) ), 0u );
2664 BOOST_CHECK( common->GetRepo() == nullptr );
2665}
2666
2667
2668// A listed path that is not a regular file is still a path. A symlink to a directory, and a
2669// submodule, both look absent to a regular-file test, and recording them as deletions drops
2670// them out of the project.
2671#ifndef __WINDOWS__
2672BOOST_AUTO_TEST_CASE( CommitKeepsAPathThatIsNotARegularFile )
2673{
2674 BOOST_TEST_REQUIRE( ready() );
2675
2676 git_repository* repo = openRepo();
2677 BOOST_TEST_REQUIRE( repo );
2678
2679 wxString sep = wxFileName::GetPathSeparator();
2680 BOOST_REQUIRE( wxFileName::Mkdir( repoPath() + sep + wxT( "shared" ), 0700, wxPATH_MKDIR_FULL ) );
2681
2682 {
2683 std::ofstream f( ( repoPath() + sep + wxT( "shared" ) + sep + wxT( "lib.txt" ) ).ToStdString() );
2684 f << "shared\n";
2685 }
2686
2687 BOOST_REQUIRE_EQUAL( symlink( "shared", ( repoPath() + sep + wxT( "link" ) ).ToUTF8().data() ), 0 );
2688
2689 GIT_COMMIT_HANDLER handler( repo );
2690
2691 BOOST_REQUIRE( handler.PerformCommit( { wxT( "link" ) }, wxT( "Add the shared library link" ), wxT( "Test Author" ),
2692 wxT( "[email protected]" ) )
2694
2695 git_oid headOid;
2696 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
2697
2698 git_commit* head = nullptr;
2699 BOOST_REQUIRE_EQUAL( git_commit_lookup( &head, repo, &headOid ), GIT_OK );
2700
2701 git_tree* tree = nullptr;
2702 BOOST_REQUIRE_EQUAL( git_commit_tree( &tree, head ), GIT_OK );
2703
2704 git_tree_entry* entry = nullptr;
2705 BOOST_CHECK_MESSAGE( git_tree_entry_bypath( &entry, tree, "link" ) == GIT_OK,
2706 "the commit dropped the symlink instead of recording it" );
2707
2708 if( entry )
2709 git_tree_entry_free( entry );
2710
2711 git_tree_free( tree );
2712 git_commit_free( head );
2713 git_repository_free( repo );
2714}
2715#endif
2716
2717
2718BOOST_AUTO_TEST_CASE( IsTransientGitFile_HandlesDosPaths )
2719{
2721
2722 BOOST_CHECK( PROJECT_GIT_UTILS::IsTransientGitFile( wxFileName( "proj\\.history\\board.kicad_pcb", wxPATH_DOS ) ) );
2724 PROJECT_GIT_UTILS::IsTransientGitFile( wxFileName( "proj\\data-proj-backups\\board.zip", wxPATH_DOS ) ) );
2725 BOOST_CHECK( PROJECT_GIT_UTILS::IsTransientGitFile( wxFileName( "proj\\settings.KICAD_PRL", wxPATH_DOS ) ) );
2726 BOOST_CHECK( PROJECT_GIT_UTILS::IsTransientGitFile( wxFileName( "proj\\board.kicad_pcb.theirs.99", wxPATH_DOS ) ) );
2727 BOOST_CHECK( !PROJECT_GIT_UTILS::IsTransientGitFile(
2728 wxFileName( "proj\\.history-notes\\board.kicad_pcb", wxPATH_DOS ) ) );
2729 BOOST_CHECK( !PROJECT_GIT_UTILS::IsTransientGitFile( wxFileName( "proj\\board.kicad_pcb.mine.100", wxPATH_DOS ) ) );
2730}
2731
2732
2733BOOST_AUTO_TEST_CASE( BuildGitChangeEntries_KeepsTrackedAndStagedTransientFiles )
2734{
2735 BOOST_REQUIRE( ready() );
2736 KIGIT::GitRepositoryPtr repo( openRepo() );
2737 BOOST_REQUIRE( repo );
2738 useEmptyGlobalIgnore( repo.get() );
2739
2740 // An ancestor outside the project must not hide its files.
2741 const wxString prefix = wxS( "workspace-backups/project/" );
2742 const wxString projectPath = repoPath() + wxS( "/" ) + prefix;
2743 KI_TEST::WriteGitFile( repoPath(), prefix + wxS( ".gitignore" ), "" );
2744 KI_TEST::WriteGitFile( repoPath(), prefix + wxS( "tracked.kicad_prl" ), "original settings\n" );
2745 KI_TEST::WriteGitFile( repoPath(), prefix + wxS( "deleted.kicad_pcb.mine" ), "original recovery\n" );
2746 KI_TEST::CommitAllGitFiles( repo.get(), wxS( "Track files the user chose to keep" ) );
2747
2748 KI_TEST::WriteGitFile( repoPath(), prefix + wxS( "tracked.kicad_prl" ), "changed settings with more data\n" );
2749 BOOST_REQUIRE( wxRemoveFile( projectPath + wxS( "deleted.kicad_pcb.mine" ) ) );
2750 KI_TEST::WriteGitFile( repoPath(), prefix + wxS( "staged.kicad_prl" ), "staged settings\n" );
2751
2752 git_index* rawIndex = nullptr;
2753 BOOST_REQUIRE_EQUAL( git_repository_index( &rawIndex, repo.get() ), GIT_OK );
2754 KIGIT::GitIndexPtr index( rawIndex );
2755 BOOST_REQUIRE_EQUAL( git_index_add_bypath( index.get(), ( prefix + wxS( "staged.kicad_prl" ) ).utf8_str() ),
2756 GIT_OK );
2757 BOOST_REQUIRE_EQUAL( git_index_write( index.get() ), GIT_OK );
2758
2759 const char* untracked[] = {
2760 "board.kicad_pcb", "untracked.kicad_prl", "board.kicad_pcb.theirs.17",
2761 "_autosave-board.kicad_pcb", "project-backups/board.zip", ".history/revisions/board.kicad_pcb",
2762 };
2763
2764 for( const char* path : untracked )
2765 KI_TEST::WriteGitFile( repoPath(), prefix + wxString::FromUTF8( path ), "new file\n" );
2766
2767 const std::set<wxString> expected = {
2768 prefix + wxS( "board.kicad_pcb" ),
2769 prefix + wxS( "tracked.kicad_prl" ),
2770 prefix + wxS( "deleted.kicad_pcb.mine" ),
2771 prefix + wxS( "staged.kicad_prl" ),
2772 };
2773
2774 auto checkEntries = [&repo, &expected]( const wxString& aProjectPath )
2775 {
2776 KIGIT_COMMON common( repo.get(), aProjectPath );
2777 std::unique_lock<std::mutex> lock = common.LockAction();
2778 std::set<wxString> paths;
2779
2780 for( const FILE_CHECKLIST_ENTRY& entry : BuildGitChangeEntries( common, aProjectPath, false ) )
2781 paths.insert( entry.path );
2782
2783 BOOST_CHECK_EQUAL_COLLECTIONS( paths.begin(), paths.end(), expected.begin(), expected.end() );
2784 };
2785
2786 checkEntries( projectPath );
2787
2788#ifndef __WINDOWS__
2789 const wxString alias = tempBase() + wxS( "/project-alias" );
2790 BOOST_REQUIRE_EQUAL( symlink( projectPath.utf8_str(), alias.utf8_str() ), 0 );
2791 checkEntries( alias );
2792#endif
2793}
2794
2795
2796// WriteTreeToDir must reproduce the full tree of a ref, including files in subdirectories, so a
2797// hierarchical schematic's sub-sheets are present when the committed side is diffed.
2798BOOST_AUTO_TEST_CASE( WriteTreeToDir_MaterializesSubdirectoryFiles )
2799{
2800 BOOST_TEST_REQUIRE( ready() );
2801
2802 git_repository* repo = openRepo();
2803 BOOST_TEST_REQUIRE( repo );
2804
2805 const wxString sep = wxFileName::GetPathSeparator();
2806
2807 createCommit( repo, wxT( "root.kicad_sch" ), wxT( "root\n" ), wxT( "add root" ) );
2808
2809 BOOST_REQUIRE( wxFileName::Mkdir( repoPath() + sep + wxT( "sub" ), wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) );
2810 createCommit( repo, wxT( "sub/child.kicad_sch" ), wxT( "child\n" ), wxT( "add child" ) );
2811
2812 // Under the fixture's own directory, so a failed run leaves nothing behind in the system temp.
2813 wxString dest = tempBase() + wxFileName::GetPathSeparator() + wxT( "tree_out" );
2814
2815 BOOST_CHECK( KIGIT::PROJECT_GIT_UTILS::WriteTreeToDir( repo, wxT( "HEAD" ), dest ) );
2816 BOOST_CHECK( wxFileName::FileExists( dest + sep + wxT( "root.kicad_sch" ) ) );
2817 BOOST_CHECK_MESSAGE( wxFileName::FileExists( dest + sep + wxT( "sub" ) + sep + wxT( "child.kicad_sch" ) ),
2818 "sub-sheet file in a subdirectory must be materialized alongside the root" );
2819
2820 if( wxFileName::DirExists( dest ) )
2821 wxFileName::Rmdir( dest, wxPATH_RMDIR_RECURSIVE );
2822
2823 git_repository_free( repo );
2824}
2825
2826
2827// The repository must stay untouched until the final commit, and that commit must also bring the
2828// working tree to the merged content.
2829BOOST_AUTO_TEST_CASE( MergeConflictRoundTrip )
2830{
2831 BOOST_TEST_REQUIRE( ready() );
2832
2833 git_repository* repo = openRepo();
2834 BOOST_TEST_REQUIRE( repo );
2835
2836 // Remember the shared base, then diverge: "mine" on HEAD, "remote" on a side commit.
2837 git_reference* headRef = nullptr;
2838 BOOST_REQUIRE_EQUAL( git_repository_head( &headRef, repo ), GIT_OK );
2839 git_oid baseOid = *git_reference_target( headRef );
2840 git_reference_free( headRef );
2841
2842 createCommit( repo, wxT( "file.txt" ), wxT( "mine\n" ), wxT( "Local change" ) );
2843
2844 // The remote-side commit shares the base but does not move HEAD.
2845 git_oid remoteCommitOid = createDetachedCommit( repo, baseOid, wxT( "file.txt" ), "remote\n", "Remote change" );
2846
2847 // A pull would leave this in FETCH_HEAD.
2848 writeFetchHead( remoteCommitOid );
2849
2850 KIGIT_COMMON common( repo );
2851
2852 wxString stageDir = tempBase() + wxFileName::GetPathSeparator() + wxT( "stages" );
2853 wxString headOid, theirsOid, conflictsError;
2854 KIGIT_ERROR_MESSAGE error;
2855 std::vector<KIGIT_CONFLICT_SIDES> conflicts;
2856
2857 BOOST_REQUIRE_MESSAGE( common.GetMergeConflicts( stageDir, headOid, theirsOid, conflicts, conflictsError ),
2858 "GetMergeConflicts failed: " + conflictsError.ToStdString() );
2859 BOOST_REQUIRE_EQUAL( conflicts.size(), 1u );
2860 BOOST_CHECK_EQUAL( conflicts[0].path.ToStdString(), "file.txt" );
2861 BOOST_CHECK( conflicts[0].hasAncestor && conflicts[0].hasOurs && conflicts[0].hasTheirs );
2862
2863 // Reported so the resolutions can be pinned to it.
2864 {
2865 char expect[GIT_OID_HEXSZ + 1] = { 0 };
2866 git_oid_tostr( expect, sizeof( expect ), &remoteCommitOid );
2867 BOOST_CHECK_EQUAL( theirsOid.ToStdString(), std::string( expect ) );
2868 }
2869
2870 auto readAll = []( const wxString& aPath )
2871 {
2872 std::ifstream in( aPath.ToStdString(), std::ios::binary );
2873 return std::string( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
2874 };
2875
2876 BOOST_CHECK_EQUAL( readAll( conflicts[0].oursFile ), "mine\n" );
2877 BOOST_CHECK_EQUAL( readAll( conflicts[0].theirsFile ), "remote\n" );
2878 BOOST_CHECK_EQUAL( readAll( conflicts[0].ancestorFile ), "initial\n" );
2879
2880 // The repository must not have been touched by the conflict listing.
2881 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_NONE );
2882
2883 // Refuse to apply resolutions against a moved head.
2885 static_cast<int>( common.CreateMergedCommit( wxT( "0000000000000000000000000000000000000000" ), theirsOid,
2886 { { conflicts[0].path, conflicts[0].oursFile } }, error ) ),
2887 static_cast<int>( MergeCommitResult::FailedCleanly ) );
2888
2889 // A background fetch can move FETCH_HEAD while the user resolves. The pinned commit id must
2890 // win over whatever FETCH_HEAD says by then.
2891 writeFetchHead( baseOid );
2892
2893 // A save landing while the user resolves must be refused, not reverted by the final
2894 // checkout.
2895 wxString trackedFile = repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" );
2896 {
2897 std::ofstream f( trackedFile.ToStdString(), std::ios::binary );
2898 f << "edited during resolution\n";
2899 }
2900
2901 BOOST_CHECK_EQUAL( static_cast<int>( common.CreateMergedCommit(
2902 headOid, theirsOid, { { conflicts[0].path, conflicts[0].oursFile } }, error ) ),
2903 static_cast<int>( MergeCommitResult::FailedCleanly ) );
2904
2905 {
2906 std::ofstream f( trackedFile.ToStdString(), std::ios::binary );
2907 f << "mine\n";
2908 }
2909
2910 // A checkout failure, here injected with git's own index lock, must leave the branch where
2911 // it was. Recording the merge first would make a later pull report up to date while the
2912 // files still hold the old content.
2913 wxString indexLock = repoPath() + wxFileName::GetPathSeparator() + wxT( ".git" ) + wxFileName::GetPathSeparator()
2914 + wxT( "index.lock" );
2915 {
2916 std::ofstream f( indexLock.ToStdString() );
2917 }
2918
2919 {
2920 wxString lockedMerged = tempBase() + wxFileName::GetPathSeparator() + wxT( "locked_merged.txt" );
2921 std::ofstream f( lockedMerged.ToStdString(), std::ios::binary );
2922 f << "merged\n";
2923 f.close();
2924
2925 // The lock also blocks the rollback, so the working files are left part way. The caller
2926 // keeps its recovery copies on this result.
2927 BOOST_CHECK_EQUAL( static_cast<int>( common.CreateMergedCommit(
2928 headOid, theirsOid, { { conflicts[0].path, lockedMerged } }, error ) ),
2929 static_cast<int>( MergeCommitResult::FailedPartially ) );
2930
2931 git_oid headNow;
2932 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headNow, repo, "HEAD" ), GIT_OK );
2933
2934 char headNowStr[GIT_OID_HEXSZ + 1] = { 0 };
2935 git_oid_tostr( headNowStr, sizeof( headNowStr ), &headNow );
2936 BOOST_CHECK_EQUAL( std::string( headNowStr ), headOid.ToStdString() );
2937 }
2938
2939 wxRemoveFile( indexLock );
2940
2941#ifndef __WINDOWS__
2942 // A failure after the checkout, injected here by making the branch ref unwritable, must
2943 // roll the working files back automatically. The operation required a clean tree, so the
2944 // rollback is lossless by construction. Directory permissions do not bind root.
2945 if( geteuid() != 0 )
2946 {
2947 // The ref update writes a lock file next to the ref and renames it into place, so the
2948 // way to make it fail is denying writes on the containing directory.
2949 wxString refsDir = repoPath() + wxFileName::GetPathSeparator() + wxT( ".git" ) + wxFileName::GetPathSeparator()
2950 + wxT( "refs" ) + wxFileName::GetPathSeparator() + wxT( "heads" );
2951
2952 BOOST_REQUIRE( wxFileName::DirExists( refsDir ) );
2953
2954 // Put the permissions back however this ends, or the fixture cannot remove its directory.
2955 struct WRITABLE_AGAIN
2956 {
2957 wxString dir;
2958 ~WRITABLE_AGAIN() { chmod( dir.fn_str(), 0755 ); }
2959 } restore{ refsDir };
2960
2961 chmod( refsDir.fn_str(), 0555 );
2962
2963 wxString refMerged = tempBase() + wxFileName::GetPathSeparator() + wxT( "ref_merged.txt" );
2964 {
2965 std::ofstream f( refMerged.ToStdString() );
2966 f << "merged\n";
2967 }
2968
2969 BOOST_CHECK_EQUAL( static_cast<int>( common.CreateMergedCommit( headOid, theirsOid,
2970 { { conflicts[0].path, refMerged } }, error ) ),
2971 static_cast<int>( MergeCommitResult::FailedCleanly ) );
2972
2973 // The branch did not move and the working file is back at the pre-merge content.
2974 git_oid headNow;
2975 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headNow, repo, "HEAD" ), GIT_OK );
2976
2977 char headNowStr[GIT_OID_HEXSZ + 1] = { 0 };
2978 git_oid_tostr( headNowStr, sizeof( headNowStr ), &headNow );
2979 BOOST_CHECK_EQUAL( std::string( headNowStr ), headOid.ToStdString() );
2980
2981 std::ifstream in( trackedFile.ToStdString(), std::ios::binary );
2982 std::string rolled( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
2983 BOOST_CHECK_EQUAL( rolled, "mine\n" );
2984 }
2985#endif
2986
2987 // The branch did not move, so the half-written file is an ordinary local modification. Put it
2988 // back the way a user cleaning up would, so the retry starts from a clean tree.
2989 {
2990 std::ofstream f( trackedFile.ToStdString(), std::ios::binary );
2991 f << "mine\n";
2992 }
2993
2994 // Resolve with fresh content and finish the merge.
2995 wxString mergedFile = tempBase() + wxFileName::GetPathSeparator() + wxT( "merged.txt" );
2996 {
2997 std::ofstream f( mergedFile.ToStdString(), std::ios::binary );
2998 f << "merged\n";
2999 }
3000
3001 BOOST_REQUIRE_MESSAGE( common.CreateMergedCommit( headOid, theirsOid, { { conflicts[0].path, mergedFile } }, error )
3003 "CreateMergedCommit failed: " + error.summary.ToStdString() );
3004
3005 // HEAD is now a merge commit of both sides, the working file carries the resolution, and no
3006 // merge state is left behind.
3007 git_oid newHead;
3008 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &newHead, repo, "HEAD" ), GIT_OK );
3009
3010 git_commit* mergeCommit = nullptr;
3011 BOOST_REQUIRE_EQUAL( git_commit_lookup( &mergeCommit, repo, &newHead ), GIT_OK );
3012 BOOST_CHECK_EQUAL( git_commit_parentcount( mergeCommit ), 2u );
3013
3014 // Merged against the pinned remote commit, not the one FETCH_HEAD moved to meanwhile.
3015 const git_oid* secondParent = git_commit_parent_id( mergeCommit, 1 );
3016 BOOST_REQUIRE( secondParent );
3017 BOOST_CHECK( git_oid_equal( secondParent, &remoteCommitOid ) );
3018 git_commit_free( mergeCommit );
3019
3020 BOOST_CHECK_EQUAL( readAll( repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" ) ), "merged\n" );
3021 BOOST_CHECK_EQUAL( git_repository_state( repo ), GIT_REPOSITORY_STATE_NONE );
3022
3023 git_repository_free( repo );
3024}
3025
3026
3027// The panel writes the .mine or .theirs recovery copy into the working tree before finishing
3028// the merge, so an untracked file must not count as a change made during resolution.
3029BOOST_AUTO_TEST_CASE( MergeConflictFinishesWithAnUntrackedFilePresent )
3030{
3031 BOOST_TEST_REQUIRE( ready() );
3032
3033 git_repository* repo = openRepo();
3034 BOOST_TEST_REQUIRE( repo );
3035
3036 git_reference* headRef = nullptr;
3037 BOOST_REQUIRE_EQUAL( git_repository_head( &headRef, repo ), GIT_OK );
3038 git_oid baseOid = *git_reference_target( headRef );
3039 git_reference_free( headRef );
3040
3041 createCommit( repo, wxT( "file.txt" ), wxT( "mine\n" ), wxT( "Local change" ) );
3042 git_oid remoteCommitOid = createDetachedCommit( repo, baseOid, wxT( "file.txt" ), "remote\n", "Remote change" );
3043 writeFetchHead( remoteCommitOid );
3044
3045 KIGIT_COMMON common( repo );
3046
3047 wxString stageDir = tempBase() + wxFileName::GetPathSeparator() + wxT( "stages" );
3048 wxString headOid, theirsOid, conflictsError;
3049 KIGIT_ERROR_MESSAGE error;
3050 std::vector<KIGIT_CONFLICT_SIDES> conflicts;
3051
3052 BOOST_REQUIRE_MESSAGE( common.GetMergeConflicts( stageDir, headOid, theirsOid, conflicts, conflictsError ),
3053 "GetMergeConflicts failed: " + conflictsError.ToStdString() );
3054 BOOST_REQUIRE_EQUAL( conflicts.size(), 1u );
3055
3056 // The recovery copy the panel leaves beside the file.
3057 {
3058 wxString copy = repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt.mine" );
3059 std::ofstream f( copy.ToStdString() );
3060 f << "mine\n";
3061 }
3062
3063 BOOST_CHECK_MESSAGE(
3064 common.CreateMergedCommit( headOid, theirsOid, { { conflicts[0].path, conflicts[0].theirsFile } }, error )
3066 "refused with an untracked file present: " + error.summary.ToStdString() );
3067
3068 git_repository_free( repo );
3069}
3070
3071
3072// Under core.autocrlf a hand-merged file written with CRLF must be committed with LF, as git add would
3073BOOST_AUTO_TEST_CASE( MergeConflictResolutionPassesCleanFilters )
3074{
3075 BOOST_TEST_REQUIRE( ready() );
3076
3077 git_repository* repo = openRepo();
3078 BOOST_TEST_REQUIRE( repo );
3079
3080 git_config* config = nullptr;
3081 BOOST_REQUIRE_EQUAL( git_repository_config( &config, repo ), GIT_OK );
3082 BOOST_REQUIRE_EQUAL( git_config_set_bool( config, "core.autocrlf", 1 ), GIT_OK );
3083 git_config_free( config );
3084
3085 git_reference* headRef = nullptr;
3086 BOOST_REQUIRE_EQUAL( git_repository_head( &headRef, repo ), GIT_OK );
3087 git_oid baseOid = *git_reference_target( headRef );
3088 git_reference_free( headRef );
3089
3090 createCommit( repo, wxT( "file.txt" ), wxT( "mine\n" ), wxT( "Local change" ) );
3091 git_oid remoteCommitOid = createDetachedCommit( repo, baseOid, wxT( "file.txt" ), "remote\n", "Remote change" );
3092 writeFetchHead( remoteCommitOid );
3093
3094 KIGIT_COMMON common( repo );
3095
3096 wxString stageDir = tempBase() + wxFileName::GetPathSeparator() + wxT( "stages" );
3097 wxString headOid, theirsOid, conflictsError;
3098 KIGIT_ERROR_MESSAGE error;
3099 std::vector<KIGIT_CONFLICT_SIDES> conflicts;
3100
3101 BOOST_REQUIRE_MESSAGE( common.GetMergeConflicts( stageDir, headOid, theirsOid, conflicts, conflictsError ),
3102 "GetMergeConflicts failed: " + conflictsError.ToStdString() );
3103 BOOST_REQUIRE_EQUAL( conflicts.size(), 1u );
3104
3105 wxString mergedFile = tempBase() + wxFileName::GetPathSeparator() + wxT( "merged.txt" );
3106 {
3107 std::ofstream f( mergedFile.ToStdString(), std::ios::binary );
3108 f << "mine\r\nremote\r\n";
3109 }
3110
3111 BOOST_REQUIRE_MESSAGE( common.CreateMergedCommit( headOid, theirsOid, { { conflicts[0].path, mergedFile } }, error )
3113 "CreateMergedCommit failed: " + error.summary.ToStdString() );
3114
3115 git_object* blob = nullptr;
3116 BOOST_REQUIRE_EQUAL( git_revparse_single( &blob, repo, "HEAD:file.txt" ), GIT_OK );
3117
3118 const git_blob* contents = reinterpret_cast<const git_blob*>( blob );
3119 BOOST_CHECK_EQUAL( std::string( static_cast<const char*>( git_blob_rawcontent( contents ) ),
3120 static_cast<size_t>( git_blob_rawsize( contents ) ) ),
3121 "mine\nremote\n" );
3122
3123 git_object_free( blob );
3124 git_repository_free( repo );
3125}
3126
3127
3128// A rename on the remote arrives as two conflict entries, the old name with no remote side and the
3129// new name with no base. Taking theirs on both must leave the content on the new name only.
3130BOOST_AUTO_TEST_CASE( MergeConflictRenameTakeTheirsLandsOnNewPath )
3131{
3132 BOOST_TEST_REQUIRE( ready() );
3133
3134 git_repository* repo = openRepo();
3135 BOOST_TEST_REQUIRE( repo );
3136
3137 wxString base;
3138
3139 for( int i = 1; i <= 12; ++i )
3140 base << wxString::Format( wxT( "line %d\n" ), i );
3141
3142 git_oid baseOid = createCommit( repo, wxT( "file.txt" ), base, wxT( "Base" ) );
3143
3144 wxString mine = base;
3145 mine.Replace( wxT( "line 6\n" ), wxT( "line 6 mine\n" ) );
3146 createCommit( repo, wxT( "file.txt" ), mine, wxT( "Local change" ) );
3147
3148 // Theirs: file.txt removed, renamed.txt added with the same text except line 6.
3149 wxString theirs = base;
3150 theirs.Replace( wxT( "line 6\n" ), wxT( "line 6 theirs\n" ) );
3151
3152 git_oid theirsOidRaw;
3153 {
3154 git_commit* baseCommit = nullptr;
3155 BOOST_REQUIRE_EQUAL( git_commit_lookup( &baseCommit, repo, &baseOid ), GIT_OK );
3156 git_tree* baseTree = nullptr;
3157 BOOST_REQUIRE_EQUAL( git_commit_tree( &baseTree, baseCommit ), GIT_OK );
3158
3159 git_treebuilder* tb = nullptr;
3160 BOOST_REQUIRE_EQUAL( git_treebuilder_new( &tb, repo, baseTree ), GIT_OK );
3161 BOOST_REQUIRE_EQUAL( git_treebuilder_remove( tb, "file.txt" ), GIT_OK );
3162
3163 std::string content = theirs.utf8_string();
3164 git_oid blob;
3165 BOOST_REQUIRE_EQUAL( git_blob_create_from_buffer( &blob, repo, content.data(), content.size() ), GIT_OK );
3166 BOOST_REQUIRE_EQUAL( git_treebuilder_insert( nullptr, tb, "renamed.txt", &blob, GIT_FILEMODE_BLOB ), GIT_OK );
3167
3168 git_oid treeOid;
3169 BOOST_REQUIRE_EQUAL( git_treebuilder_write( &treeOid, tb ), GIT_OK );
3170 git_tree* tree = nullptr;
3171 BOOST_REQUIRE_EQUAL( git_tree_lookup( &tree, repo, &treeOid ), GIT_OK );
3172
3173 git_signature* sig = nullptr;
3174 BOOST_REQUIRE_EQUAL( git_signature_now( &sig, "QA", "[email protected]" ), GIT_OK );
3175 const git_commit* parents[1] = { baseCommit };
3176 BOOST_REQUIRE_EQUAL( git_commit_create( &theirsOidRaw, repo, nullptr, sig, sig, nullptr, "Rename and edit",
3177 tree, 1, parents ),
3178 GIT_OK );
3179 git_signature_free( sig );
3180 git_tree_free( tree );
3181 git_treebuilder_free( tb );
3182 git_tree_free( baseTree );
3183 git_commit_free( baseCommit );
3184 }
3185
3186 writeFetchHead( theirsOidRaw );
3187
3188 KIGIT_COMMON common( repo );
3189 wxString stageDir = tempBase() + wxFileName::GetPathSeparator() + wxT( "stages" );
3190 wxString headOid, theirsOid, conflictsError;
3191 KIGIT_ERROR_MESSAGE error;
3192 std::vector<KIGIT_CONFLICT_SIDES> conflicts;
3193
3194 BOOST_REQUIRE_MESSAGE( common.GetMergeConflicts( stageDir, headOid, theirsOid, conflicts, conflictsError ),
3195 conflictsError );
3196
3197
3198 BOOST_REQUIRE_EQUAL( conflicts.size(), 2u );
3199
3200 std::vector<std::pair<wxString, wxString>> resolved;
3201
3202 for( const KIGIT_CONFLICT_SIDES& c : conflicts )
3203 resolved.emplace_back( c.path, c.hasTheirs ? c.theirsFile : wxString() );
3204
3205 BOOST_REQUIRE_MESSAGE( common.CreateMergedCommit( headOid, theirsOid, resolved, error )
3207 error.summary );
3208
3209 wxString workdir = wxString::FromUTF8( git_repository_workdir( repo ) );
3210 bool renamedExists = wxFileExists( workdir + wxT( "renamed.txt" ) );
3211 bool oldExists = wxFileExists( workdir + wxT( "file.txt" ) );
3212
3213 BOOST_CHECK_MESSAGE( renamedExists, "theirs' content must land on the renamed path" );
3214 BOOST_CHECK_MESSAGE( !oldExists, "the old path must not survive a take-theirs of a rename" );
3215
3216 git_repository_free( repo );
3217}
3218
3219
3220// Rebuilding from the parent would drop every file the amended commit held but the list omits.
3221BOOST_AUTO_TEST_CASE( Amend_KeepsFilesAlreadyInCommit )
3222{
3223 BOOST_TEST_REQUIRE( ready() );
3224
3225 git_repository* repo = openRepo();
3226 BOOST_TEST_REQUIRE( repo );
3227
3228 // The commit to amend carries second.txt, which the amend below does not mention.
3229 createCommit( repo, wxT( "second.txt" ), wxT( "two\n" ), wxT( "Add second" ) );
3230
3231 {
3232 wxString filePath = repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" );
3233 std::ofstream f( filePath.ToStdString() );
3234 f << "amended\n";
3235 }
3236
3237 GIT_COMMIT_HANDLER handler( repo );
3238 BOOST_REQUIRE( handler.PerformAmend( { wxT( "file.txt" ) }, wxT( "Amended" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL )
3240
3241 git_oid headOid;
3242 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
3243
3244 git_commit* head = nullptr;
3245 BOOST_REQUIRE_EQUAL( git_commit_lookup( &head, repo, &headOid ), GIT_OK );
3246
3247 git_tree* tree = nullptr;
3248 BOOST_REQUIRE_EQUAL( git_commit_tree( &tree, head ), GIT_OK );
3249
3250 BOOST_CHECK_MESSAGE( git_tree_entry_byname( tree, "second.txt" ) != nullptr,
3251 "a file already in the amended commit must survive an amend that does not list it" );
3252 BOOST_CHECK( git_tree_entry_byname( tree, "file.txt" ) != nullptr );
3253
3254 git_tree_free( tree );
3255 git_commit_free( head );
3256 git_repository_free( repo );
3257}
3258
3259
3260// A switch that would overwrite local changes must report a conflict and change nothing.
3261// A remote-tracking branch cannot be stood on. Checking one out could only attach HEAD to a
3262// local branch of the same name, which may be at another commit, so it is refused outright and
3263// nothing on disk is touched.
3264BOOST_AUTO_TEST_CASE( SwitchToBranch_RefusesARemoteBranch )
3265{
3266 BOOST_TEST_REQUIRE( ready() );
3267
3268 git_repository* repo = openRepo();
3269 BOOST_TEST_REQUIRE( repo );
3270
3271 git_oid localTip = createCommit( repo, wxT( "file.txt" ), wxT( "local\n" ), wxT( "local" ) );
3272
3273 git_commit* tipCommit = nullptr;
3274 BOOST_REQUIRE_EQUAL( git_commit_lookup( &tipCommit, repo, &localTip ), GIT_OK );
3275 KIGIT::GitCommitPtr tipPtr( tipCommit );
3276
3277 git_reference* localBranch = nullptr;
3278 BOOST_REQUIRE_EQUAL( git_branch_create( &localBranch, repo, "feature", tipCommit, 0 ), GIT_OK );
3279 git_reference_free( localBranch );
3280
3281 // origin/feature further along than the local branch of the same name, as a fetch leaves it.
3282 git_oid remoteTip = createDetachedCommit( repo, localTip, wxT( "file.txt" ), "remote\n", "remote" );
3283 git_reference* tracking = nullptr;
3284 BOOST_REQUIRE_EQUAL( git_reference_create( &tracking, repo, "refs/remotes/origin/feature", &remoteTip, 1, nullptr ),
3285 GIT_OK );
3286 git_reference_free( tracking );
3287
3288 KIGIT_COMMON common( repo );
3289 GIT_BRANCH_HANDLER handler( &common );
3290
3291 BOOST_CHECK( handler.SwitchToBranch( wxT( "origin/feature" ) ) == BranchResult::Error );
3292 const wxString error = handler.GetErrorString();
3293
3294 BOOST_CHECK_MESSAGE( error.Contains( wxS( "remote" ) ),
3295 "the refusal should say the branch is on the remote, got: " + error.ToStdString() );
3296
3297 // Nothing moved and nothing was written.
3298 git_oid headNow;
3299 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headNow, repo, "HEAD" ), GIT_OK );
3300 BOOST_CHECK( git_oid_equal( &headNow, &localTip ) );
3301
3302 std::ifstream f( ( repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" ) ).ToStdString() );
3303 std::string content( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
3304 BOOST_CHECK_EQUAL( content, "local\n" );
3305
3306 git_repository_free( repo );
3307}
3308
3309
3310BOOST_AUTO_TEST_CASE( SwitchToBranch_ReportsConflictOverLocalChanges )
3311{
3312 BOOST_TEST_REQUIRE( ready() );
3313
3314 git_repository* repo = openRepo();
3315 BOOST_TEST_REQUIRE( repo );
3316
3317 git_oid headOid;
3318 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
3319
3320 git_commit* headCommit = nullptr;
3321 BOOST_REQUIRE_EQUAL( git_commit_lookup( &headCommit, repo, &headOid ), GIT_OK );
3322
3323 git_reference* oldBranch = nullptr;
3324 BOOST_REQUIRE_EQUAL( git_branch_create( &oldBranch, repo, "old", headCommit, 0 ), GIT_OK );
3325 git_reference_free( oldBranch );
3326 git_commit_free( headCommit );
3327
3328 git_oid advancedOid = createCommit( repo, wxT( "file.txt" ), wxT( "master2\n" ), wxT( "Advance master" ) );
3329
3330 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3331
3332 {
3333 std::ofstream f( ( workDir + wxT( "file.txt" ) ).ToStdString(), std::ios::binary );
3334 f << "local edit\n";
3335 }
3336
3337 KIGIT_COMMON common( repo );
3338 GIT_BRANCH_HANDLER handler( &common );
3339
3340 BOOST_CHECK( handler.SwitchToBranch( wxT( "old" ) ) == BranchResult::Conflict );
3341
3342 git_oid afterOid;
3343 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &afterOid, repo, "HEAD" ), GIT_OK );
3344 BOOST_CHECK_EQUAL( git_oid_cmp( &afterOid, &advancedOid ), 0 );
3345
3346 std::ifstream in( ( workDir + wxT( "file.txt" ) ).ToStdString(), std::ios::binary );
3347 std::string content( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
3348 BOOST_CHECK_EQUAL( content, "local edit\n" );
3349
3350 git_repository_free( repo );
3351}
3352
3353
3354// A never-committed file the target branch carries must stop the switch too.
3355BOOST_AUTO_TEST_CASE( SwitchToBranch_ReportsConflictOverUntrackedCollision )
3356{
3357 BOOST_TEST_REQUIRE( ready() );
3358
3359 git_repository* repo = openRepo();
3360 BOOST_TEST_REQUIRE( repo );
3361
3362 git_oid headOid;
3363 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
3364
3365 git_commit* headCommit = nullptr;
3366 BOOST_REQUIRE_EQUAL( git_commit_lookup( &headCommit, repo, &headOid ), GIT_OK );
3367
3368 git_reference* plainBranch = nullptr;
3369 BOOST_REQUIRE_EQUAL( git_branch_create( &plainBranch, repo, "plain", headCommit, 0 ), GIT_OK );
3370 git_reference_free( plainBranch );
3371 git_commit_free( headCommit );
3372
3373 createCommit( repo, wxT( "extra.txt" ), wxT( "committed\n" ), wxT( "Add extra" ) );
3374
3375 KIGIT_COMMON common( repo );
3376 GIT_BRANCH_HANDLER handler( &common );
3377
3378 BOOST_REQUIRE( handler.SwitchToBranch( wxT( "plain" ) ) == BranchResult::Success );
3379
3380 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3381
3382 {
3383 std::ofstream f( ( workDir + wxT( "extra.txt" ) ).ToStdString(), std::ios::binary );
3384 f << "local\n";
3385 }
3386
3387 BOOST_CHECK( handler.SwitchToBranch( wxT( "master" ) ) == BranchResult::Conflict );
3388
3389 std::ifstream in( ( workDir + wxT( "extra.txt" ) ).ToStdString(), std::ios::binary );
3390 std::string content( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
3391 BOOST_CHECK_EQUAL( content, "local\n" );
3392
3393 git_repository_free( repo );
3394}
3395
3396
3397// A file deleted from the working tree is offered in the checklist, so committing it must
3398// record the deletion instead of failing to add the missing path.
3399BOOST_AUTO_TEST_CASE( Commit_RecordsDeletedFile )
3400{
3401 BOOST_TEST_REQUIRE( ready() );
3402
3403 git_repository* repo = openRepo();
3404 BOOST_TEST_REQUIRE( repo );
3405
3406 createCommit( repo, wxT( "doomed.txt" ), wxT( "doomed\n" ), wxT( "Add doomed" ) );
3407
3408 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3409 BOOST_TEST_REQUIRE( wxRemoveFile( workDir + wxT( "doomed.txt" ) ) );
3410
3411 GIT_COMMIT_HANDLER handler( repo );
3412 CommitResult result = handler.PerformCommit( { wxT( "doomed.txt" ) }, wxT( "Remove doomed" ), TEST_AUTHOR_NAME,
3414
3416
3417 git_oid headOid;
3418 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
3419
3420 git_commit* head = nullptr;
3421 BOOST_REQUIRE_EQUAL( git_commit_lookup( &head, repo, &headOid ), GIT_OK );
3422
3423 git_tree* tree = nullptr;
3424 BOOST_REQUIRE_EQUAL( git_commit_tree( &tree, head ), GIT_OK );
3425
3426 BOOST_CHECK( git_tree_entry_byname( tree, "doomed.txt" ) == nullptr );
3427 BOOST_CHECK( git_tree_entry_byname( tree, "file.txt" ) != nullptr );
3428
3429 git_tree_free( tree );
3430 git_commit_free( head );
3431 git_repository_free( repo );
3432}
3433
3434
3435// The selected entries must also advance to the committed content, or they linger afterwards as
3436// phantom staged changes.
3437BOOST_AUTO_TEST_CASE( Commit_PreservesIndexEntriesOfUnselectedFiles )
3438{
3439 BOOST_TEST_REQUIRE( ready() );
3440
3441 git_repository* repo = openRepo();
3442 BOOST_TEST_REQUIRE( repo );
3443
3444 createCommit( repo, wxT( "board.txt" ), wxT( "board v1\n" ), wxT( "Add board" ) );
3445 createCommit( repo, wxT( "doomed.txt" ), wxT( "doomed\n" ), wxT( "Add doomed" ) );
3446
3447 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3448
3449 auto writeAll = [&]( const wxString& aName, const std::string& aContent )
3450 {
3451 std::ofstream f( ( workDir + aName ).ToStdString(), std::ios::binary );
3452 f << aContent;
3453 };
3454
3455 auto readAll = [&]( const wxString& aName )
3456 {
3457 std::ifstream in( ( workDir + aName ).ToStdString(), std::ios::binary );
3458 return std::string( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
3459 };
3460
3461 // Staged content of a path, or a marker for "no entry staged".
3462 auto stagedContent = [&]( const char* aPath )
3463 {
3464 std::string result = "<none>";
3465 git_index* index = nullptr;
3466 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
3467 BOOST_REQUIRE_EQUAL( git_index_read( index, 1 ), GIT_OK );
3468
3469 if( const git_index_entry* entry = git_index_get_bypath( index, aPath, 0 ) )
3470 {
3471 git_blob* blob = nullptr;
3472 BOOST_REQUIRE_EQUAL( git_blob_lookup( &blob, repo, &entry->id ), GIT_OK );
3473 result.assign( static_cast<const char*>( git_blob_rawcontent( blob ) ), git_blob_rawsize( blob ) );
3474 git_blob_free( blob );
3475 }
3476
3477 git_index_free( index );
3478 return result;
3479 };
3480
3481 auto committedContent = [&]( const char* aPath )
3482 {
3483 std::string result = "<none>";
3484 git_oid headOid;
3485 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
3486
3487 git_commit* head = nullptr;
3488 BOOST_REQUIRE_EQUAL( git_commit_lookup( &head, repo, &headOid ), GIT_OK );
3489
3490 git_tree* tree = nullptr;
3491 BOOST_REQUIRE_EQUAL( git_commit_tree( &tree, head ), GIT_OK );
3492
3493 git_tree_entry* entry = nullptr;
3494
3495 if( git_tree_entry_bypath( &entry, tree, aPath ) == GIT_OK )
3496 {
3497 git_blob* blob = nullptr;
3498 BOOST_REQUIRE_EQUAL( git_blob_lookup( &blob, repo, git_tree_entry_id( entry ) ), GIT_OK );
3499 result.assign( static_cast<const char*>( git_blob_rawcontent( blob ) ), git_blob_rawsize( blob ) );
3500 git_blob_free( blob );
3501 git_tree_entry_free( entry );
3502 }
3503
3504 git_tree_free( tree );
3505 git_commit_free( head );
3506 return result;
3507 };
3508
3509 // Three kinds of staging the user did outside KiCad and did not select: a modification, a
3510 // brand new file, and a deletion.
3511 writeAll( wxT( "notes.txt" ), "staged A\n" );
3512 writeAll( wxT( "board.txt" ), "board staged\n" );
3513
3514 git_index* index = nullptr;
3515 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
3516 BOOST_REQUIRE_EQUAL( git_index_add_bypath( index, "notes.txt" ), GIT_OK );
3517 BOOST_REQUIRE_EQUAL( git_index_add_bypath( index, "board.txt" ), GIT_OK );
3518 BOOST_REQUIRE_EQUAL( git_index_remove_bypath( index, "doomed.txt" ), GIT_OK );
3519 BOOST_REQUIRE_EQUAL( git_index_write( index ), GIT_OK );
3520 git_index_free( index );
3521
3522 // The staged version and the working version differ, so a lost index entry cannot be
3523 // recovered from the working file.
3524 writeAll( wxT( "notes.txt" ), "working B\n" );
3525 writeAll( wxT( "board.txt" ), "board working\n" );
3526
3527 // The selected file is a fourth path, untouched by any of the staging above.
3528 writeAll( wxT( "file.txt" ), "selected\n" );
3529
3530 GIT_COMMIT_HANDLER handler( repo );
3532 handler.PerformCommit( { wxT( "file.txt" ) }, wxT( "Only file.txt" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3534
3535 // The commit holds HEAD plus the selected file only.
3536 BOOST_CHECK_EQUAL( committedContent( "file.txt" ), "selected\n" );
3537 BOOST_CHECK_EQUAL( committedContent( "board.txt" ), "board v1\n" );
3538 BOOST_CHECK_EQUAL( committedContent( "notes.txt" ), "<none>" );
3539 BOOST_CHECK_EQUAL( committedContent( "doomed.txt" ), "doomed\n" );
3540
3541 // Every unselected staged decision survives, and the working files are untouched.
3542 BOOST_CHECK_EQUAL( stagedContent( "notes.txt" ), "staged A\n" );
3543 BOOST_CHECK_EQUAL( stagedContent( "board.txt" ), "board staged\n" );
3544 BOOST_CHECK_EQUAL( stagedContent( "doomed.txt" ), "<none>" );
3545 BOOST_CHECK_EQUAL( readAll( wxT( "notes.txt" ) ), "working B\n" );
3546 BOOST_CHECK_EQUAL( readAll( wxT( "board.txt" ) ), "board working\n" );
3547
3548 // The selected path matches what was committed, so it is not left looking staged.
3549 BOOST_CHECK_EQUAL( stagedContent( "file.txt" ), "selected\n" );
3550
3551 // A selected deletion behaves the same way, and still leaves the others alone.
3552 BOOST_TEST_REQUIRE( wxRemoveFile( workDir + wxT( "file.txt" ) ) );
3553
3554 result = handler.PerformCommit( { wxT( "file.txt" ) }, wxT( "Remove file.txt" ), TEST_AUTHOR_NAME,
3557
3558 BOOST_CHECK_EQUAL( committedContent( "file.txt" ), "<none>" );
3559 BOOST_CHECK_EQUAL( stagedContent( "file.txt" ), "<none>" );
3560 BOOST_CHECK_EQUAL( stagedContent( "notes.txt" ), "staged A\n" );
3561 BOOST_CHECK_EQUAL( stagedContent( "board.txt" ), "board staged\n" );
3562 BOOST_CHECK_EQUAL( stagedContent( "doomed.txt" ), "<none>" );
3563
3564 // A message-only amend keeps the tree and must not disturb the staged entries either.
3565 result = handler.PerformAmend( {}, wxT( "Reworded" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3567
3568 BOOST_CHECK_EQUAL( stagedContent( "notes.txt" ), "staged A\n" );
3569 BOOST_CHECK_EQUAL( stagedContent( "board.txt" ), "board staged\n" );
3570 BOOST_CHECK_EQUAL( stagedContent( "doomed.txt" ), "<none>" );
3571 BOOST_CHECK_EQUAL( committedContent( "board.txt" ), "board v1\n" );
3572
3573 // A failed commit must not cost the user any staged content either.
3574 writeAll( wxT( "late.txt" ), "late\n" );
3575 BOOST_CHECK( handler.PerformCommit( { wxT( "late.txt" ) }, wxT( "Bad author" ), wxEmptyString, wxEmptyString )
3577
3578 BOOST_CHECK_EQUAL( stagedContent( "notes.txt" ), "staged A\n" );
3579 BOOST_CHECK_EQUAL( stagedContent( "board.txt" ), "board staged\n" );
3580 BOOST_CHECK_EQUAL( stagedContent( "doomed.txt" ), "<none>" );
3581
3582 git_repository_free( repo );
3583}
3584
3585
3586// libgit2 wants UTF-8 paths. A locale conversion would mangle or reject non-ASCII names, so
3587// check that they survive an add, a modify, an amend and a delete with byte-exact identity.
3588BOOST_AUTO_TEST_CASE( Commit_HandlesNonAsciiPaths )
3589{
3590 BOOST_TEST_REQUIRE( ready() );
3591
3592 git_repository* repo = openRepo();
3593 BOOST_TEST_REQUIRE( repo );
3594
3595 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3596
3597 const wxString umlaut = wxString::FromUTF8( "Gr\xc3\xb6\xc3\x9f"
3598 "e.kicad_sch" );
3599 const wxString cyrillic = wxString::FromUTF8( "\xd0\xbf\xd0\xbb\xd0\xb0\xd1\x82\xd0\xb0.txt" );
3600 const std::string umlautUtf8 = umlaut.utf8_string();
3601 const std::string cyrillicUtf8 = cyrillic.utf8_string();
3602
3603 auto writeAll = [&]( const wxString& aName, const std::string& aContent )
3604 {
3605 KI_TEST::WriteGitFile( repoPath(), aName, aContent );
3606 };
3607
3608 auto inHeadTree = [&]( const std::string& aPath )
3609 {
3610 git_oid headOid;
3611 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
3612
3613 git_commit* head = nullptr;
3614 BOOST_REQUIRE_EQUAL( git_commit_lookup( &head, repo, &headOid ), GIT_OK );
3615
3616 git_tree* tree = nullptr;
3617 BOOST_REQUIRE_EQUAL( git_commit_tree( &tree, head ), GIT_OK );
3618
3619 git_tree_entry* entry = nullptr;
3620 bool found = git_tree_entry_bypath( &entry, tree, aPath.c_str() ) == GIT_OK;
3621
3622 if( found )
3623 git_tree_entry_free( entry );
3624
3625 git_tree_free( tree );
3626 git_commit_free( head );
3627 return found;
3628 };
3629
3630 writeAll( umlaut, "one\n" );
3631 writeAll( cyrillic, "one\n" );
3632
3633 GIT_COMMIT_HANDLER handler( repo );
3635 handler.PerformCommit( { umlaut, cyrillic }, wxT( "Add" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3637
3638 // The recorded path must be the same bytes as the file on disk, not a locale transcoding.
3639 BOOST_CHECK( inHeadTree( umlautUtf8 ) );
3640 BOOST_CHECK( inHeadTree( cyrillicUtf8 ) );
3641
3642 writeAll( umlaut, "two\n" );
3643 result = handler.PerformCommit( { umlaut }, wxT( "Modify" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3645 BOOST_CHECK( inHeadTree( umlautUtf8 ) );
3646
3647 writeAll( umlaut, "three\n" );
3648 result = handler.PerformAmend( { umlaut }, wxT( "Amended" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3650 BOOST_CHECK( inHeadTree( umlautUtf8 ) );
3651 BOOST_CHECK( inHeadTree( cyrillicUtf8 ) );
3652
3653 BOOST_TEST_REQUIRE( wxRemoveFile( workDir + umlaut ) );
3654 result = handler.PerformCommit( { umlaut }, wxT( "Delete" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3656
3657 BOOST_CHECK( !inHeadTree( umlautUtf8 ) );
3658 BOOST_CHECK( inHeadTree( cyrillicUtf8 ) );
3659
3660 git_repository_free( repo );
3661}
3662
3663
3664// While another process holds .git/index.lock, KiCad's own index write must fail cleanly and
3665// leave that process's staging on disk untouched.
3666BOOST_AUTO_TEST_CASE( Commit_DoesNotDamageIndexWhileAnotherProcessHoldsTheLock )
3667{
3668 BOOST_TEST_REQUIRE( ready() );
3669
3670 git_repository* repo = openRepo();
3671 BOOST_TEST_REQUIRE( repo );
3672
3673 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3674
3675 {
3676 std::ofstream f( ( workDir + wxT( "notes.txt" ) ).ToStdString(), std::ios::binary );
3677 f << "staged elsewhere\n";
3678 }
3679
3680 git_repository* foreignRepo = nullptr;
3681 BOOST_REQUIRE_EQUAL( git_repository_open( &foreignRepo, repoPath().ToUTF8().data() ), GIT_OK );
3682
3683 git_index* foreign = nullptr;
3684 BOOST_REQUIRE_EQUAL( git_repository_index( &foreign, foreignRepo ), GIT_OK );
3685 BOOST_REQUIRE_EQUAL( git_index_add_bypath( foreign, "notes.txt" ), GIT_OK );
3686 BOOST_REQUIRE_EQUAL( git_index_write( foreign ), GIT_OK );
3687 git_index_free( foreign );
3688 git_repository_free( foreignRepo );
3689
3690 {
3691 std::ofstream f( ( workDir + wxT( "file.txt" ) ).ToStdString(), std::ios::binary );
3692 f << "selected\n";
3693 }
3694
3695 // Stand in for another git process that is part way through its own index write.
3696 wxString indexLock = repoPath() + wxFileName::GetPathSeparator() + wxT( ".git" ) + wxFileName::GetPathSeparator()
3697 + wxT( "index.lock" );
3698 {
3699 std::ofstream f( indexLock.ToStdString() );
3700 f << "held\n";
3701 }
3702
3703 GIT_COMMIT_HANDLER handler( repo );
3705 handler.PerformCommit( { wxT( "file.txt" ) }, wxT( "Only file.txt" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3706
3707 // The commit itself does not need the index lock, so it exists. Only the staged file list
3708 // could not be rewritten, which is a different outcome from a failed commit.
3710 BOOST_CHECK( !handler.GetErrorString().IsEmpty() );
3711
3712 BOOST_TEST_REQUIRE( wxRemoveFile( indexLock ) );
3713
3714 git_oid committed;
3715 BOOST_CHECK_MESSAGE( git_reference_name_to_id( &committed, repo, "HEAD" ) == GIT_OK,
3716 "the commit must exist even though the index could not be rewritten" );
3717
3718 // The other process's staging is still exactly as it left it.
3719 git_index* after = nullptr;
3720 BOOST_REQUIRE_EQUAL( git_repository_index( &after, repo ), GIT_OK );
3721 BOOST_REQUIRE_EQUAL( git_index_read( after, 1 ), GIT_OK );
3722
3723 const git_index_entry* notes = git_index_get_bypath( after, "notes.txt", 0 );
3724 BOOST_REQUIRE_MESSAGE( notes, "the locked-out write damaged another process's staging" );
3725
3726 git_blob* blob = nullptr;
3727 BOOST_REQUIRE_EQUAL( git_blob_lookup( &blob, repo, &notes->id ), GIT_OK );
3728 std::string content( static_cast<const char*>( git_blob_rawcontent( blob ) ), git_blob_rawsize( blob ) );
3729 BOOST_CHECK_EQUAL( content, "staged elsewhere\n" );
3730
3731 git_blob_free( blob );
3732 git_index_free( after );
3733 git_repository_free( repo );
3734}
3735
3736
3737// Amend needs the same protection as Commit. Staging done outside KiCad must survive it.
3738BOOST_AUTO_TEST_CASE( Amend_KeepsStagingWrittenByAnotherProcess )
3739{
3740 BOOST_TEST_REQUIRE( ready() );
3741
3742 git_repository* repo = openRepo();
3743 BOOST_TEST_REQUIRE( repo );
3744
3745 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3746
3747 git_index* cached = nullptr;
3748 BOOST_REQUIRE_EQUAL( git_repository_index( &cached, repo ), GIT_OK );
3749 KIGIT::GitIndexPtr cachedPtr( cached );
3750
3751 {
3752 std::ofstream f( ( workDir + wxT( "notes.txt" ) ).ToStdString(), std::ios::binary );
3753 f << "staged elsewhere\n";
3754 }
3755
3756 // A second handle on the same directory stands in for a terminal git process.
3757 git_repository* foreignRepo = nullptr;
3758 BOOST_REQUIRE_EQUAL( git_repository_open( &foreignRepo, repoPath().ToUTF8().data() ), GIT_OK );
3759
3760 git_index* foreign = nullptr;
3761 BOOST_REQUIRE_EQUAL( git_repository_index( &foreign, foreignRepo ), GIT_OK );
3762 BOOST_REQUIRE_EQUAL( git_index_add_bypath( foreign, "notes.txt" ), GIT_OK );
3763 BOOST_REQUIRE_EQUAL( git_index_write( foreign ), GIT_OK );
3764
3765 const git_index_entry* stagedBefore = git_index_get_bypath( foreign, "notes.txt", 0 );
3766 BOOST_REQUIRE( stagedBefore );
3767 git_oid stagedBlob = stagedBefore->id;
3768
3769 git_index_free( foreign );
3770 git_repository_free( foreignRepo );
3771
3772 {
3773 std::ofstream f( ( workDir + wxT( "file.txt" ) ).ToStdString(), std::ios::binary );
3774 f << "amended\n";
3775 }
3776
3777 GIT_COMMIT_HANDLER handler( repo );
3778 CommitResult result = handler.PerformAmend( { wxT( "file.txt" ) }, wxT( "Amended message" ), TEST_AUTHOR_NAME,
3781
3782 git_repository_free( repo );
3783
3784 // Reopen so nothing is answered from a cached index.
3785 git_repository* fresh = nullptr;
3786 BOOST_REQUIRE_EQUAL( git_repository_open( &fresh, repoPath().ToUTF8().data() ), GIT_OK );
3787
3788 git_index* after = nullptr;
3789 BOOST_REQUIRE_EQUAL( git_repository_index( &after, fresh ), GIT_OK );
3790
3791 const git_index_entry* notes = git_index_get_bypath( after, "notes.txt", 0 );
3792 BOOST_REQUIRE_MESSAGE( notes, "the externally staged file must still be staged after an amend" );
3793 BOOST_CHECK_MESSAGE( git_oid_equal( &notes->id, &stagedBlob ),
3794 "the externally staged blob must be the exact one the other process wrote" );
3795
3796 // The amend must not have pulled notes.txt into the commit.
3797 git_oid headOid;
3798 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, fresh, "HEAD" ), GIT_OK );
3799
3800 git_commit* headCommit = nullptr;
3801 BOOST_REQUIRE_EQUAL( git_commit_lookup( &headCommit, fresh, &headOid ), GIT_OK );
3802
3803 git_tree* headTree = nullptr;
3804 BOOST_REQUIRE_EQUAL( git_commit_tree( &headTree, headCommit ), GIT_OK );
3805
3806 git_tree_entry* leaked = nullptr;
3807 BOOST_CHECK_MESSAGE( git_tree_entry_bypath( &leaked, headTree, "notes.txt" ) != GIT_OK,
3808 "an unselected staged file must not ride into the amended commit" );
3809 git_tree_entry_free( leaked );
3810
3811 git_tree_free( headTree );
3812 git_commit_free( headCommit );
3813 git_index_free( after );
3814 git_repository_free( fresh );
3815}
3816
3817
3818BOOST_AUTO_TEST_CASE( Commit_KeepsStagingWrittenByAnotherProcess )
3819{
3820 BOOST_TEST_REQUIRE( ready() );
3821
3822 git_repository* repo = openRepo();
3823 BOOST_TEST_REQUIRE( repo );
3824
3825 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3826
3827 // Make the repository handle cache an index that knows nothing about the staging below.
3828 git_index* cached = nullptr;
3829 BOOST_REQUIRE_EQUAL( git_repository_index( &cached, repo ), GIT_OK );
3830 KIGIT::GitIndexPtr cachedPtr( cached );
3831 BOOST_REQUIRE_EQUAL( git_index_entrycount( cached ), 1 );
3832
3833 {
3834 std::ofstream f( ( workDir + wxT( "notes.txt" ) ).ToStdString(), std::ios::binary );
3835 f << "staged elsewhere\n";
3836 }
3837
3838 // A second repository handle on the same directory stands in for the terminal.
3839 git_repository* foreignRepo = nullptr;
3840 BOOST_REQUIRE_EQUAL( git_repository_open( &foreignRepo, repoPath().ToUTF8().data() ), GIT_OK );
3841
3842 git_index* foreign = nullptr;
3843 BOOST_REQUIRE_EQUAL( git_repository_index( &foreign, foreignRepo ), GIT_OK );
3844 BOOST_REQUIRE_EQUAL( git_index_add_bypath( foreign, "notes.txt" ), GIT_OK );
3845 BOOST_REQUIRE_EQUAL( git_index_write( foreign ), GIT_OK );
3846 git_index_free( foreign );
3847 git_repository_free( foreignRepo );
3848
3849 {
3850 std::ofstream f( ( workDir + wxT( "file.txt" ) ).ToStdString(), std::ios::binary );
3851 f << "selected\n";
3852 }
3853
3854 GIT_COMMIT_HANDLER handler( repo );
3856 handler.PerformCommit( { wxT( "file.txt" ) }, wxT( "Only file.txt" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3858
3859 git_index* after = nullptr;
3860 BOOST_REQUIRE_EQUAL( git_repository_index( &after, repo ), GIT_OK );
3861 BOOST_REQUIRE_EQUAL( git_index_read( after, 1 ), GIT_OK );
3862
3863 const git_index_entry* notes = git_index_get_bypath( after, "notes.txt", 0 );
3864 BOOST_REQUIRE_MESSAGE( notes, "staging written by another process was lost" );
3865
3866 git_blob* blob = nullptr;
3867 BOOST_REQUIRE_EQUAL( git_blob_lookup( &blob, repo, &notes->id ), GIT_OK );
3868 std::string content( static_cast<const char*>( git_blob_rawcontent( blob ) ), git_blob_rawsize( blob ) );
3869 BOOST_CHECK_EQUAL( content, "staged elsewhere\n" );
3870
3871 git_blob_free( blob );
3872 git_index_free( after );
3873 git_repository_free( repo );
3874}
3875
3876
3877// The panel promises to commit exactly the checked files. Content staged outside KiCad for
3878// an unchecked file must not ride into the commit.
3879BOOST_AUTO_TEST_CASE( Commit_IgnoresContentStagedElsewhere )
3880{
3881 BOOST_TEST_REQUIRE( ready() );
3882
3883 git_repository* repo = openRepo();
3884 BOOST_TEST_REQUIRE( repo );
3885
3886 createCommit( repo, wxT( "sneaky.txt" ), wxT( "clean\n" ), wxT( "Add sneaky" ) );
3887
3888 wxString workDir = wxString::FromUTF8( git_repository_workdir( repo ) );
3889
3890 // Stage a change to sneaky.txt the way a command line git add would, then change the
3891 // checked file too.
3892 {
3893 std::ofstream f( ( workDir + wxT( "sneaky.txt" ) ).ToStdString(), std::ios::binary );
3894 f << "staged elsewhere\n";
3895 }
3896
3897 git_index* index = nullptr;
3898 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
3899 BOOST_REQUIRE_EQUAL( git_index_add_bypath( index, "sneaky.txt" ), GIT_OK );
3900 BOOST_REQUIRE_EQUAL( git_index_write( index ), GIT_OK );
3901 git_index_free( index );
3902
3903 {
3904 std::ofstream f( ( workDir + wxT( "file.txt" ) ).ToStdString(), std::ios::binary );
3905 f << "wanted\n";
3906 }
3907
3908 GIT_COMMIT_HANDLER handler( repo );
3910 handler.PerformCommit( { wxT( "file.txt" ) }, wxT( "Only file.txt" ), TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL );
3911
3913
3914 git_oid headOid;
3915 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &headOid, repo, "HEAD" ), GIT_OK );
3916
3917 git_commit* head = nullptr;
3918 BOOST_REQUIRE_EQUAL( git_commit_lookup( &head, repo, &headOid ), GIT_OK );
3919
3920 git_tree* tree = nullptr;
3921 BOOST_REQUIRE_EQUAL( git_commit_tree( &tree, head ), GIT_OK );
3922
3923 const git_tree_entry* sneaky = git_tree_entry_byname( tree, "sneaky.txt" );
3924 BOOST_REQUIRE( sneaky );
3925
3926 git_blob* blob = nullptr;
3927 BOOST_REQUIRE_EQUAL( git_blob_lookup( &blob, repo, git_tree_entry_id( sneaky ) ), GIT_OK );
3928
3929 std::string sneakyContent( static_cast<const char*>( git_blob_rawcontent( blob ) ), git_blob_rawsize( blob ) );
3930
3931 BOOST_CHECK_EQUAL( sneakyContent, "clean\n" );
3932
3933 git_blob_free( blob );
3934 git_tree_free( tree );
3935 git_commit_free( head );
3936 git_repository_free( repo );
3937}
3938
3939
3940// The old version arrives as a new commit on top of the head, and never over uncommitted work.
3941BOOST_AUTO_TEST_CASE( RestoreVersionRoundTrip )
3942{
3943 BOOST_TEST_REQUIRE( ready() );
3944
3945 git_repository* repo = openRepo();
3946 BOOST_TEST_REQUIRE( repo );
3947
3948 git_oid secondOid = createCommit( repo, wxT( "file.txt" ), wxT( "second\n" ), wxT( "Second version" ) );
3949
3950 git_object* firstObj = nullptr;
3951 BOOST_REQUIRE_EQUAL( git_revparse_single( &firstObj, repo, "HEAD~1" ), GIT_OK );
3952 git_oid firstOid = *git_object_id( firstObj );
3953 git_object_free( firstObj );
3954
3955 char firstHash[GIT_OID_HEXSZ + 1] = { 0 };
3956 git_oid_tostr( firstHash, sizeof( firstHash ), &firstOid );
3957
3958 KIGIT_COMMON common( repo, repoPath() );
3959 KIGIT_ERROR_MESSAGE error;
3960
3961 // Refuses over uncommitted changes.
3962 wxString trackedFile = repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" );
3963 {
3964 std::ofstream f( trackedFile.ToStdString(), std::ios::binary );
3965 f << "uncommitted\n";
3966 }
3967
3968 BOOST_CHECK( common.RestoreVersion( wxString::FromUTF8( firstHash ), error ) == RestoreResult::Dirty );
3969
3970 {
3971 std::ofstream f( trackedFile.ToStdString(), std::ios::binary );
3972 f << "second\n";
3973 }
3974
3975 // Restores as a new commit whose parent is the current head.
3976 BOOST_REQUIRE_MESSAGE( common.RestoreVersion( wxString::FromUTF8( firstHash ), error ) == RestoreResult::Restored,
3977 "RestoreVersion failed: " + error.summary.ToStdString() );
3978
3979 git_oid newHead;
3980 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &newHead, repo, "HEAD" ), GIT_OK );
3981
3982 git_commit* restoreCommit = nullptr;
3983 BOOST_REQUIRE_EQUAL( git_commit_lookup( &restoreCommit, repo, &newHead ), GIT_OK );
3984 BOOST_CHECK_EQUAL( git_commit_parentcount( restoreCommit ), 1u );
3985 BOOST_CHECK( git_oid_equal( git_commit_parent_id( restoreCommit, 0 ), &secondOid ) );
3986 git_commit_free( restoreCommit );
3987
3988 std::ifstream in( trackedFile.ToStdString() );
3989 std::string content( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
3990 BOOST_CHECK_EQUAL( content, "initial\n" );
3991
3992 // Restoring the same version again is a no-op.
3993 BOOST_CHECK( common.RestoreVersion( wxString::FromUTF8( firstHash ), error ) == RestoreResult::AlreadyCurrent );
3994
3995 git_repository_free( repo );
3996}
3997
3998
3999// Restoring one project in a shared repository must leave the siblings current.
4000BOOST_AUTO_TEST_CASE( RestoreScopesToProjectDirectory )
4001{
4002 BOOST_TEST_REQUIRE( ready() );
4003
4004 KIGIT::GitRepositoryPtr repo( openRepo() );
4005 BOOST_REQUIRE( repo );
4006
4007 git_oid rootOid;
4008 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &rootOid, repo.get(), "HEAD" ), GIT_OK );
4009 createCommit( repo.get(), "projects/board/f.txt", "a1\n", "A v1" );
4010 git_oid bothV1 = createCommit( repo.get(), "projects/board2/g.txt", "b1\n", "B v1" );
4011
4012 createCommit( repo.get(), "projects/board/f.txt", "a2\n", "A v2" );
4013 createCommit( repo.get(), "projects/board2/g.txt", "b2\n", "B v2" );
4014
4015 char v1Hash[GIT_OID_HEXSZ + 1] = { 0 };
4016 git_oid_tostr( v1Hash, sizeof( v1Hash ), &bothV1 );
4017
4018 const wxString projectPath = repoPath() + wxS( "/projects/board" );
4019 KIGIT_COMMON common( repo.get(), projectPath );
4020 KIGIT_ERROR_MESSAGE error;
4021
4022 BOOST_REQUIRE_MESSAGE( common.RestoreVersion( wxString::FromUTF8( v1Hash ), error ) == RestoreResult::Restored,
4023 "RestoreVersion failed: " + error.summary.ToStdString() );
4024
4025 auto readAll = []( const wxString& aPath )
4026 {
4027 std::ifstream in( aPath.ToStdString(), std::ios::binary );
4028 return std::string( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
4029 };
4030
4031 // The restored project went back, the sibling stayed current.
4032 BOOST_CHECK_EQUAL( readAll( repoPath() + wxS( "/projects/board/f.txt" ) ), "a1\n" );
4033 BOOST_CHECK_EQUAL( readAll( repoPath() + wxS( "/projects/board2/g.txt" ) ), "b2\n" );
4034 BOOST_CHECK_EQUAL( readAll( repoPath() + wxS( "/file.txt" ) ), "initial\n" );
4035
4036 // A version from before the project's folder existed is refused, not emptied.
4037 char rootHash[GIT_OID_HEXSZ + 1] = { 0 };
4038 git_oid_tostr( rootHash, sizeof( rootHash ), &rootOid );
4039
4040 BOOST_CHECK( common.RestoreVersion( wxString::FromUTF8( rootHash ), error ) == RestoreResult::Error );
4041 BOOST_CHECK_EQUAL( readAll( repoPath() + wxS( "/projects/board/f.txt" ) ), "a1\n" );
4042
4043#ifndef __WINDOWS__
4044 // A symlink to the project must restore the same folder.
4045 const wxString projectLink = TempPath() + wxS( "/project-link" );
4046 BOOST_REQUIRE_EQUAL( symlink( projectPath.utf8_str(), projectLink.utf8_str() ), 0 );
4047 createCommit( repo.get(), "projects/board/f.txt", "a3\n", "A v3" );
4048
4049 KIGIT_COMMON linkedProject( repo.get(), projectLink );
4050 BOOST_REQUIRE_MESSAGE( linkedProject.RestoreVersion( wxString::FromUTF8( v1Hash ), error )
4052 "RestoreVersion failed: " + error.summary.ToStdString() );
4053 BOOST_CHECK_EQUAL( readAll( repoPath() + wxS( "/projects/board/f.txt" ) ), "a1\n" );
4054 BOOST_CHECK_EQUAL( readAll( repoPath() + wxS( "/projects/board2/g.txt" ) ), "b2\n" );
4055#endif
4056}
4057
4058
4059BOOST_AUTO_TEST_CASE( RestoreRefusesUnknownOrOutsideProject )
4060{
4061 BOOST_TEST_REQUIRE( ready() );
4062
4063 KIGIT::GitRepositoryPtr repo( openRepo() );
4064 BOOST_REQUIRE( repo );
4065
4066 git_oid firstOid;
4067 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &firstOid, repo.get(), "HEAD" ), GIT_OK );
4068 git_oid currentOid = createCommit( repo.get(), "file.txt", "second\n", "Second version" );
4069
4070 char firstHash[GIT_OID_HEXSZ + 1] = { 0 };
4071 git_oid_tostr( firstHash, sizeof( firstHash ), &firstOid );
4072
4073 const wxString outsidePath = repoPath() + wxS( "2" );
4074 BOOST_REQUIRE( wxFileName::Mkdir( outsidePath ) );
4075 const std::vector<wxString> projectPaths = { wxEmptyString, TempPath(), outsidePath };
4076
4077 for( const wxString& projectPath : projectPaths )
4078 {
4079 KIGIT_COMMON common( repo.get(), projectPath );
4080 KIGIT_ERROR_MESSAGE error;
4081
4082 BOOST_CHECK( common.RestoreVersion( wxString::FromUTF8( firstHash ), error ) == RestoreResult::Error );
4083 BOOST_CHECK( !error.details.IsEmpty() );
4084
4085 git_oid afterOid;
4086 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &afterOid, repo.get(), "HEAD" ), GIT_OK );
4087 BOOST_CHECK( git_oid_equal( &currentOid, &afterOid ) );
4088
4089 unsigned int status = 0;
4090 BOOST_REQUIRE_EQUAL( git_status_file( &status, repo.get(), "file.txt" ), GIT_OK );
4091 BOOST_CHECK_EQUAL( status, GIT_STATUS_CURRENT );
4092
4093 wxString contents;
4094 wxFile file( repoPath() + wxS( "/file.txt" ) );
4095 BOOST_REQUIRE( file.IsOpened() );
4096 BOOST_REQUIRE( file.ReadAll( &contents ) );
4097 BOOST_CHECK_EQUAL( contents.ToStdString(), "second\n" );
4098 }
4099}
4100
4101
4102// The colliding content was never committed, so nothing could bring it back.
4103BOOST_AUTO_TEST_CASE( RestoreRefusesUntrackedCollision )
4104{
4105 BOOST_TEST_REQUIRE( ready() );
4106
4107 git_repository* repo = openRepo();
4108 BOOST_TEST_REQUIRE( repo );
4109
4110 // A version that carries notes.txt, then a commit deleting it.
4111 git_oid withNotesOid = createCommit( repo, wxT( "notes.txt" ), wxT( "keep\n" ), wxT( "Add notes" ) );
4112
4113 {
4114 git_index* index = nullptr;
4115 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
4116 BOOST_REQUIRE_EQUAL( git_index_remove_bypath( index, "notes.txt" ), GIT_OK );
4117 git_index_write( index );
4118
4119 git_oid treeOid;
4120 BOOST_REQUIRE_EQUAL( git_index_write_tree( &treeOid, index ), GIT_OK );
4121 git_index_free( index );
4122
4123 git_tree* tree = nullptr;
4124 BOOST_REQUIRE_EQUAL( git_tree_lookup( &tree, repo, &treeOid ), GIT_OK );
4125
4126 git_commit* parent = nullptr;
4127 BOOST_REQUIRE_EQUAL( git_commit_lookup( &parent, repo, &withNotesOid ), GIT_OK );
4128
4129 git_signature* sig = nullptr;
4130 BOOST_REQUIRE_EQUAL( git_signature_now( &sig, TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL ), GIT_OK );
4131
4132 const git_commit* parents[1] = { parent };
4133 git_oid deleteOid;
4135 git_commit_create( &deleteOid, repo, "HEAD", sig, sig, nullptr, "Delete notes", tree, 1, parents ),
4136 GIT_OK );
4137
4138 git_signature_free( sig );
4139 git_commit_free( parent );
4140 git_tree_free( tree );
4141 wxRemoveFile( repoPath() + wxFileName::GetPathSeparator() + wxT( "notes.txt" ) );
4142 }
4143
4144 char withNotesHash[GIT_OID_HEXSZ + 1] = { 0 };
4145 git_oid_tostr( withNotesHash, sizeof( withNotesHash ), &withNotesOid );
4146
4147 KIGIT_COMMON common( repo, repoPath() );
4148 KIGIT_ERROR_MESSAGE error;
4149
4150 // A new, never committed notes.txt collides with the version being restored.
4151 wxString notesFile = repoPath() + wxFileName::GetPathSeparator() + wxT( "notes.txt" );
4152 {
4153 std::ofstream f( notesFile.ToStdString(), std::ios::binary );
4154 f << "precious\n";
4155 }
4156
4157 // An untracked file the old version does not carry must not block anything.
4158 wxString unrelatedFile = repoPath() + wxFileName::GetPathSeparator() + wxT( "unrelated.txt" );
4159 {
4160 std::ofstream f( unrelatedFile.ToStdString(), std::ios::binary );
4161 f << "scratch\n";
4162 }
4163
4164 auto readAll = []( const wxString& aPath )
4165 {
4166 std::ifstream in( aPath.ToStdString(), std::ios::binary );
4167 return std::string( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
4168 };
4169
4170 BOOST_CHECK( common.RestoreVersion( wxString::FromUTF8( withNotesHash ), error ) == RestoreResult::Dirty );
4171 BOOST_CHECK_EQUAL( readAll( notesFile ), "precious\n" );
4172
4173 // With the colliding file gone, the harmless untracked one alone does not block.
4174 wxRemoveFile( notesFile );
4175
4176 BOOST_REQUIRE_MESSAGE( common.RestoreVersion( wxString::FromUTF8( withNotesHash ), error )
4178 "RestoreVersion failed: " + error.summary.ToStdString() );
4179 BOOST_CHECK_EQUAL( readAll( notesFile ), "keep\n" );
4180 BOOST_CHECK_EQUAL( readAll( unrelatedFile ), "scratch\n" );
4181
4182 git_repository_free( repo );
4183}
4184
4185
4186// A file deleted here and changed on the remote conflicts with no local side. Keeping the
4187// deletion must produce a merge commit without the file, not a zero byte one.
4188BOOST_AUTO_TEST_CASE( MergeConflictKeepsDeletion )
4189{
4190 BOOST_TEST_REQUIRE( ready() );
4191
4192 git_repository* repo = openRepo();
4193 BOOST_TEST_REQUIRE( repo );
4194
4195 git_reference* headRef = nullptr;
4196 BOOST_REQUIRE_EQUAL( git_repository_head( &headRef, repo ), GIT_OK );
4197 git_oid baseOid = *git_reference_target( headRef );
4198 git_reference_free( headRef );
4199
4200 // Local side deletes the file.
4201 {
4202 git_index* index = nullptr;
4203 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
4204 BOOST_REQUIRE_EQUAL( git_index_remove_bypath( index, "file.txt" ), GIT_OK );
4205 git_index_write( index );
4206
4207 git_oid treeOid;
4208 BOOST_REQUIRE_EQUAL( git_index_write_tree( &treeOid, index ), GIT_OK );
4209 git_index_free( index );
4210
4211 git_tree* tree = nullptr;
4212 BOOST_REQUIRE_EQUAL( git_tree_lookup( &tree, repo, &treeOid ), GIT_OK );
4213
4214 git_commit* baseCommit = nullptr;
4215 BOOST_REQUIRE_EQUAL( git_commit_lookup( &baseCommit, repo, &baseOid ), GIT_OK );
4216
4217 git_signature* sig = nullptr;
4218 BOOST_REQUIRE_EQUAL( git_signature_now( &sig, TEST_AUTHOR_NAME, TEST_AUTHOR_EMAIL ), GIT_OK );
4219
4220 const git_commit* parents[1] = { baseCommit };
4221 git_oid deleteOid;
4223 git_commit_create( &deleteOid, repo, "HEAD", sig, sig, nullptr, "Delete file", tree, 1, parents ),
4224 GIT_OK );
4225
4226 git_signature_free( sig );
4227 git_commit_free( baseCommit );
4228 git_tree_free( tree );
4229 wxRemoveFile( repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" ) );
4230 }
4231
4232 // Remote side modifies it, without moving HEAD.
4233 git_oid remoteCommitOid = createDetachedCommit( repo, baseOid, wxT( "file.txt" ), "remote\n", "Remote change" );
4234
4235 writeFetchHead( remoteCommitOid );
4236
4237 KIGIT_COMMON common( repo );
4238
4239 wxString stageDir = tempBase() + wxFileName::GetPathSeparator() + wxT( "del_stages" );
4240 wxString headOid, theirsOid, conflictsError;
4241 KIGIT_ERROR_MESSAGE error;
4242 std::vector<KIGIT_CONFLICT_SIDES> conflicts;
4243
4244 BOOST_REQUIRE_MESSAGE( common.GetMergeConflicts( stageDir, headOid, theirsOid, conflicts, conflictsError ),
4245 "GetMergeConflicts failed: " + conflictsError.ToStdString() );
4246 BOOST_REQUIRE_EQUAL( conflicts.size(), 1u );
4247 BOOST_CHECK( !conflicts[0].hasOurs );
4248 BOOST_CHECK( conflicts[0].hasTheirs );
4249
4250 // Keep the deletion: an empty resolved path, not the extracted empty placeholder file.
4251 BOOST_REQUIRE_MESSAGE( common.CreateMergedCommit( headOid, theirsOid, { { conflicts[0].path, wxString() } }, error )
4253 "CreateMergedCommit failed: " + error.summary.ToStdString() );
4254
4255 git_oid newHead;
4256 BOOST_REQUIRE_EQUAL( git_reference_name_to_id( &newHead, repo, "HEAD" ), GIT_OK );
4257
4258 git_commit* mergeCommit = nullptr;
4259 BOOST_REQUIRE_EQUAL( git_commit_lookup( &mergeCommit, repo, &newHead ), GIT_OK );
4260 BOOST_CHECK_EQUAL( git_commit_parentcount( mergeCommit ), 2u );
4261
4262 git_tree* mergedTree = nullptr;
4263 BOOST_REQUIRE_EQUAL( git_commit_tree( &mergedTree, mergeCommit ), GIT_OK );
4264 BOOST_CHECK_MESSAGE( git_tree_entry_byname( mergedTree, "file.txt" ) == nullptr,
4265 "keeping the deletion must not commit the file" );
4266 git_tree_free( mergedTree );
4267 git_commit_free( mergeCommit );
4268
4269 BOOST_CHECK( !wxFileName::FileExists( repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" ) ) );
4270
4271 git_repository_free( repo );
4272}
4273
4274
4275// Viewing a diff materializes a committed tree, and that must never replace what the user has
4276// staged.
4277BOOST_AUTO_TEST_CASE( WriteTreeToDir_LeavesIndexUntouched )
4278{
4279 BOOST_TEST_REQUIRE( ready() );
4280
4281 git_repository* repo = openRepo();
4282 BOOST_TEST_REQUIRE( repo );
4283
4284 // Stage content that differs from both HEAD and the working file.
4285 wxString filePath = repoPath() + wxFileName::GetPathSeparator() + wxT( "file.txt" );
4286 {
4287 std::ofstream f( filePath.ToStdString() );
4288 f << "staged-work-in-progress";
4289 }
4290
4291 git_index* index = nullptr;
4292 BOOST_REQUIRE_EQUAL( git_repository_index( &index, repo ), GIT_OK );
4293 git_index_add_bypath( index, "file.txt" );
4294 git_index_write( index );
4295
4296 const git_index_entry* before = git_index_get_bypath( index, "file.txt", 0 );
4297 BOOST_REQUIRE( before );
4298 git_oid stagedOid = before->id;
4299
4300 // Under the fixture's own directory, so a failed run leaves nothing behind in the system temp.
4301 wxString dest = tempBase() + wxFileName::GetPathSeparator() + wxT( "tree_out" );
4302
4303 BOOST_CHECK( KIGIT::PROJECT_GIT_UTILS::WriteTreeToDir( repo, wxT( "HEAD" ), dest ) );
4304
4305 // Re-read the index from disk and confirm the staged blob is still the one we staged, not
4306 // the committed version that was checked out.
4307 git_index_read( index, 1 );
4308 const git_index_entry* after = git_index_get_bypath( index, "file.txt", 0 );
4309 BOOST_REQUIRE( after );
4310 BOOST_CHECK_MESSAGE( git_oid_equal( &stagedOid, &after->id ),
4311 "WriteTreeToDir must not rewrite the repository index" );
4312
4313 git_index_free( index );
4314
4315 if( wxFileName::DirExists( dest ) )
4316 wxFileName::Rmdir( dest, wxPATH_RMDIR_RECURSIVE );
4317
4318 git_repository_free( repo );
4319}
4320
4321
int index
const char * name
void AdvancePhase() override
Use the next available virtual zone of the dialog progress bar.
void SetTitle(const wxString &) override
Change the title displayed on the window caption.
void AdvanceProgress() override
Increment the progress bar length (inside the current virtual zone).
void SetCurrentProgress(double) override
Set the progress value to aProgress (0..1).
void Report(const wxString &) override
Display aMessage in the progress bar dialog.
void BeginPhase(int) override
Initialize the aPhase virtual zone of the dialog progress bar.
bool IsCancelled() const override
void AdvancePhase(const wxString &) override
Use the next available virtual zone of the dialog progress bar and updates the message.
void SetMaxProgress(int) override
Fix the value that gives the 100 percent progress bar length (inside the current virtual zone).
bool KeepRefreshing(bool=false) override
Update the UI (if any).
void SetNumPhases(int) override
Set the number of phases.
BranchResult SwitchToBranch(const wxString &aBranchName)
Switch to the specified branch.
void SetRemote(const wxString &aRemote)
void SetClonePath(const wxString &aPath)
CommitResult PerformCommit(const std::vector< wxString > &aFiles, const wxString &aMessage, const wxString &aAuthorName, const wxString &aAuthorEmail)
CommitResult PerformAmend(const std::vector< wxString > &aFiles, const wxString &aMessage, const wxString &aAuthorName, const wxString &aAuthorEmail)
InitResult InitializeRepository(const wxString &aPath)
Initialize a new git repository in the specified directory.
bool SetupRemote(const RemoteConfig &aConfig)
Set up a remote for the repository.
void SetProgressReporter(std::unique_ptr< PROGRESS_REPORTER > aProgressReporter)
bool PerformFetch(bool aSkipLock=false)
PullResult PerformPull()
PushResult PerformPush(bool aForce=false)
std::map< wxString, FileStatus > GetFileStatus(const wxString &aPathspec=wxEmptyString, bool aChangedOnly=false)
Get detailed file status for all files in the specified path.
Utility class with helper functions for project level git operations.
static bool IsTransientGitFile(const wxFileName &aFile)
Match a project-relative path against the shared transient patterns.
static bool WriteTreeToDir(git_repository *aRepo, const wxString &aRef, const wxString &aDestDir)
Check out a whole tree into a directory, leaving the repository's working copy and index alone.
static bool IsWithinProjectPath(const wxString &aAbsPath, const wxString &aProjectPath)
Test whether an absolute file path lives inside the current project directory.
int Push(const std::function< wxString()> &aConnected)
Connect, then push the refspec aConnected answers, so the caller can check what it pushes after a con...
Publishes a token for as long as its operation runs.
The project's git session.
std::shared_ptr< std::atomic< bool > > CANCEL_TOKEN
One token per operation.
GIT_CONN_TYPE GetConnType() const
std::vector< KIGIT_COMMIT_INFO > GetRecentCommits(size_t aMax=50, const KIGIT_HISTORY_FILTER &aFilter={}) const
bool HasUncommittedTrackedChanges(bool *aReadOk=nullptr) const
wxString GetRemote() const
bool IsOperationInProgress() const
True while a merge, rebase, cherry-pick or revert is in progress, which refuses commits.
std::unique_lock< std::mutex > LockAction()
git_repository * GetRepo() const
bool AddRemote(const wxString &aName, const wxString &aUrl)
static CANCEL_TOKEN NewCancelToken()
bool GetMergeConflicts(const wxString &aStageDir, wxString &aHeadOid, wxString &aTheirsOid, std::vector< KIGIT_CONFLICT_SIDES > &aConflicts, wxString &aError)
Recompute the merge in memory and extract each conflicted file's three versions into aStageDir,...
std::pair< std::set< wxString >, std::set< wxString > > GetDifferentFiles() const
Return a pair of sets of files that differ locally from the remote repository The first set is files ...
bool IsShuttingDown() const
Background timers ask this before starting work of their own.
bool DiscardChanges(const std::vector< wxString > &aPaths, wxString &aError)
Put the given working directory relative paths back to their committed state.
wxString GetUsername() const
void SetShuttingDown(bool aCancel)
Stop the operation running now and keep later ones from starting.
bool IsPathInHead(const wxString &aPath)
True when the working directory relative path exists in the HEAD commit's tree.
std::optional< KIGIT_UPSTREAM_STATUS > UpstreamStatus() const
The current branch against its upstream.
MergeCommitResult CreateMergedCommit(const wxString &aExpectedHeadOid, const wxString &aTheirsOid, const std::vector< std::pair< wxString, wxString > > &aResolvedFiles, KIGIT_ERROR_MESSAGE &aError)
Redo the merge with each conflicted path replaced by its resolved file, then commit and check out.
bool AbandonOperation(wxString &aError)
Drop that operation and return to the last commit. The caller holds the action lock.
wxString GetPassword()
The secret for the remote, read without ever prompting, so it is safe on a transfer worker.
GitOperation OperationInProgress() const
Which operation that is, so the panel can name it.
RestoreResult RestoreVersion(const wxString &aCommitHash, KIGIT_ERROR_MESSAGE &aError)
Restore the project as it was at aCommitHash, recorded as a new commit on top of the current head.
void SetRepo(git_repository *aRepo)
const std::vector< wxString > & GetErrorStrings() const
wxString GetErrorString()
void SetCancelToken(const KIGIT_COMMON::CANCEL_TOKEN &aToken)
Callbacks read this token rather than the session, so one operation's cancel cannot reach another.
const KIGIT_COMMON::CANCEL_TOKEN & CancelToken() const
bool IsThisOperationCancelled() const
Give each test a backend and a temporary directory.
const wxString & TempPath() const
Container for project specific data.
Definition project.h:63
PROJECT * GetProject(const wxString &aFullPath) const
Retrieve a loaded project by name.
bool UnloadProject(PROJECT *aProject, bool aSave=true)
Save, unload and unregister the given PROJECT.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true, bool aOverrideLock=false)
Load a project or sets up a new project with a specified path.
static std::string ToStdString(const wxString &aStr)
void SetGitBackend(GIT_BACKEND *aBackend)
GIT_BACKEND * GetGitBackend()
CommitResult
Definition git_backend.h:55
@ SuccessIndexStale
Committed, but the staged list was left as another program had it. Never retry on this.
Definition git_backend.h:59
InitResult
PullResult
PushResult
@ Busy
Another git operation held the action lock, so nothing was pushed.
std::vector< FILE_CHECKLIST_ENTRY > BuildGitChangeEntries(KIGIT_COMMON &aCommon, const wxString &aProjectPath, bool aDarkTheme)
Build the file checklist entries for the project's changed files, transient files filtered out and ea...
@ AlreadyCurrent
The chosen version's content matches the current head.
@ Restored
A new commit carrying the old version's content was created.
@ Error
The restore failed. See the error string.
@ Dirty
Uncommitted changes exist, and restoring would overwrite them.
The one place a fetch, push, clone or connection check reaches a remote.
std::unique_ptr< git_repository, decltype([](git_repository *aRepo) { git_repository_free(aRepo); })> GitRepositoryPtr
A unique pointer for git_repository objects with automatic cleanup.
std::unique_ptr< git_commit, decltype([](git_commit *aCommit) { git_commit_free(aCommit); })> GitCommitPtr
A unique pointer for git_commit objects with automatic cleanup.
std::unique_ptr< git_config, decltype([](git_config *aConfig) { git_config_free(aConfig); })> GitConfigPtr
A unique pointer for git_config objects with automatic cleanup.
std::unique_ptr< git_index, decltype([](git_index *aIndex) { git_index_free(aIndex); })> GitIndexPtr
A unique pointer for git_index objects with automatic cleanup.
std::unique_ptr< git_remote, decltype([](git_remote *aRemote) { git_remote_free(aRemote); })> GitRemotePtr
A unique pointer for git_remote objects with automatic cleanup.
KIGIT::GitRepositoryPtr InitGitRepository(const wxString &aPath, const char *aBranch="main", const char *aAuthorName="QA Test", const char *aAuthorEmail="[email protected]")
Pin the branch and author so repository setup does not depend on the user's Git config.
void WriteGitFile(const wxString &aRepoPath, const wxString &aRelativePath, const std::string &aContents)
Write test data without staging it. Create parent directories when needed.
git_oid CommitAllGitFiles(git_repository *aRepo, const wxString &aMessage)
Stage all changes, including deletions, and commit them.
git_oid CommitGitFile(git_repository *aRepo, const wxString &aPath, const wxString &aMessage)
Stage one file and commit the index. Other staged changes are kept.
bool collide(T aObject, U aAnotherObject, int aLayer, int aMinDistance)
Used by SHAPE_INDEX to implement Query().
One file row in a FILE_CHECKLIST_CTRL.
Build a temp directory tree containing a local working repo with one commit and a bare "remote" repo ...
const wxString & repoPath() const
wxString readConfig(git_repository *aRepo, const wxString &aKey)
Read a string value from the repo config, or "" if absent.
git_oid createCommit(git_repository *aRepo, const wxString &aFile, const wxString &aContent, const wxString &aMessage)
Create a new commit on the current branch from a single (path, content) pair.
git_repository * openRepo() const
Open the working repo. Caller frees with git_repository_free.
void useEmptyGlobalIgnore(git_repository *aRepo)
bool clearUpstreamConfig(git_repository *aRepo, const wxString &aBranch)
Drop branch.
bool addOrigin(git_repository *aRepo)
Add an origin remote pointing at the bare remote on disk.
const wxString & remotePath() const
bool setUpstreamConfig(git_repository *aRepo, const wxString &aBranch)
Set branch.<aBranch>.merge = refs/heads/<aBranch>, branch.<aBranch>.remote = origin.
void writeFetchHead(const git_oid &aOid)
Write .git/FETCH_HEAD naming aOid, as a fetch would leave it.
git_oid createDetachedCommit(git_repository *aRepo, const git_oid &aParentOid, const wxString &aFile, const std::string &aContent, const char *aMessage)
Create a commit on top of aParentOid setting aFile to aContent, without moving HEAD.
const wxString & tempBase() const
A summary the user can act on, with the raw text that explains it kept apart for the details.
BOOST_AUTO_TEST_CASE(HorizontalAlignment)
BOOST_CHECK(res.column_datatype(0)==SQL_NUMERIC||res.column_datatype(0)==SQL_DECIMAL)
BOOST_REQUIRE_EQUAL(rows.size(), 1)
BOOST_CHECK_EQUAL(std::any_cast< std::string >(rows[0].at("val")), "12345678901234567.89")
BOOST_REQUIRE_MESSAGE(dc.CacheTableInfo(table, { "part_id", "val" }), dc.GetLastError())
BOOST_REQUIRE(res.columns()==1)
BOOST_CHECK_EQUAL_COLLECTIONS(mixed.begin(), mixed.end(), expMixed.begin(), expMixed.end())
static const char * TEST_AUTHOR_NAME
static const char * TEST_AUTHOR_EMAIL
BOOST_AUTO_TEST_SUITE_END()
std::string path
IbisParser parser & reporter
static const char * TEST_AUTHOR_NAME
static const char * TEST_AUTHOR_EMAIL
BOOST_AUTO_TEST_CASE(FetchHeadMarksAtMostOneBranchToMerge)
static wxString seedProjectFile(const wxString &aDir)
VECTOR3I expected(15, 30, 45)
BOOST_TEST_CONTEXT("Test Clearance")
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.