KiCad PCB EDA Suite
Loading...
Searching...
No Matches
git_commit_pane.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
21#include <cli/exit_codes.h>
24#include <frame_type.h>
25#include <kiway.h>
26#include <kiway_player.h>
27#include <mail_type.h>
28
29#include <algorithm>
30#include <memory>
31#include <optional>
32
33#include <wx/app.h>
34#include <wx/aui/floatpane.h>
35#include <wx/aui/framemanager.h>
36#include <wx/button.h>
37#include <wx/dataview.h>
38#include <wx/file.h>
39#include <wx/filefn.h>
40#include <wx/filename.h>
41#include <wx/hyperlink.h>
42#include <wx/menu.h>
43#include <wx/msgdlg.h>
44#include <wx/settings.h>
45#include <wx/sizer.h>
46#include <wx/statbox.h>
47#include <wx/stattext.h>
48#include <wx/textctrl.h>
49#include <wx/utils.h>
50#include <wx/weakref.h>
51
52#include <wx/choicdlg.h>
53
54#include <bitmap_store.h>
55#include <bitmaps.h>
56#include <clipboard.h>
57#include <confirm.h>
62#include <kiplatform/ui.h>
64#include <reporter.h>
66#include <git/kigit_ignore.h>
73#include <eda_base_frame.h>
75#include <pgm_base.h>
76#include <project.h>
80#include <set>
81#include <thread>
85#include <widgets/ui_common.h>
86
87
88namespace
89{
90enum
91{
92 ID_OPEN_ADVANCED = wxID_HIGHEST + 1,
93 ID_SET_AUTHOR
94};
95}
96
97
98// Pin both the branch (including an unborn one) and its tip while a commit's status reads run.
99// The caller holds the action lock, just as it does when validating this before the write.
100static std::pair<wxString, wxString> commitHead( git_repository* aRepo )
101{
102 std::pair<wxString, wxString> state;
103 git_reference* head = nullptr;
104
105 if( git_reference_lookup( &head, aRepo, "HEAD" ) == GIT_OK )
106 {
107 if( const char* target = git_reference_symbolic_target( head ) )
108 state.first = wxString::FromUTF8( target );
109
110 git_reference_free( head );
111 }
112
113 git_oid oid;
114
115 if( git_reference_name_to_id( &oid, aRepo, "HEAD" ) == GIT_OK )
116 state.second = wxString::FromUTF8( git_oid_tostr_s( &oid ) );
117
118 return state;
119}
120
121
122// Check again under the action lock before amending. A push can change eligibility without moving HEAD.
123static wxString amendRefusal( KIGIT_COMMON& aCommon, const std::pair<wxString, wxString>& aExpectedHead )
124{
125 if( aExpectedHead.second.IsEmpty() || aExpectedHead != commitHead( aCommon.GetRepo() ) )
126 return _( "The branch or its last commit changed. Select the commit to amend again." );
127
128 if( aCommon.IsHeadDetached() || aCommon.IsHeadUnborn() )
129 return _( "Switch to a branch before amending its last commit." );
130
131 if( aCommon.IsOperationInProgress() )
132 return _( "Finish or abandon the current Git operation before amending a commit." );
133
134 if( !aCommon.HasLocalCommits() )
135 return _( "Only an unpushed commit can be amended." );
136
137 return wxEmptyString;
138}
139
140
141// Make aName at HEAD and move onto it, so the next commit lands there. The caller holds the git
142// action lock. A failure leaves nothing behind and says why in aError and aDetail.
143static bool moveToNewBranch( KIGIT_COMMON& aCommon, const wxString& aName, wxString& aError, wxString& aDetail )
144{
145 GIT_BRANCH_HANDLER branchHandler( &aCommon );
146
147 // With no commits there is nothing to branch from, so the first commit makes the branch.
148 if( aCommon.IsHeadUnborn() )
149 {
150 if( !aCommon.StartUnbornBranch( aName ) )
151 {
152 aError = wxString::Format( _( "Could not start branch '%s'." ), aName );
154 return false;
155 }
156
157 return true;
158 }
159
160 if( !aCommon.CreateBranch( aName ) )
161 {
162 aError = wxString::Format( _( "Could not create branch '%s'." ), aName );
164 return false;
165 }
166
167 if( branchHandler.SwitchToBranch( aName ) != BranchResult::Success )
168 {
169 KIGIT_ERROR_MESSAGE switchError = branchHandler.PopError();
170
171 aError = switchError.summary.IsEmpty()
172 ? wxString::Format( _( "Could not switch to the new branch '%s'." ), aName )
173 : switchError.summary;
174 aDetail = switchError.details;
175 aCommon.DeleteBranch( aName );
176 return false;
177 }
178
179 return true;
180}
181
182
183// Go back to aPrevious and drop aName, after the commit meant for it failed. The caller holds
184// the git action lock.
185static void dropNewBranch( KIGIT_COMMON& aCommon, const wxString& aName, const wxString& aPrevious )
186{
187 // Before the first commit there was no branch to come back to, and the name is only where
188 // HEAD points.
189 if( aPrevious.IsEmpty() )
190 return;
191
192 GIT_BRANCH_HANDLER branchHandler( &aCommon );
193 branchHandler.SwitchToBranch( aPrevious );
194 aCommon.DeleteBranch( aName );
195}
196
197
199 GIT_COMMIT_PANE( aParent, aParent )
200{
201}
202
203
205 GIT_COMMIT_PANE_BASE( aParent ),
206 m_frame( aFrame ),
207 m_hasUnpushedCommits( false ),
208 m_hasRemote( false ),
209 m_headDetached( false ),
210 m_upstreamAhead( 0 ),
211 m_operationInProgress( false ),
213 m_editorsDirty( false )
214{
215 m_summary->SetHint( _( "Summarize your changes..." ) );
216 m_newBranchName->SetHint( _( "Branch name" ) );
217
218 // Sized by hand, or the longest message would set the width of the whole row. It shrinks in a
219 // narrow dock so the settings button stays reachable.
220 m_recentMessages->SetMinSize( FromDIP( wxSize( 60, -1 ) ) );
221 m_recentMessages->SetMaxSize( FromDIP( wxSize( 170, -1 ) ) );
223
224 m_summaryCount->SetToolTip( _( "Git tools show up to 72 characters of the summary on one line." ) );
226
227 // No platform hints a multi line box natively, and wx's stand-in text is wiped by ChangeValue
228 m_descriptionHint = new wxStaticText( this, wxID_ANY, _( "Extended Description (optional)" ) );
229 m_descriptionHint->Bind( wxEVT_LEFT_DOWN,
230 [this]( wxMouseEvent& )
231 {
232 m_description->SetFocus();
233 } );
234
235 m_settingsButton->Bind( wxEVT_BUTTON, &GIT_COMMIT_PANE::onSettings, this );
236 m_commitButton->Bind( wxEVT_BUTTON, &GIT_COMMIT_PANE::onCommit, this );
237
238 // Commit from the keyboard, since the description box takes a plain Return as a new line.
239 // Adding Shift does what the button's menu calls Commit and Push.
240 auto commitOnEnter = [this]( wxKeyEvent& aEvent )
241 {
242 bool enter = aEvent.GetKeyCode() == WXK_RETURN || aEvent.GetKeyCode() == WXK_NUMPAD_ENTER;
243
244 if( enter && ( aEvent.CmdDown() || aEvent.ControlDown() ) )
245 {
246 if( aEvent.ShiftDown() )
247 {
248 if( m_commitAndPushItem->IsEnabled() )
249 {
250 doCommit( true );
251 return;
252 }
253 }
254 else if( m_commitButton->IsEnabled() )
255 {
257 return;
258 }
259 }
260
261 aEvent.Skip();
262 };
263
264 m_summary->Bind( wxEVT_CHAR_HOOK, commitOnEnter );
265 m_description->Bind( wxEVT_CHAR_HOOK, commitOnEnter );
266 m_commitAndPushItem = m_commitButton->GetSplitButtonMenu()->Append( wxID_ANY, _( "Commit and Push" ) );
267 m_commitButton->GetSplitButtonMenu()->Bind( wxEVT_MENU, &GIT_COMMIT_PANE::onCommitAndPush, this,
268 m_commitAndPushItem->GetId() );
269 m_pullButton->Bind( wxEVT_BUTTON, &GIT_COMMIT_PANE::onPull, this );
270 m_amendCheckbox->Bind( wxEVT_CHECKBOX, &GIT_COMMIT_PANE::onAmendToggled, this );
271 m_undoCommitButton->Bind( wxEVT_BUTTON, &GIT_COMMIT_PANE::onUndoCommit, this );
272 m_summary->Bind( wxEVT_TEXT, &GIT_COMMIT_PANE::onMessageChanged, this );
273 m_newBranchName->Bind( wxEVT_TEXT,
274 [this]( wxCommandEvent& )
275 {
277 } );
278 m_newBranchCheckbox->Bind( wxEVT_CHECKBOX, &GIT_COMMIT_PANE::onNewBranchToggled, this );
279 m_recentMessages->Bind( wxEVT_CHOICE, &GIT_COMMIT_PANE::onRecentMessage, this );
280 m_showDiffButton->Bind( wxEVT_BUTTON, &GIT_COMMIT_PANE::onShowDiff, this );
281 Bind( wxEVT_SYS_COLOUR_CHANGED, &GIT_COMMIT_PANE::onThemeChanged, this );
282 m_copyTrustCommand->Bind( wxEVT_BUTTON,
283 [this]( wxCommandEvent& )
284 {
285 SaveClipboard( m_trustCommand->GetValue().utf8_string() );
286 } );
287 m_showDiffButton->SetToolTip( _( "Show what changed in the selected file. Pick a file in the list first." ) );
288 m_description->Bind( wxEVT_TEXT,
289 [this]( wxCommandEvent& )
290 {
292
295 } );
296 m_checklist->Bind( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, &GIT_COMMIT_PANE::onChecklistChanged, this );
297 m_checklist->SetToolTip( _( "Double click a file to see what changed in it. Right click for more." ) );
298 m_checklist->Bind( wxEVT_DATAVIEW_ITEM_ACTIVATED, &GIT_COMMIT_PANE::onFileActivated, this );
299 m_checklist->Bind( wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, &GIT_COMMIT_PANE::onChecklistContextMenu, this );
300 m_checklist->Bind( wxEVT_DATAVIEW_SELECTION_CHANGED,
301 [this]( wxDataViewEvent& )
302 {
303 m_showDiffButton->Enable( m_checklist->GetSelection().IsOk() );
304
306 m_fileSelectedHandler( m_checklist->GetItemPath( m_checklist->GetSelection() ) );
307 } );
308 Bind( wxEVT_IDLE, &GIT_COMMIT_PANE::onIdle, this );
309
310 // Inside the advanced window the page is wide enough for the list and the message side
311 // by side.
312 m_inAdvancedWindow = aParent != aFrame;
313
314 // Otherwise the history is only reachable through the gear menu, where users did not find it
315 m_historyLink = new wxHyperlinkCtrl( this, wxID_ANY, _( "History..." ), wxEmptyString, wxDefaultPosition,
316 wxDefaultSize, wxHL_ALIGN_RIGHT | wxNO_BORDER );
317 m_historyLink->SetToolTip( _( "Show the commits made to this project" ) );
318 m_historyLink->Hide();
320 m_historyLink->Bind( wxEVT_HYPERLINK,
321 [this]( wxHyperlinkEvent& )
322 {
323 ShowHistory();
324 } );
325 GetSizer()->Add( m_historyLink, 0, wxALIGN_RIGHT | wxLEFT | wxRIGHT | wxBOTTOM, 4 );
326
327 // A short dock scrolls, and the list must still show a few files when it does
328 m_checklist->SetMinSize( FromDIP( wxSize( -1, 100 ) ) );
329
331 layoutWide();
332
333 applyTheme();
334
335 // Sized by hand, or a long branch name would set the width of the whole row. Wide enough
336 // for an ordinary name, with the tooltip carrying the rest when one is longer.
337
338 // Measured while every control is still shown, leaving room for the scrollbar a short dock adds
339 m_minDockWidth = GetSizer()->CalcMin().x + wxSystemSettings::GetMetric( wxSYS_VSCROLL_X, this );
340
341 // The advanced window takes its minimum from this, and the branch row stays hidden until the status arrives
343 SetMinSize( wxSize( m_minDockWidth, -1 ) );
344
345 // A dock shorter than the controls scrolls them rather than drawing them over each other
346 SetScrollRate( 0, FromDIP( 10 ) );
347
350}
351
352
354{
355 wxSizer* column = GetSizer();
356 column->Detach( m_changesRow );
357 column->Detach( m_emptyLabel );
358 column->Detach( m_trustRow );
359 column->Detach( m_undoCommitButton );
360 column->Detach( m_checklist );
361 column->GetItem( m_description )->SetProportion( 1 );
362 column->SetMinSize( FromDIP( wxSize( 280, -1 ) ) );
363
364 // The docked pane's cap is for a narrow dock; here the caption and most of a message fit
365 m_recentMessages->SetMaxSize( wxDefaultSize );
366 m_recentMessages->SetMinSize( FromDIP( wxSize( 170, -1 ) ) );
367
368 wxStaticText* heading = new wxStaticText( this, wxID_ANY, _( "Commit Message" ) );
369 heading->SetFont( heading->GetFont().Bold() );
370 column->Insert( 0, heading, 0, wxLEFT | wxRIGHT | wxTOP, 8 );
371
372 wxStaticBoxSizer* summary = new wxStaticBoxSizer( wxVERTICAL, this, _( "Summary" ) );
373 wxWindow* box = summary->GetStaticBox();
374
375 m_summaryFiles = new wxStaticText( box, wxID_ANY, wxEmptyString );
376 m_summaryAdded = new wxStaticText( box, wxID_ANY, wxEmptyString );
377 m_summaryRemoved = new wxStaticText( box, wxID_ANY, wxEmptyString );
378
379 wxBoxSizer* lines = new wxBoxSizer( wxHORIZONTAL );
380 lines->Add( m_summaryAdded, 0, wxRIGHT, 8 );
381 lines->Add( m_summaryRemoved, 0 );
382 summary->Add( m_summaryFiles, 0, wxLEFT | wxRIGHT | wxTOP, 4 );
383 summary->Add( lines, 0, wxALL, 4 );
384
385 // Under the commit options box.
386 size_t afterOptions = column->GetItemCount();
387
388 for( size_t ii = 0; ii < column->GetItemCount(); ++ii )
389 {
390 if( column->GetItem( ii )->GetSizer() == m_optionsSizer )
391 afterOptions = ii + 1;
392 }
393
394 column->Insert( afterOptions, summary, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, 8 );
395
396 wxBoxSizer* files = new wxBoxSizer( wxVERTICAL );
397 files->Add( m_changesRow, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, 8 );
398 files->Add( m_emptyLabel, 0, wxALL, 8 );
399 files->Add( m_trustRow, 0, wxEXPAND | wxBOTTOM | wxLEFT | wxRIGHT, 8 );
400 files->Add( m_undoCommitButton, 0, wxBOTTOM | wxLEFT | wxRIGHT, 8 );
401 files->Add( m_checklist, 1, wxALL | wxEXPAND, 4 );
402
403 // The list is the only part that stretches, so without a floor the docked split leaves it one row tall
404 m_checklist->SetMinSize( FromDIP( wxSize( -1, 120 ) ) );
405
406 wxBoxSizer* row = new wxBoxSizer( wxHORIZONTAL );
407 row->Add( files, 1, wxEXPAND );
408 row->Add( column, 0, wxEXPAND );
409
410 // The old sizer lives on as the right column.
411 SetSizer( row, false );
412 Layout();
413}
414
415
416void GIT_COMMIT_PANE::SetFileSelectedHandler( std::function<void( const wxString& )> aHandler )
417{
418 m_fileSelectedHandler = std::move( aHandler );
419}
420
421
423{
424 // Before the members go, so neither a handler nor another pane's Cancel reaches this pane
425 m_transferLink.reset();
426 m_ownHold.Release();
427
428 m_refresh.Cancel();
429 m_actionQuery.Cancel();
430
431 // The window's Pull and Push run through this pane, so it goes when the pane goes.
433
434 // The transfer outlives this pane, and its completion refreshes the other windows, so
435 // nothing has to be reported here. Asking it to stop is the destructor's own job.
436 if( std::shared_ptr<KIGIT_COMMON> common = m_listenerSession.lock() )
437 common->RemoveRefreshListener( this );
438}
439
440
442{
443 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
444
445 if( m_listenerSession.lock() == common )
446 return;
447
448 // Loading a project replaces the git session, so move the listener to the new one.
449 if( std::shared_ptr<KIGIT_COMMON> previous = m_listenerSession.lock() )
450 previous->RemoveRefreshListener( this );
451
452 // The window still lists the previous project, so it closes with the project that filled it.
453 // A first attach replaced nothing, and must not take the window from whoever opened it.
456
457 m_refresh.Cancel();
458 m_actionQuery.Cancel();
460
461 if( m_actionPending )
462 {
463 m_actionPending = false;
464 setBusy( false, wxEmptyString );
465 }
466
467 m_hasRepo = false;
468
469 m_amendCheckbox->SetValue( false );
470 m_amendHead = {};
471 m_undoHead = {};
472 m_listenerAttached = true;
473
474 // The remembered paths describe the previous project's file list, so a path that repeats in
475 // the new project would inherit the old project's tick state.
476 m_shownPaths.clear();
477
478 common->AddRefreshListener( this,
479 [this]()
480 {
482 } );
483 m_listenerSession = common;
485
486 // Another window's transfer on this repository shows here and this pane's Cancel can stop it
487 m_transferLink = common->Transfers().Subscribe( this );
489}
490
491
493{
494 bool hasRepo = false;
495 bool hasLocalCommits = false;
496 bool hasRemote = false;
497 bool headDetached = false;
499 size_t upstreamAhead = 0;
500 size_t unpushed = 0;
502 std::pair<wxString, wxString> head;
503 wxString attachError;
506 std::vector<FILE_CHECKLIST_ENTRY> entries;
507 std::vector<KIGIT_BRANCH_INFO> branches;
508 std::vector<wxString> recentMessages;
509 std::pair<int, int> lineStats{ 0, 0 };
510};
511
512
514{
515 syncListener();
516
517 // A session attached before the preference was turned off is still bound.
518 if( !Pgm().GetCommonSettings()->m_Git.enableGit )
519 {
520 m_refresh.Cancel();
522 return;
523 }
524
525 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
526 wxString projectPath = m_frame->Prj().GetProjectPath();
527 bool dark = KIPLATFORM::UI::IsDarkTheme();
528 bool countLines = m_summaryFiles != nullptr;
529 auto status = std::make_shared<STATUS>();
530 status->attachError = common->GetAttachError();
531 status->attachTrustCommand = common->GetAttachTrustCommand();
532
533 m_refresh.Run(
534 common,
535 [status, projectPath, dark, countLines]( KIGIT_COMMON& aCommon )
536 {
537 status->hasRepo = true;
538 status->entries = BuildGitChangeEntries( aCommon, projectPath, dark );
539 status->hasRemote = aCommon.HasPushAndPullRemote();
540 status->headDetached = aCommon.IsHeadDetached();
541 status->operationInProgress = aCommon.IsOperationInProgress();
542 status->operation = aCommon.OperationInProgress();
543
544 if( std::optional<KIGIT_UPSTREAM_STATUS> upstream = aCommon.UpstreamStatus() )
545 {
546 status->hasLocalCommits = upstream->HasLocalCommits();
547 status->upstreamAhead = upstream->divergence.behind;
548 status->unpushed = upstream->divergence.ahead;
549 }
550
551 status->branches = aCommon.GetBranches();
552 KIGIT::SortBranchesForDisplay( status->branches );
553 status->currentBranch = aCommon.GetCurrentBranchName();
554 status->head = commitHead( aCommon.GetRepo() );
555 status->recentMessages = aCommon.GetRecentCommitMessages( 10 );
556
557 if( countLines )
558 {
559 std::set<wxString> changed;
560
561 for( const FILE_CHECKLIST_ENTRY& entry : status->entries )
562 changed.insert( entry.path );
563
564 status->lineStats = aCommon.GetWorkingTreeLineStats( changed );
565 }
566 },
567 [this, common, status]()
568 {
569 if( m_frame->Prj().GetGitCommon() == common && !common->IsShuttingDown()
570 && Pgm().GetCommonSettings()->m_Git.enableGit )
571 {
572 applyStatus( *status );
573 }
574 } );
575}
576
577
579{
580 std::vector<FILE_CHECKLIST_ENTRY> entries = aStatus.entries;
581 m_hasRepo = aStatus.hasRepo;
582 m_hasRemote = aStatus.hasRemote;
585 m_operation = aStatus.operation;
587
588 // Without a remote there is nowhere to push to, so local commits are not waiting for it.
591 m_lineStats = aStatus.lineStats;
592 populateBranches( aStatus );
594
595 // Allow saving unsaved editor changes for review even when no files are listed yet.
596 m_editorsDirty = aStatus.hasRepo && DocumentEditorsDirty( m_frame->Kiway() );
597
598 // Amending is offered only while the last commit has not been pushed, so an already
599 // published commit can never be rewritten from here.
601 m_undoHead = aStatus.head;
602
603 // Preserve unticked files across refreshes. New files start unchecked while amending.
604 std::set<wxString> stillChecked;
605
606 for( const wxString& path : m_checklist->GetCheckedPaths() )
607 stillChecked.insert( path );
608
609 for( FILE_CHECKLIST_ENTRY& entry : entries )
610 {
611 if( ( m_shownPaths.count( entry.path ) && !stillChecked.count( entry.path ) )
612 || ( m_amendCheckbox->IsChecked() && !m_shownPaths.count( entry.path ) ) )
613 entry.checked = false;
614 }
615
616 m_shownPaths.clear();
617
618 for( const FILE_CHECKLIST_ENTRY& entry : entries )
619 m_shownPaths.insert( entry.path );
620
621 m_checklist->SetEntries( entries );
623
624 bool hasChanges = !entries.empty();
625 wxString trustCommand;
626
627 m_checklist->Show( hasChanges );
628 m_changesRow->ShowItems( hasChanges );
629
630 // The message field also has to be there for a message-only amend and for committing
631 // unsaved editor changes, when the list itself is empty.
632 updateMessageVisibility( hasChanges );
633
635 {
636 setStatusText( wxString::Format( _( "This project is in the middle of a %s that was started outside "
637 "KiCad or interrupted. Abandon it to go back to the last commit, "
638 "or finish it with the program that started it." ),
639 operationNoun() ) );
640 m_emptyLabel->Show( true );
641 }
642 else if( m_headDetached )
643 {
644 setStatusText( _( "This project is showing an old snapshot rather than a branch, so it cannot be "
645 "committed or pushed from here. In the Advanced Git window, choose Branches "
646 "and double click a branch to go back to it." ) );
647 m_emptyLabel->Show( true );
648 }
649 else if( hasChanges )
650 {
651 m_emptyLabel->Show( false );
652 }
653 else
654 {
655 if( !Pgm().GetCommonSettings()->m_Git.enableGit )
656 setStatusText( _( "Version control is turned off in Preferences." ) );
657 else if( !aStatus.hasRepo && !aStatus.attachError.IsEmpty() )
658 {
659 setStatusText( aStatus.attachError );
660 trustCommand = aStatus.attachTrustCommand;
661 }
662 else if( !aStatus.hasRepo )
663 setStatusText( _( "This project is not under version control. To set it up, right click "
664 "the project in the project manager and choose Version Control." ) );
665 else if( m_upstreamAhead )
666 setStatusText( wxString::Format( wxPLURAL( "The tracked branch has %zu commit this project does not. "
667 "Get Changes brings it in.",
668 "The tracked branch has %zu commits this project does not. "
669 "Get Changes brings them in.",
671 m_upstreamAhead ) );
672 else if( m_unpushedCount )
673 setStatusText( wxString::Format( wxPLURAL( "%zu commit is waiting to be pushed.",
674 "%zu commits are waiting to be pushed.", m_unpushedCount ),
675 m_unpushedCount ) );
676 else if( m_hasUnpushedCommits )
677 setStatusText( _( "Committed changes are waiting to be pushed." ) );
678 else
679 setStatusText( _( "No changes" ) );
680
681 m_emptyLabel->Show( true );
682 }
683
684 showTrustCommand( trustCommand );
687 m_undoCommitButton->Enable( m_canAmend && !m_actionPending && !m_transfer.IsBusy() );
689 Layout();
691}
692
693
695{
697 dialog->ReloadPages();
698}
699
700
705
706
708{
709 m_actionQuery.Cancel();
711
712 if( m_actionPending )
713 {
714 m_actionPending = false;
715 setBusy( false, wxEmptyString );
716 }
717 m_hasRepo = false;
718 m_hasUnpushedCommits = false;
719 m_unpushedCount = 0;
720 m_hasRemote = false;
721 m_headDetached = false;
722 m_operationInProgress = false;
724 m_upstreamAhead = 0;
725 m_editorsDirty = false;
726
727 m_shownPaths.clear();
728 m_checklist->SetEntries( {} );
729 m_checklist->Show( false );
730 m_changesRow->ShowItems( false );
731 m_branchName->SetLabel( wxEmptyString );
732 m_branchRow->ShowItems( false );
733 m_settingsButton->Show();
734
735 m_canAmend = false;
736 m_amendCheckbox->SetValue( false );
737 m_amendHead = {};
738 m_undoHead = {};
739 m_undoCommitButton->Hide();
740 m_historyLink->Hide();
742
743 setStatusText( _( "Version control is turned off in Preferences." ) );
744 m_emptyLabel->Show( true );
745 showTrustCommand( wxEmptyString );
746
748 Layout();
749}
750
751
752void GIT_COMMIT_PANE::showTrustCommand( const wxString& aCommand )
753{
754 m_trustCommand->ChangeValue( aCommand );
755 m_trustRow->ShowItems( !aCommand.IsEmpty() );
756}
757
758
759void GIT_COMMIT_PANE::setStatusText( const wxString& aText )
760{
761 m_statusText = aText;
763 Layout();
764}
765
766
768{
769 // Rows shown or hidden change the content height without the size event wx refits the scroll area on
770 if( GetBestVirtualSize() != GetVirtualSize() )
771 FitInside();
772
773 bool done = layoutAndWrapStatus();
774
775 // AUI sizes a pane from its pane info alone and squeezes the controls past their minimum
776 const int height = GetSizer()->CalcMin().y;
777
778 // Floating or docking the pane reparents it into a frame laid out from a copy of the pane info
779 if( height != m_dockMinHeight || GetParent() != m_dockParent )
780 {
781 m_dockMinHeight = height;
782 m_dockParent = GetParent();
783 m_dockUpdatePending = true;
784 }
785
786 return done;
787}
788
789
791{
792 bool done = GIT_COMMIT_PANE_BASE::Layout();
793 wxSizer* column = m_emptyLabel ? m_emptyLabel->GetContainingSizer() : nullptr;
794
795 if( !column || m_statusText.IsEmpty() )
796 return done;
797
798 // Every resize ends here, and so does a change in the wide layout's other column, which moves the
799 // label's column without resizing the pane
800 const int available = column == GetSizer() ? GetClientSize().GetWidth() : column->GetSize().GetWidth();
801
802 // The floor keeps a collapsed column from breaking at every character
803 const int width = std::max( 40, available - 2 * column->GetItem( m_emptyLabel )->GetBorder() );
804
805 if( width == m_statusWrapWidth )
806 return done;
807
808 m_statusWrapWidth = width;
809
810 // A line that fills the label exactly can be broken again by the native Windows control
811 m_emptyLabel->SetLabelText( KIUI::WrapText( m_emptyLabel, m_statusText, width - 1 ) );
812
813 // The label's height follows its line count only once the sizer runs again
814 return GIT_COMMIT_PANE_BASE::Layout();
815}
816
817
819{
820 wxAuiManager* manager = wxAuiManager::GetManager( this );
821
822 if( !manager )
823 return;
824
825 wxAuiPaneInfo& pane = manager->GetPane( this );
826
827 if( !pane.IsOk() )
828 return;
829
830 // A refresh passes through shorter states, so compare with what the manager already has
831 const bool changed = pane.min_size.y != m_dockMinHeight;
832
833 pane.MinSize( pane.min_size.x, m_dockMinHeight );
834
835 // A floating pane is laid out by a copy of its info in the floating frame's own manager
836 if( wxAuiFloatingFrame* floating = wxDynamicCast( pane.frame, wxAuiFloatingFrame ) )
837 {
838 wxAuiManager& inner = floating->GetAuiManager();
839 wxAuiPaneInfo& innerPane = inner.GetPane( this );
840
841 if( innerPane.min_size != pane.min_size )
842 {
843 innerPane.MinSize( pane.min_size );
844 inner.Update();
845 }
846
847 // wx opens a floating pane at its FloatingSize even when that is below the pane's minimum
848 const wxSize minimum = floating->GetSizer()->GetMinSize();
849 const wxSize size = floating->GetClientSize();
850
851 floating->SetMinClientSize( minimum );
852
853 if( size.x < minimum.x || size.y < minimum.y )
854 floating->SetClientSize( wxSize( std::max( size.x, minimum.x ), std::max( size.y, minimum.y ) ) );
855 }
856 else if( changed && pane.IsShown() )
857 {
858 manager->Update();
859 }
860}
861
862
864{
866 m_descriptionHint->SetForegroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_GRAYTEXT ) );
867
868 // The summary's line counts use the diff colours
869 if( m_summaryAdded )
870 {
871 const KICAD_DIFF::DIFF_COLOR_THEME theme =
873
874 m_summaryAdded->SetForegroundColour( theme.added.ToColour() );
875 m_summaryRemoved->SetForegroundColour( theme.removed.ToColour() );
876 }
877}
878
879
880void GIT_COMMIT_PANE::onThemeChanged( wxSysColourChangedEvent& aEvent )
881{
882 // Icons and colours picked at construction belong to the theme that was active then
883 applyTheme();
884
885 // The list's row colours are chosen when its status is read
887
888 aEvent.Skip();
889}
890
891
892void GIT_COMMIT_PANE::onIdle( wxIdleEvent& aEvent )
893{
894 aEvent.Skip();
895
896 // Update() from inside Layout() would recurse, and during a sash drag it would drop the drag
897 if( m_dockUpdatePending && !wxWindow::GetCapture() )
898 {
899 m_dockUpdatePending = false;
901 }
902
903 // Every layout path moves the box, so the hint follows it from here.
905
906 // Editing does not announce itself to the pane, so watch for the unsaved editor state
907 // changing while the pane is visible. The refresh runs only on the transition.
908 if( !Pgm().GetCommonSettings()->m_Git.enableGit || m_transfer.IsBusy() || m_actionPending || m_refresh.IsBusy()
909 || !IsShownOnScreen() )
910 return;
911
912 bool dirty = m_hasRepo && DocumentEditorsDirty( m_frame->Kiway() );
913
914 if( dirty != m_editorsDirty )
916}
917
918
919void GIT_COMMIT_PANE::onSettings( wxCommandEvent& aEvent )
920{
921 wxMenu menu;
922
923 // Inside the advanced window the entry would only raise the window it is in.
924 if( !m_inAdvancedWindow )
925 {
926 menu.Append( ID_OPEN_ADVANCED, _( "Open Advanced Git Window..." ) );
927 menu.Bind( wxEVT_MENU,
928 [this]( wxCommandEvent& )
929 {
930 // The window belongs to the session, not to this panel, so all three
931 // frames raise the same one.
933 },
934 ID_OPEN_ADVANCED );
935 }
936
937 menu.Append( ID_SET_AUTHOR, _( "Set Author..." ) );
938 menu.Bind( wxEVT_MENU,
939 [this]( wxCommandEvent& )
940 {
941 setAuthor();
942 },
943 ID_SET_AUTHOR );
944
945 PopupMenu( &menu );
946}
947
948
950{
951 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
952 auto identity = std::make_shared<KIGIT::GIT_IDENTITY>();
953
955 common,
956 [identity]( KIGIT_COMMON& aSession )
957 {
958 *identity = KIGIT::ReadGitIdentity( aSession );
959 },
960 [this, common, identity]()
961 {
962 KIGIT::EditGitIdentity( this, m_frame, common, *identity );
963 },
964 _( "Reading author..." ) );
965}
966
968{
969 // A commit is possible with listed changes, unsaved editor changes, or an amend. Both callers
970 // share this, so the fields cannot disappear while the buttons still ask for a message.
971 bool show = aHasChanges || m_editorsDirty || m_amendCheckbox->IsChecked();
972
973 m_summary->Show( show );
975 m_description->Show( show );
976
977 // A pick only fills the message fields, so the list goes with them
978 m_recentMessages->Show( show && !m_recentMessageTexts.empty() );
979
980 // The options box stays for a message only amend, with just the amend tick in it.
981 m_optionsSizer->ShowItems( show || m_canAmend );
982 m_amendCheckbox->Show( m_canAmend || m_amendCheckbox->IsChecked() );
983 m_signOffCheckbox->Show( show );
984 m_newBranchCheckbox->Show( show );
985 m_newBranchName->Show( show );
986}
987
988
990{
991 switch( m_operation )
992 {
993 case GitOperation::Merge: return _( "merge" );
994 case GitOperation::Rebase: return _( "rebase" );
995 case GitOperation::CherryPick: return _( "cherry-pick" );
996 case GitOperation::Revert: return _( "revert" );
997 default: return _( "git operation" );
998 }
999}
1000
1001
1003{
1004 switch( m_operation )
1005 {
1006 case GitOperation::Merge: return _( "Abandon Merge" );
1007 case GitOperation::Rebase: return _( "Abandon Rebase" );
1008 case GitOperation::CherryPick: return _( "Abandon Cherry-pick" );
1009 case GitOperation::Revert: return _( "Abandon Revert" );
1010 default: return _( "Abandon Operation" );
1011 }
1012}
1013
1014
1016{
1017 // While a transfer runs the busy state owns the controls. Checklist or message edits
1018 // must not re-enable the buttons under it.
1019 if( m_transfer.IsBusy() || othersBusy() || m_actionPending )
1020 return;
1021
1022 // Until the repository's status arrives the ticked rows may still be another repository's
1023 if( !m_hasRepo )
1024 {
1025 m_commitButton->Enable( false );
1026 m_commitAndPushItem->Enable( false );
1027 m_pullButton->SetLabel( _( "Get Changes" ) );
1028 m_pullButton->UnsetToolTip();
1029 m_pullButton->Enable( false );
1030 return;
1031 }
1032
1034 {
1035 m_commitButton->Enable( false );
1036 m_pullButton->SetLabel( abandonLabel() );
1037 m_pullButton->Enable( true );
1038 return;
1039 }
1040
1041 if( m_headDetached )
1042 {
1043 m_commitButton->Enable( false );
1044 m_pullButton->Enable( false );
1045 return;
1046 }
1047
1048 // The empty state label only shows when there is nothing to commit, so the button carries
1049 // the notice the rest of the time.
1050 if( m_upstreamAhead )
1051 {
1052 m_pullButton->SetLabel( wxString::Format( _( "Get Changes (%zu)" ), m_upstreamAhead ) );
1053 m_pullButton->SetToolTip( _( "The tracked branch has commits this project does not have." ) );
1054 }
1055 else
1056 {
1057 m_pullButton->SetLabel( _( "Get Changes" ) );
1058 m_pullButton->UnsetToolTip();
1059 }
1060
1061 bool hasCheckedChanges = !m_checklist->GetCheckedPaths().empty();
1062 bool amend = m_amendCheckbox->IsChecked();
1063 bool newBranch = !amend && m_newBranchCheckbox->IsChecked();
1064 bool hasMessage = !m_summary->GetValue().Trim().IsEmpty();
1065 bool hasBranchName = !newBranch || !m_newBranchName->GetValue().Trim().IsEmpty();
1066
1067 // An amend stays on the branch its commit is on.
1068 m_newBranchCheckbox->Enable( !amend );
1069 m_newBranchName->Enable( newBranch );
1070
1071 wxString mainLabel = _( "Commit" );
1072 wxString menuLabel = _( "Commit and Push" );
1073 bool mainEnabled = false;
1074 bool menuEnabled = false;
1075 m_commitButtonPushes = false;
1076
1077 // A disabled button with nothing said about it reads as broken, so each state the user can
1078 // act on names what it is waiting for.
1079 wxString blocked;
1080
1081 if( amend )
1082 {
1083 // A message-only amend needs no checked files, just a message.
1084 mainLabel = _( "Amend" );
1085 menuLabel = _( "Amend and Push" );
1086 mainEnabled = hasMessage && m_canAmend;
1087 menuEnabled = hasMessage && m_canAmend;
1088
1089 if( !m_canAmend )
1090 blocked = _( "This commit can no longer be amended. Untick Amend to start a new commit." );
1091 else if( !hasMessage )
1092 blocked = _( "Write a summary to amend the last commit." );
1093 }
1094 else if( hasCheckedChanges || m_editorsDirty )
1095 {
1096 // The commit button also starts saving unsaved editor changes for review.
1097 mainEnabled = hasMessage && hasBranchName;
1098 menuEnabled = hasMessage && hasBranchName;
1099
1100 if( !hasMessage )
1101 blocked = _( "Write a summary to commit." );
1102 else if( !hasBranchName )
1103 blocked = _( "Name the new branch, or untick Create a new branch." );
1104 }
1105 else if( m_hasUnpushedCommits )
1106 {
1107 if( m_unpushedCount )
1108 mainLabel = wxString::Format( _( "Push (%zu)" ), m_unpushedCount );
1109 else
1110 mainLabel = _( "Push" );
1111
1112 mainEnabled = true;
1113 m_commitButtonPushes = true;
1114 }
1115 else if( !m_shownPaths.empty() )
1116 {
1117 blocked = _( "Tick a file to commit it." );
1118 }
1119
1120 m_commitButton->SetLabel( mainLabel );
1121 m_commitButton->Enable( mainEnabled );
1122 m_commitAndPushItem->SetItemLabel( menuLabel );
1123 m_commitAndPushItem->Enable( menuEnabled );
1124
1125 // Unsaved editor changes are a fact about the commit the user is about to make, so this
1126 // goes beside the file list rather than only where there is nothing else to say.
1127 wxString reason;
1128
1129 if( m_editorsDirty )
1130 reason = _( "The open editors have unsaved changes. Committing offers to save them first." );
1131
1132 // A disabled control shows no tooltip, so the one line the panel has says why Get Changes
1133 // is off.
1135 {
1136 if( !reason.IsEmpty() )
1137 reason += wxS( "\n" );
1138
1139 reason += _( "This project has no remote, so there is nothing to get changes from or push to. "
1140 "Add one from the Remotes page of the Advanced Git window." );
1141 }
1142
1143 if( !blocked.IsEmpty() )
1144 {
1145 if( !reason.IsEmpty() )
1146 reason += wxS( "\n" );
1147
1148 reason += blocked;
1149 }
1150
1151 if( !reason.IsEmpty() )
1152 setStatusText( reason );
1153
1154 // With nothing listed the empty state owns the line and has already set its own text.
1155 bool showReason = !reason.IsEmpty() || m_shownPaths.empty();
1156
1157 if( m_emptyLabel->IsShown() != showReason )
1158 {
1159 m_emptyLabel->Show( showReason );
1160 Layout();
1161 }
1162
1163 // Pushing and pulling need a remote. Committing does not.
1164 m_pullButton->Enable( m_hasRemote );
1165}
1166
1167
1169{
1170 // Git tools show the first line whole up to 72 columns.
1171 int left = 72 - static_cast<int>( m_summary->GetValue().length() );
1172 m_summaryCount->SetLabel( wxString::Format( wxS( "%d" ), left ) );
1173
1174 // A count shown from the first character reads as a limit the user must work to
1175 bool show = m_summary->IsShown() && left <= 10;
1176
1177 if( m_summaryCount->IsShown() != show )
1178 {
1179 m_summaryCount->Show( show );
1180 Layout();
1181 }
1182}
1183
1184
1185void GIT_COMMIT_PANE::onMessageChanged( wxCommandEvent& aEvent )
1186{
1189
1192}
1193
1194
1196{
1197 return KIGIT::ComposeCommitMessage( m_summary->GetValue(), m_description->GetValue(), wxEmptyString );
1198}
1199
1200
1201void GIT_COMMIT_PANE::SetCommitMessage( const wxString& aMessage )
1202{
1203 wxString summary;
1204 wxString description;
1205
1206 KIGIT::SplitCommitMessage( aMessage, summary, description );
1207
1208 // ChangeValue rather than SetValue, so filling one form does not echo back into the other.
1209 m_summary->ChangeValue( summary );
1210 setDescription( description );
1213}
1214
1215
1216void GIT_COMMIT_PANE::onNewBranchToggled( wxCommandEvent& aEvent )
1217{
1219
1220 if( m_newBranchCheckbox->IsChecked() )
1221 m_newBranchName->SetFocus();
1222}
1223
1224
1225void GIT_COMMIT_PANE::onShowDiff( wxCommandEvent& aEvent )
1226{
1227 wxString path = m_checklist->GetItemPath( m_checklist->GetSelection() );
1228
1229 if( !path.IsEmpty() )
1231}
1232
1233
1235{
1236 m_branchName->SetLabel( wxEmptyString );
1237 m_branchRow->ShowItems( aStatus.hasRepo );
1238
1239 // The advanced window is reachable without a repository, as the old button was.
1240 m_settingsButton->Show();
1241
1242 if( !aStatus.hasRepo )
1243 return;
1244
1245 // This says where a commit will land. Switching branch is a different act, and it belongs
1246 // to the project tree and the advanced window, which is where the surfaces for it are.
1248
1249 wxString shown = m_currentBranch;
1250
1251 // Detached, or no commits yet, leaves no branch to name. Say which rather than show
1252 // nothing at all.
1253 if( shown.IsEmpty() )
1254 shown = m_headDetached ? _( "Not on a branch" ) : _( "No commits yet" );
1255
1256 m_branchName->SetLabel( shown );
1257 m_branchRow->Layout();
1258}
1259
1260
1261void GIT_COMMIT_PANE::populateRecentMessages( const std::vector<wxString>& aMessages )
1262{
1263 m_recentMessageTexts = aMessages;
1264
1265 // A dropdown always shows its selection, so the first entry is the caption.
1266 m_recentMessages->Clear();
1267 m_recentMessages->Append( _( "Recent messages" ) );
1268
1269 for( const wxString& message : m_recentMessageTexts )
1270 {
1271 wxString line = message.BeforeFirst( '\n' );
1272
1273 if( line.length() > 40 )
1274 line = line.Left( 37 ) + wxS( "..." );
1275
1276 m_recentMessages->Append( line );
1277 }
1278
1279 m_recentMessages->SetSelection( 0 );
1280}
1281
1282
1283void GIT_COMMIT_PANE::onRecentMessage( wxCommandEvent& aEvent )
1284{
1285 int picked = m_recentMessages->GetSelection() - 1;
1286 wxString summary, description;
1287
1288 // The caption entry starts the message over.
1289 if( picked >= 0 && picked < static_cast<int>( m_recentMessageTexts.size() ) )
1290 KIGIT::SplitCommitMessage( m_recentMessageTexts[picked], summary, description );
1291
1292 m_summary->SetValue( summary );
1293 setDescription( description );
1294 m_recentMessages->SetSelection( 0 );
1295}
1296
1297
1299{
1300 // Over the box's top left corner, where typed text would start.
1301 bool show = m_description->IsShown() && m_description->IsEmpty();
1302 wxPoint at = m_description->GetPosition() + wxPoint( FromDIP( 6 ), FromDIP( 4 ) );
1303
1304 if( m_descriptionHint->IsShown() != show )
1305 m_descriptionHint->Show( show );
1306
1307 if( m_descriptionHint->GetPosition() != at )
1308 m_descriptionHint->SetPosition( at );
1309}
1310
1311
1312void GIT_COMMIT_PANE::setDescription( const wxString& aText )
1313{
1314 m_description->ChangeValue( aText );
1316}
1317
1318
1319void GIT_COMMIT_PANE::onChecklistChanged( wxDataViewEvent& aEvent )
1320{
1322 updateSummary();
1323}
1324
1325
1327{
1328 // A ticked file is staged for the commit, an unticked one is left out.
1329 int staged = static_cast<int>( m_checklist->GetCheckedPaths().size() );
1330 int unstaged = static_cast<int>( m_shownPaths.size() ) - staged;
1331
1332 m_changesLabel->SetLabel( wxString::Format( _( "Changes to Commit (%d of %d)" ), staged,
1333 static_cast<int>( m_shownPaths.size() ) ) );
1334 m_showDiffButton->Enable( m_checklist->GetSelection().IsOk() );
1335
1336 if( m_summaryFiles )
1337 {
1338 wxString stagedText = wxString::Format(
1339 wxPLURAL( "%d file will be committed", "%d files will be committed", staged ), staged );
1340 wxString unstagedText = wxString::Format( wxPLURAL( "%d left out", "%d left out", unstaged ), unstaged );
1341
1342 m_summaryFiles->SetLabel( wxString::Format( wxS( "%s, %s" ), stagedText, unstagedText ) );
1343 m_summaryAdded->SetLabel( wxString::Format( wxS( "+%d" ), m_lineStats.first ) );
1344 m_summaryRemoved->SetLabel( wxString::Format( wxS( "-%d" ), m_lineStats.second ) );
1345 }
1346
1347 Layout();
1348}
1349
1350
1351void GIT_COMMIT_PANE::onChecklistContextMenu( wxDataViewEvent& aEvent )
1352{
1353 if( m_transfer.IsBusy() || m_actionPending )
1354 return;
1355
1356 wxString path = m_checklist->GetItemPath( aEvent.GetItem() );
1357
1358 if( path.IsEmpty() )
1359 return;
1360
1361 // The list holds only files, so the target is never a directory.
1362 GIT_IGNORE_TARGET target;
1363
1364 // Git keeps tracking a file it already knows, so ignoring is only offered for one it does not.
1365 bool canIgnore = false;
1366
1367 {
1368 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
1369 std::unique_lock<std::mutex> lock = common->TryLockAction();
1370
1371 if( lock.owns_lock() )
1372 {
1373 const std::optional<wxString> prefix = common->GetProjectPrefix();
1374
1375 if( prefix && path.StartsWith( *prefix ) )
1376 target.path = path.Mid( prefix->length() );
1377
1378 canIgnore = !target.path.IsEmpty() && !KIGIT::IgnoreState( *common, target.path, false ).tracked;
1379 }
1380 }
1381
1382 const wxString extensionRule = KIGIT::ExtensionIgnoreRule( target.path );
1383
1384 wxMenu menu;
1385 menu.Append( 1, _( "Show History for This File" ) );
1386 menu.AppendSeparator();
1387 menu.Append( 2, _( "Discard Changes" ) );
1388
1389 if( canIgnore )
1390 {
1391 menu.AppendSeparator();
1392 menu.Append( 3, _( "Ignore This File" ) );
1393
1394 if( !extensionRule.IsEmpty() )
1395 menu.Append( 4, wxString::Format( _( "Ignore All '%s' Files" ), extensionRule ) );
1396 }
1397
1398 switch( GetPopupMenuSelectionFromUser( menu ) )
1399 {
1400 case 1:
1401 // From the Changes page the window is already open, so it only turns to History.
1403 dialog->ShowHistoryForFile( path );
1404 else
1406
1407 break;
1408
1409 case 2:
1410 discardFile( m_frame->Prj().GetGitCommon(), path );
1411 break;
1412
1413 case 3: ChangeGitIgnore( m_frame, this, GIT_IGNORE_CHANGE::IGNORE_PATH, { target } ); break;
1414
1415 case 4: ChangeGitIgnore( m_frame, this, GIT_IGNORE_CHANGE::IGNORE_EXTENSION, { target } ); break;
1416
1417 default:
1418 break;
1419 }
1420}
1421
1422
1423void GIT_COMMIT_PANE::discardFile( std::shared_ptr<KIGIT_COMMON> aCommon, const wxString& aPath )
1424{
1425 struct FILE_STATE
1426 {
1427 bool tracked = false;
1428 bool conflicted = false;
1429 wxString root;
1430 };
1431
1432 auto state = std::make_shared<FILE_STATE>();
1433
1435 aCommon,
1436 [state, aPath]( KIGIT_COMMON& aSession )
1437 {
1438 state->tracked = aSession.IsPathInHead( aPath );
1439 state->conflicted = aSession.IsPathConflicted( aPath );
1440 state->root = aSession.GetGitRootDirectory();
1441 },
1442 [this, aCommon, aPath, state]()
1443 {
1444 confirmDiscardFile( aCommon, aPath, state->tracked, state->conflicted, state->root );
1445 },
1446 _( "Checking changes..." ) );
1447}
1448
1449
1450void GIT_COMMIT_PANE::confirmDiscardFile( std::shared_ptr<KIGIT_COMMON> aCommon, const wxString& aPath, bool aTracked,
1451 bool aConflicted, wxString aRoot )
1452{
1453 // An unsaved editor's next save would undo the discard, so settle that first.
1454 if( EditorsDirty( m_frame->Kiway() ) )
1455 {
1456 DisplayInfoMessage( this, _( "An editor has unsaved changes. Save or revert them before discarding "
1457 "files, so the discard is not undone by the next save." ) );
1458 return;
1459 }
1460
1461 wxString name = wxFileName( aPath ).GetFullName();
1462 wxString question;
1463
1464 if( aConflicted )
1465 {
1466 // Putting back what HEAD holds also clears the conflict, so the file is settled rather
1467 // than only reverted.
1468 question = wxString::Format( _( "Resolve the conflict in '%s' by going back to the version this "
1469 "project was on?\n\n"
1470 "The version that arrived is dropped, and the file no longer needs "
1471 "resolving." ),
1472 name );
1473 }
1474 else if( aTracked )
1475 {
1476 question = wxString::Format( _( "Throw away the changes to '%s'?\n\n"
1477 "The file goes back to the last committed version." ),
1478 name );
1479 }
1480 else
1481 {
1482 question = wxString::Format( _( "Move '%s' to the trash?\n\n"
1483 "It has never been committed, so there is no version to bring back." ),
1484 name );
1485 }
1486
1487 wxMessageDialog dlg( this, question, _( "Discard Changes" ), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING );
1488 dlg.SetYesNoLabels( aConflicted ? _( "Resolve" )
1489 : aTracked ? _( "Discard" )
1490 : _( "Move to Trash" ),
1491 _( "Cancel" ) );
1492
1493 if( dlg.ShowModal() != wxID_YES )
1494 return;
1495
1496 if( aCommon != m_frame->Prj().GetGitCommon() || aCommon->IsShuttingDown() )
1497 return;
1498
1499 if( EditorsDirty( m_frame->Kiway() ) )
1500 return;
1501
1502 // Snapshot first, so an editor showing the file reloads the committed version afterwards.
1503 EDITOR_SNAPSHOT docsBefore = CaptureOpenEditorDocs( m_frame->Kiway() );
1504
1505 // Dropping the staged entry before touching the file means a contended lock or an index
1506 // failure leaves everything unchanged.
1507 std::unique_lock<std::mutex> lock = KIGIT::TryLockAction( *aCommon, this );
1508
1509 if( !lock.owns_lock() )
1510 return;
1511
1512 // The question above ran without the lock, so the project may have closed meanwhile.
1513 if( !aCommon->GetRepo() )
1514 return;
1515
1516 wxString error;
1517
1518 if( !aCommon->DiscardChanges( { aPath }, error ) )
1519 {
1520 lock.unlock();
1521 DisplayErrorMessage( this, wxString::Format( _( "Could not discard the changes to '%s'." ), name ),
1522 error );
1523 return;
1524 }
1525
1526 lock.unlock();
1527
1528 if( !aTracked )
1529 {
1530 if( !aRoot.EndsWith( wxS( "/" ) ) )
1531 aRoot += wxS( "/" );
1532
1533 wxFileName fullPath( aRoot + aPath );
1534
1535 // A previous discard can have removed the file already, so a missing file is done,
1536 // not an error.
1537 if( fullPath.FileExists() && !KIPLATFORM::ENV::MoveToTrash( fullPath.GetFullPath(), error ) )
1538 {
1539 // The staged entry is already gone, so the panels still refresh.
1540 aCommon->NotifyRefreshListeners();
1541 DisplayErrorMessage( this,
1542 wxString::Format( _( "Could not move '%s' to the trash. The file is "
1543 "still on disk, so discard it again to retry." ),
1544 name ),
1545 error );
1546 return;
1547 }
1548 }
1549
1550 ReloadOpenEditors( m_frame->Kiway(), docsBefore );
1551 aCommon->NotifyRefreshListeners();
1552}
1553
1554
1555void GIT_COMMIT_PANE::onFileActivated( wxDataViewEvent& aEvent )
1556{
1557 wxString path = m_checklist->GetItemPath( aEvent.GetItem() );
1558
1559 if( !path.IsEmpty() )
1561}
1562
1563
1564void GIT_COMMIT_PANE::onCommit( wxCommandEvent& aEvent )
1565{
1567}
1568
1569
1570void GIT_COMMIT_PANE::onCommitAndPush( wxCommandEvent& aEvent )
1571{
1572 doCommit( true );
1573}
1574
1575
1576void GIT_COMMIT_PANE::onPull( wxCommandEvent& aEvent )
1577{
1578 syncListener();
1579
1580 // The button reads Cancel for another window's transfer, which only its owner can stop
1581 if( othersBusy() && !m_transfer.IsBusy() )
1582 {
1583 if( othersCanCancel() )
1584 {
1585 // Before the calls, which may end the transfers and restore the button
1586 m_pullButton->Enable( false );
1587 transfers().CancelAll();
1588 }
1589
1590 return;
1591 }
1592
1593 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
1594
1595 if( !common->GetRepo() )
1596 return;
1597
1598 if( m_actionPending )
1599 {
1601 m_actionQuery.Cancel();
1602 m_actionPending = false;
1603 setBusy( false, _( "Cancelled." ) );
1604 return;
1605 }
1606
1607 // While a transfer runs this button reads Cancel. The transfer callbacks poll the flag and
1608 // abort on their next tick, and the completion then reports the cancellation. A stalled
1609 // connection runs no callbacks until it times out, so the cancel cannot be prompt.
1610 if( m_transfer.IsBusy() )
1611 {
1612 m_transfer.Cancel();
1613
1614 m_pullButton->Enable( false );
1615
1616 // The one Cancel button stops the other windows' transfers as well
1617 transfers().CancelAll();
1618
1619 m_frame->SetStatusText( _( "Cancelling. A stalled connection stops only when it times out." ) );
1620 return;
1621 }
1622
1624 {
1625 abandonOperation( common );
1626 return;
1627 }
1628
1629 Pull();
1630}
1631
1632
1634{
1635 // The Advanced window also calls this, with the panel's status out of sight.
1636 if( m_transfer.IsBusy() || othersBusy() || m_actionPending )
1637 {
1638 KIGIT::ShowBusyMessage( this );
1639 return false;
1640 }
1641
1643 {
1644 DisplayInfoMessage( this, wxString::Format( _( "Finish or abandon the %s in progress first." ),
1645 operationNoun() ) );
1646 return false;
1647 }
1648
1649 // The panel disables its own buttons for this, but the advanced window's reach here too.
1650 if( m_headDetached )
1651 {
1652 DisplayInfoMessage( this, _( "This project is showing an old snapshot rather than a branch, so it cannot be "
1653 "committed or pushed from here. In the Advanced Git window, choose Branches "
1654 "and double click a branch to go back to it." ) );
1655 return false;
1656 }
1657
1658 return true;
1659}
1660
1661
1663{
1664 syncListener();
1665
1666 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
1667
1668 if( !common->GetRepo() || !transferCanStart() )
1669 return;
1670
1671 if( !m_hasRemote )
1672 {
1673 DisplayInfoMessage( this, _( "No remote is configured to get changes from." ) );
1674 return;
1675 }
1676
1678 submitPull( common, false );
1679}
1680
1681
1683{
1684 syncListener();
1685
1686 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
1687
1688 if( !common->GetRepo() || !transferCanStart() )
1689 return;
1690
1691 if( !m_hasRemote )
1692 {
1693 DisplayInfoMessage( this, _( "No remote is configured to push to." ) );
1694 return;
1695 }
1696
1698 {
1699 DisplayInfoMessage( this, _( "There are no commits to push." ) );
1700 return;
1701 }
1702
1704 submitPush( common );
1705}
1706
1707
1708void GIT_COMMIT_PANE::abandonOperation( std::shared_ptr<KIGIT_COMMON> aCommon )
1709{
1710 struct PREPARATION
1711 {
1712 std::vector<wxString> outside;
1713 bool ready = false;
1714 };
1715
1716 auto preparation = std::make_shared<PREPARATION>();
1717 const wxString projectPath = m_frame->Prj().GetProjectPath();
1718
1720 aCommon,
1721 [preparation, projectPath]( KIGIT_COMMON& aSession )
1722 {
1723 // Going back to the last commit covers the whole repository, so work in a
1724 // sibling project has to be named before the user agrees.
1725 preparation->outside = ChangedTrackedFilesOutsideProject( aSession, projectPath );
1726 preparation->ready = true;
1727 },
1728 [this, aCommon, preparation]()
1729 {
1730 if( preparation->ready )
1731 finishAbandonOperation( aCommon, preparation->outside );
1732 },
1733 _( "Checking working files..." ) );
1734}
1735
1736
1737void GIT_COMMIT_PANE::finishAbandonOperation( std::shared_ptr<KIGIT_COMMON> aCommon,
1738 const std::vector<wxString>& aOutside )
1739{
1740 // Saving would only turn unsaved edits into changes that are then thrown away, so ask for
1741 // a decision in the editors first rather than offer a save.
1742 auto canAbandon = [this, aCommon]()
1743 {
1744 if( aCommon != m_frame->Prj().GetGitCommon() || aCommon->IsShuttingDown()
1745 || !Pgm().GetCommonSettings()->m_Git.enableGit )
1746 {
1747 return false;
1748 }
1749
1750 if( EditorsDirty( m_frame->Kiway() ) )
1751 {
1752 DisplayInfoMessage( this, _( "The open editors have unsaved changes. Save or revert them first, so it "
1753 "is clear what is being abandoned." ) );
1754 return false;
1755 }
1756
1757 return true;
1758 };
1759
1760 if( !canAbandon() )
1761 return;
1762
1763 wxString question = wxString::Format( _( "Abandon the %s and go back to the last commit?\n\n"
1764 "Changes made to the files since that commit are discarded." ),
1765 operationNoun() );
1766
1767 if( !aOutside.empty() )
1768 {
1769 wxString listed;
1770
1771 for( const wxString& path : aOutside )
1772 listed += wxS( "\n " ) + path;
1773
1774 question += wxString::Format( _( "\n\nThis also discards uncommitted changes elsewhere in this "
1775 "repository:%s" ),
1776 listed );
1777 }
1778
1779 if( !IsOK( this, question ) || !canAbandon() )
1780 return;
1781
1782 EDITOR_SNAPSHOT docsBefore = CaptureOpenEditorDocs( m_frame->Kiway() );
1783 wxString error;
1784 bool ok = false;
1785
1786 {
1787 std::unique_lock<std::mutex> lock = KIGIT::TryLockAction( *aCommon, this );
1788
1789 if( !lock.owns_lock() )
1790 return;
1791
1792 ok = aCommon->AbandonOperation( error );
1793 }
1794
1795 if( !ok )
1796 {
1797 DisplayErrorMessage( this, wxString::Format( _( "Could not abandon the %s." ), operationNoun() ), error );
1798 return;
1799 }
1800
1801 ReloadOpenEditors( m_frame->Kiway(), docsBefore );
1802 aCommon->NotifyRefreshListeners();
1803 setBusy( false, _( "Back at the last commit." ) );
1804}
1805
1806
1807void GIT_COMMIT_PANE::onAmendToggled( wxCommandEvent& aEvent )
1808{
1809 if( m_amendCheckbox->IsChecked() )
1810 {
1811 BeginAmend();
1812 return;
1813 }
1814
1815 m_amendHead = {};
1817 Layout();
1819}
1820
1821
1822void GIT_COMMIT_PANE::onUndoCommit( wxCommandEvent& aEvent )
1823{
1824 syncListener();
1825
1826 if( m_actionPending || m_transfer.IsBusy() || othersBusy() )
1827 {
1828 KIGIT::ShowBusyMessage( this );
1829 return;
1830 }
1831
1832 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
1833 git_oid expectedHead;
1834
1835 if( !common->GetRepo() || git_oid_fromstr( &expectedHead, m_undoHead.second.utf8_string().c_str() ) != GIT_OK )
1836 return;
1837
1839 KIGIT_ERROR_MESSAGE error;
1840 wxString message;
1841
1842 {
1843 std::unique_lock<std::mutex> lock = KIGIT::TryLockAction( *common, this );
1844
1845 if( !lock.owns_lock() )
1846 return;
1847
1848 GIT_COMMIT_HANDLER commitHandler( common->GetRepo() );
1849 result = commitHandler.PerformUndoLastCommit( m_undoHead.first, expectedHead, message );
1850 error = commitHandler.PopError();
1851 }
1852
1853 common->NotifyRefreshListeners();
1854
1855 switch( result )
1856 {
1858 {
1859 m_amendCheckbox->SetValue( false );
1860 m_amendHead = {};
1861 m_newBranchCheckbox->SetValue( false );
1862 m_newBranchName->Clear();
1863
1864 wxString summary, description;
1865 KIGIT::SplitCommitMessage( message, summary, description );
1866
1867 wxString restored = KIGIT::ComposeCommitMessage( summary, description, wxEmptyString );
1868 wxString draft = GetCommitMessage();
1869 wxWeakRef<GIT_COMMIT_PANE> pane( this );
1870
1871 if( !draft.IsEmpty() && draft != restored
1872 && !IsOK( this, _( "Replace the current commit message with the undone commit's message?" ) ) )
1873 {
1874 if( pane && !pane->IsBeingDeleted() )
1875 {
1876 setBusy( false, _( "Undid the last commit. Its changes are back in the list, and your message was "
1877 "kept." ) );
1878 }
1879
1880 break;
1881 }
1882
1883 if( !pane || pane->IsBeingDeleted() )
1884 break;
1885
1886 SetCommitMessage( restored );
1887
1890
1891 setBusy( false, _( "Undid the last commit. Its changes are back in the list, ready to commit again." ) );
1892 break;
1893 }
1894
1896 DisplayInfoMessage( this, wxString::Format( _( "This commit is already on the remote branch %s, so undoing "
1897 "it here would rewrite history others may have. Make a new "
1898 "commit that fixes it instead." ),
1899 message ) );
1900 break;
1901
1903 DisplayInfoMessage( this, _( "The branch or its last commit changed. Review the latest commit and try "
1904 "again." ) );
1905 break;
1906
1907 case UndoCommitResult::NoCommit: DisplayInfoMessage( this, _( "This branch has no commit to undo." ) ); break;
1908
1910 DisplayErrorMessage( this, error.summary.IsEmpty() ? _( "Could not undo the commit." ) : error.summary,
1911 error.details );
1912 break;
1913 }
1914}
1915
1916
1917void GIT_COMMIT_PANE::BeginAmend( const wxString& aExpectedCommit )
1918{
1919 struct AMEND_INFO
1920 {
1921 std::pair<wxString, wxString> head;
1922 wxString message;
1923 wxString refusal;
1924 };
1925
1926 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
1927 auto info = std::make_shared<AMEND_INFO>();
1928
1930 common,
1931 [info, aExpectedCommit]( KIGIT_COMMON& aSession )
1932 {
1933 info->head = commitHead( aSession.GetRepo() );
1934 info->refusal = amendRefusal( aSession, info->head );
1935
1936 if( !aExpectedCommit.IsEmpty() && aExpectedCommit != info->head.second )
1937 info->refusal = _( "The selected commit is no longer the last commit on this branch." );
1938
1939 if( info->refusal.IsEmpty() )
1940 {
1941 wxString summary, description;
1942 KIGIT::SplitCommitMessage( aSession.GetLastCommitMessage(), summary, description );
1943 info->message = KIGIT::ComposeCommitMessage( summary, description, wxEmptyString );
1944 }
1945 },
1946 [this, common, info, aExpectedCommit]()
1947 {
1948 if( !info->refusal.IsEmpty() )
1949 {
1950 if( m_amendHead.second.IsEmpty() )
1951 m_amendCheckbox->SetValue( false );
1952
1954 DisplayInfoMessage( this, info->refusal );
1955 return;
1956 }
1957
1958 bool fromHistory = !aExpectedCommit.IsEmpty();
1959 wxString draft = GetCommitMessage();
1960 wxWeakRef<GIT_COMMIT_PANE> pane( this );
1961 wxWeakRef<EDA_BASE_FRAME> frame( m_frame );
1962
1963 if( fromHistory && !draft.IsEmpty() && draft != info->message
1964 && !IsOK( this, _( "Replace the current commit message with the selected commit's message?" ) ) )
1965 {
1966 return;
1967 }
1968
1969 if( !pane || pane->IsBeingDeleted() || !frame || frame->IsBeingDeleted()
1970 || common != frame->Prj().GetGitCommon() || common->IsShuttingDown()
1971 || !Pgm().GetCommonSettings()->m_Git.enableGit
1972 || frame->Prj().GetLocalSettings().m_GitIntegrationDisabled )
1973 {
1974 return;
1975 }
1976
1977 if( GetCommitMessage() != draft )
1978 return;
1979
1980 m_canAmend = true;
1981 m_amendHead = info->head;
1982 m_amendCheckbox->SetValue( true );
1983 m_newBranchCheckbox->SetValue( false );
1984
1985 // History starts with a message-only amend. Files can be selected on this form.
1986 if( fromHistory )
1987 m_checklist->SetAllChecked( false );
1988
1989 // Keep a draft when the user ticks Amend while composing a message.
1990 if( fromHistory || draft.IsEmpty() )
1991 {
1992 SetCommitMessage( info->message );
1993
1996 }
1997
1999 Layout();
2001 m_summary->SetFocus();
2002 },
2003 _( "Reading last commit..." ) );
2004}
2005
2006
2008{
2010 bool amend = false;
2011 bool newBranch = false;
2012 bool andPush = false;
2013 bool signOff = false;
2015 wxString branchName;
2016 wxString summary;
2017 wxString description;
2018 wxString lfsMessage;
2020 std::vector<wxString> files;
2021 std::pair<wxString, wxString> head;
2022};
2023
2024
2025void GIT_COMMIT_PANE::doCommit( bool aAndPush )
2026{
2027 syncListener();
2028
2029 if( !m_hasRepo )
2030 return;
2031
2032 if( m_actionPending || m_transfer.IsBusy() || othersBusy() )
2033 {
2034 KIGIT::ShowBusyMessage( this );
2035 return;
2036 }
2037
2038 std::shared_ptr<KIGIT_COMMON> common = m_frame->Prj().GetGitCommon();
2039
2040 if( !common->GetRepo() )
2041 return;
2042
2043 const bool amend = m_amendCheckbox->IsChecked();
2044 const bool newBranch = !amend && m_newBranchCheckbox->IsChecked();
2045 wxString branchName = m_newBranchName->GetValue();
2046 branchName.Trim( true ).Trim( false );
2047
2048 if( newBranch )
2049 {
2050 if( wxString nameError = KIGIT::BranchNameError( branchName ); !nameError.IsEmpty() )
2051 {
2052 DisplayErrorMessage( this, nameError );
2053 m_newBranchName->SetFocus();
2054 return;
2055 }
2056 }
2057
2058 std::vector<wxString> files = m_checklist->GetCheckedPaths();
2059
2060 // Unsaved editor changes can be saved for review. With only local commits waiting,
2061 // the button reads "Push".
2062 if( files.empty() && !amend && !DocumentEditorsDirty( m_frame->Kiway() ) )
2063 {
2064 if( !aAndPush || !m_hasUnpushedCommits )
2065 return;
2066
2068 submitPush( common );
2069 return;
2070 }
2071
2072 auto request = std::make_shared<COMMIT_REQUEST>();
2073 request->amend = amend;
2074 request->head = m_amendHead;
2075 request->newBranch = newBranch;
2076 request->andPush = aAndPush;
2077 request->signOff = m_signOffCheckbox->IsChecked();
2078 request->branchName = branchName;
2079 request->displayedBranch = m_currentBranch;
2080 request->summary = m_summary->GetValue();
2081 request->description = m_description->GetValue();
2082 request->files = std::move( files );
2083
2085 common,
2086 [request]( KIGIT_COMMON& aCommon )
2087 {
2088 if( request->amend )
2089 request->amendRefusal = amendRefusal( aCommon, request->head );
2090 else
2091 request->head = commitHead( aCommon.GetRepo() );
2092
2093 request->identity = KIGIT::ReadGitIdentity( aCommon );
2094 request->lfsMessage = KIGIT::PROJECT_GIT_UTILS::LfsRefusal( &aCommon );
2095 },
2096 [this, common, request]()
2097 {
2098 saveForCommit( common, request );
2099 },
2100 _( "Checking changes..." ) );
2101}
2102
2103
2104void GIT_COMMIT_PANE::saveForCommit( std::shared_ptr<KIGIT_COMMON> aCommon, std::shared_ptr<COMMIT_REQUEST> aRequest )
2105{
2106 if( !aRequest->amendRefusal.IsEmpty() )
2107 {
2108 DisplayInfoMessage( this, aRequest->amendRefusal );
2109 aCommon->NotifyRefreshListeners();
2110 return;
2111 }
2112
2113 if( !aRequest->displayedBranch.IsEmpty()
2114 && aRequest->head.first != wxS( "refs/heads/" ) + aRequest->displayedBranch )
2115 {
2116 DisplayInfoMessage( this, _( "The branch changed while preparing the commit. "
2117 "Review the changes and commit again." ) );
2118 aCommon->NotifyRefreshListeners();
2119 return;
2120 }
2121
2122 if( !aRequest->lfsMessage.IsEmpty() )
2123 {
2124 DisplayErrorMessage( this, aRequest->lfsMessage );
2125 return;
2126 }
2127
2128 bool saved = false;
2129
2131 return;
2132
2133 if( aCommon != m_frame->Prj().GetGitCommon() || aCommon->IsShuttingDown() )
2134 return;
2135
2136 if( saved )
2137 {
2138 // Saving can change which files belong in the commit. Show them before committing.
2139 aCommon->NotifyRefreshListeners();
2140 return;
2141 }
2142
2143 finishCommit( aCommon, *aRequest );
2144}
2145
2146
2147void GIT_COMMIT_PANE::finishCommit( std::shared_ptr<KIGIT_COMMON> common, const COMMIT_REQUEST& aRequest )
2148{
2149 const std::vector<wxString>& files = aRequest.files;
2150 const bool amend = aRequest.amend;
2151 const bool newBranch = aRequest.newBranch;
2152 const wxString& branchName = aRequest.branchName;
2153
2154 // Entered on the strength of unsaved editor changes alone, but the user declined the save,
2155 // so nothing reached the working tree and there is nothing to commit.
2156 if( files.empty() && !amend )
2157 {
2158 setBusy( false, _( "Nothing was saved, so there is nothing to commit." ) );
2159 return;
2160 }
2161
2162 // A fresh machine has no git identity yet, and the commit cannot be recorded without one.
2163 if( !KIGIT::EnsureGitIdentity( this, m_frame, common, aRequest.identity ) )
2164 return;
2165
2166 if( common != m_frame->Prj().GetGitCommon() || common->IsShuttingDown() )
2167 return;
2168
2170 KIGIT_ERROR_MESSAGE error;
2171 wxString branchError;
2172 wxString branchDetail;
2173 wxString previousBranch;
2174
2175 {
2176 // Keep the lock through branch creation and the commit. Closing the identity prompt wakes a
2177 // status read, so a bare try loses to it
2178 std::unique_lock<std::mutex> lock = KIGIT::WaitForActionLock( *common, this );
2179
2180 if( !lock.owns_lock() )
2181 return;
2182
2183 if( aRequest.head != commitHead( common->GetRepo() ) )
2184 {
2185 lock.unlock();
2186 DisplayInfoMessage( this, _( "The branch or its last commit changed while preparing the commit. "
2187 "Review the changes and commit again." ) );
2188 common->NotifyRefreshListeners();
2189 return;
2190 }
2191
2192 if( amend )
2193 {
2194 wxString refusal = amendRefusal( *common, aRequest.head );
2195
2196 if( !refusal.IsEmpty() )
2197 {
2198 lock.unlock();
2199 DisplayInfoMessage( this, refusal );
2200 common->NotifyRefreshListeners();
2201 return;
2202 }
2203 }
2204
2205 GIT_CONFIG_HANDLER configHandler( common.get() );
2206 GitUserConfig userConfig = configHandler.GetUserConfig();
2207 wxString signOff;
2208
2209 if( aRequest.signOff )
2210 signOff = wxString::Format( wxS( "%s <%s>" ), userConfig.authorName, userConfig.authorEmail );
2211
2212 wxString message = KIGIT::ComposeCommitMessage( aRequest.summary, aRequest.description, signOff );
2213
2214 // The new branch starts at HEAD, so switching to it leaves the working tree as it is.
2215 if( newBranch )
2216 previousBranch = common->GetCurrentBranchName();
2217
2218 if( !newBranch || moveToNewBranch( *common, branchName, branchError, branchDetail ) )
2219 {
2220 GIT_COMMIT_HANDLER commitHandler( common->GetRepo() );
2221
2222 if( amend )
2223 result = commitHandler.PerformAmend( files, message, userConfig.authorName, userConfig.authorEmail );
2224 else
2225 result = commitHandler.PerformCommit( files, message, userConfig.authorName, userConfig.authorEmail );
2226
2227 error = commitHandler.PopError();
2228
2230
2231 // A failed commit must not leave the project on an empty new branch.
2232 if( newBranch && !committed )
2233 dropNewBranch( *common, branchName, previousBranch );
2234 }
2235 }
2236
2237 if( !branchError.IsEmpty() )
2238 {
2239 DisplayErrorMessage( this, branchError, branchDetail );
2240 return;
2241 }
2242
2243 // The commit exists on this path, so saying it failed would invite a second one.
2245 {
2246 DisplayInfoMessage( this, error.summary, error.details );
2247 }
2248 else if( result != CommitResult::Success )
2249 {
2250 DisplayErrorMessage( this, error.summary.IsEmpty() ? _( "Could not create the commit." ) : error.summary,
2251 error.details );
2252 return;
2253 }
2254
2255 // The other commit pane can still edit the shared message while this one is preparing.
2256 if( m_summary->GetValue() == aRequest.summary && m_description->GetValue() == aRequest.description )
2257 {
2258 m_summary->Clear();
2259 setDescription( wxEmptyString );
2260 }
2261 m_amendCheckbox->SetValue( false );
2262 m_amendHead = {};
2263 m_newBranchCheckbox->SetValue( false );
2264 m_newBranchName->Clear();
2265 common->NotifyRefreshListeners();
2266
2267 if( aRequest.andPush )
2268 {
2270 submitPush( common );
2271 }
2272 else
2273 setBusy( false, _( "Committed." ) );
2274}
2275
2276
2277void GIT_COMMIT_PANE::runActionQuery( std::shared_ptr<KIGIT_COMMON> aCommon, std::function<void( KIGIT_COMMON& )> aWork,
2278 std::function<void()> aDone, const wxString& aStatus )
2279{
2280 if( m_actionPending || m_transfer.IsBusy() || othersBusy() )
2281 {
2282 // A finished transfer's follow-up must still end its hold and hand the controls over
2283 if( !m_actionPending && !m_transfer.IsBusy() )
2284 setBusy( false, wxEmptyString );
2285
2286 KIGIT::ShowBusyMessage( this );
2287 return;
2288 }
2289
2290 m_actionPending = true;
2291 setBusy( true, aStatus );
2292 auto read = std::make_shared<bool>( false );
2293
2294 m_actionQuery.Run(
2295 aCommon,
2296 [read, work = std::move( aWork )]( KIGIT_COMMON& aSession )
2297 {
2298 work( aSession );
2299 *read = true;
2300 },
2301 [this, aCommon, read, done = std::move( aDone )]()
2302 {
2303 m_actionPending = false;
2304
2305 // Hands the controls to another window's transfer that started meanwhile
2306 setBusy( false, wxEmptyString );
2307
2308 if( othersBusy() )
2309 {
2310 KIGIT::ShowBusyMessage( this );
2311 return;
2312 }
2313
2314 if( *read && aCommon == m_frame->Prj().GetGitCommon() && !aCommon->IsShuttingDown()
2315 && aCommon->GetRepo() && Pgm().GetCommonSettings()->m_Git.enableGit )
2316 {
2317 done();
2318 }
2319 } );
2320}
2321
2322
2324{
2325 // The project keeps its session alive, so the reference outlives the temporary
2326 return m_frame->Prj().GetGitCommon()->Transfers();
2327}
2328
2329
2331{
2332 return transfers().IsBusy( m_ownHold );
2333}
2334
2335
2337{
2338 return transfers().Status( m_ownHold );
2339}
2340
2341
2343{
2344 return transfers().CanCancel( m_ownHold );
2345}
2346
2347
2349{
2350 // This pane's own transfer keeps the controls, and only the status line follows the others
2351 if( m_transfer.IsBusy() )
2352 {
2353 m_frame->SetStatusText( othersBusy() ? othersStatus() : m_transferStatus );
2354 return;
2355 }
2356
2357 if( othersBusy() )
2358 {
2359 m_showingOthers = true;
2360 setBusy( true, othersStatus() );
2361 m_pullButton->Enable( othersCanCancel() );
2362 return;
2363 }
2364
2365 // A pending action of this pane's own keeps the controls and its Cancel
2366 if( std::exchange( m_showingOthers, false ) )
2367 setBusy( m_actionPending, wxEmptyString );
2368}
2369
2370
2371void GIT_COMMIT_PANE::ShowTransferProgress( const wxString& aText )
2372{
2373 m_frame->SetStatusText( aText );
2374}
2375
2376
2377void GIT_COMMIT_PANE::setBusy( bool aBusy, const wxString& aStatus )
2378{
2379 if( !aBusy )
2380 m_ownHold.Release();
2381
2382 // Another window's transfer keeps the pane busy until its owner ends it, and its status replaces
2383 // whatever this pane's own work showed
2384 if( !aBusy && othersBusy() )
2385 {
2386 m_showingOthers = true;
2387 setBusy( true, othersStatus() );
2388 m_pullButton->Enable( othersCanCancel() );
2389 return;
2390 }
2391
2392 m_checklist->Enable( !aBusy );
2393 m_commitButton->Enable( !aBusy );
2394 m_amendCheckbox->Enable( !aBusy );
2395 m_undoCommitButton->Enable( !aBusy && m_canAmend );
2396 m_signOffCheckbox->Enable( !aBusy );
2397 m_newBranchCheckbox->Enable( !aBusy );
2398 m_newBranchName->Enable( !aBusy && m_newBranchCheckbox->IsChecked() );
2399 m_recentMessages->Enable( !aBusy );
2400 m_summary->Enable( !aBusy );
2401 m_description->Enable( !aBusy );
2402 m_frame->SetStatusText( aStatus );
2403
2404 // The frame status bar is overwritten within seconds by the editors, so an outcome shown
2405 // with the empty label also goes to the panel's own label, where it stays.
2406 if( !aBusy && !aStatus.IsEmpty() && m_emptyLabel->IsShown() && !m_headDetached && !m_operationInProgress )
2407 setStatusText( aStatus );
2408
2410 m_busyChangedHandler( aBusy );
2411
2412 // While a transfer runs, the network button turns into its cancel control.
2413 if( aBusy )
2414 {
2415 m_pullButton->SetLabel( _( "Cancel" ) );
2416 m_pullButton->Enable( true );
2417 }
2418 else
2419 {
2420 m_pullButton->SetLabel( _( "Get Changes" ) );
2422 }
2423}
2424
2425
2426bool GIT_COMMIT_PANE::deferForSecret( const std::shared_ptr<KIGIT_COMMON>& aCommon, const wxString& aStatus,
2427 std::function<void()> aStart )
2428{
2429 if( aCommon->SecretRead() )
2430 return false;
2431
2432 // Busy and cancellable through the read, as the transfer it stands for would be
2433 unsigned request = ++m_keyringRequest;
2434 m_keyringWait = true;
2435 m_actionPending = true;
2436 setBusy( true, aStatus );
2437 m_ownHold.Begin( aCommon, aStatus,
2438 [this]()
2439 {
2441 } );
2442
2443 bool deferred = KIGIT_COMMON::DeferForSecret( aCommon, m_transfer.Alive(),
2444 [this, aCommon, request, start = std::move( aStart )]()
2445 {
2446 if( request != m_keyringRequest || !m_keyringWait )
2447 return;
2448
2449 m_keyringWait = false;
2450 m_actionPending = false;
2451
2452 if( aCommon != m_frame->Prj().GetGitCommon()
2453 || aCommon->IsShuttingDown() )
2454 {
2455 setBusy( false, wxEmptyString );
2456 return;
2457 }
2458
2459 start();
2460 } );
2461
2462 if( !deferred && request == m_keyringRequest )
2463 {
2464 m_keyringWait = false;
2465 m_actionPending = false;
2466 }
2467
2468 return deferred;
2469}
2470
2471
2473{
2474 if( !std::exchange( m_keyringWait, false ) )
2475 return false;
2476
2477 // The read still finishes, and its answer is kept, but nothing starts from it
2479 return true;
2480}
2481
2482
2484{
2485 if( !dropKeyringWait() )
2486 return;
2487
2488 m_actionPending = false;
2489 setBusy( false, _( "Cancelled." ) );
2490}
2491
2492
2493void GIT_COMMIT_PANE::submitPush( std::shared_ptr<KIGIT_COMMON> aCommon, bool aRetriedAfterTrust )
2494{
2495 struct TARGET
2496 {
2497 bool hasRemote = false;
2498 wxString branch;
2499 wxString head;
2500 };
2501
2502 auto target = std::make_shared<TARGET>();
2503
2505 aCommon,
2506 [target]( KIGIT_COMMON& aSession )
2507 {
2508 target->hasRemote = aSession.HasPushAndPullRemote();
2509 target->branch = aSession.GetCurrentBranchName();
2510 target->head = aSession.GetHeadCommitId();
2511 },
2512 [this, aCommon, target, aRetriedAfterTrust]()
2513 {
2514 if( !target->hasRemote )
2515 {
2516 setBusy( false, _( "Committed. No remote is configured to push to." ) );
2517 aCommon->NotifyRefreshListeners();
2518 return;
2519 }
2520
2521 startPush( aCommon, target->branch, target->head, aRetriedAfterTrust );
2522 },
2523 _( "Checking remote..." ) );
2524}
2525
2526
2527void GIT_COMMIT_PANE::startPush( std::shared_ptr<KIGIT_COMMON> aCommon, const wxString& aBranch, const wxString& aHead,
2528 bool aRetriedAfterTrust )
2529{
2530 // Read the keyring here, where an unlock prompt can show, then come back
2531 if( deferForSecret( aCommon, _( "Pushing..." ),
2532 [this, aCommon, aBranch, aHead, aRetriedAfterTrust]()
2533 {
2534 startPush( aCommon, aBranch, aHead, aRetriedAfterTrust );
2535 } ) )
2536 {
2537 return;
2538 }
2539
2540 m_transferStatus = _( "Pushing..." );
2541 setBusy( true, m_transferStatus );
2542 m_ownHold.Begin( aCommon, m_transferStatus,
2543 [this]()
2544 {
2545 m_transfer.Cancel();
2546 } );
2547
2548 // Carried rather than captured by reference, because Start returns before the work runs.
2549 struct OUTCOME
2550 {
2552 wxString error;
2553 wxString details;
2554 bool authFailure = false;
2555 bool cancelled = false;
2556
2557 std::optional<KIGIT::HOST_KEY_FAILURE> hostKey;
2558 };
2559
2560 auto outcome = std::make_shared<OUTCOME>();
2561
2562 bool started = m_transfer.Start(
2563 "git push",
2564 [aCommon, outcome, aBranch, aHead, alive = m_transfer.Alive(),
2565 pane = this]( const KIGIT_COMMON::CANCEL_TOKEN& aToken )
2566 {
2567 GIT_PUSH_HANDLER handler( aCommon.get() );
2568 handler.SetProgressReporter( std::make_unique<KIGIT_STATUS_REPORTER>(
2569 alive,
2570 [pane]( const wxString& aText )
2571 {
2572 pane->ShowTransferProgress( aText );
2573 } ) );
2574 handler.SetWaitForActionLock( true );
2575 handler.SetExpectedTarget( aBranch, aHead );
2576 handler.SetCancelToken( aToken );
2577 outcome->result = handler.PerformPush();
2578 KIGIT_ERROR_MESSAGE error = handler.PopError();
2579 outcome->error = error.summary;
2580 outcome->details = error.details;
2581 outcome->authFailure = handler.WasAuthFailure();
2582 outcome->hostKey = handler.GetHostKeyFailure();
2583
2584 // This operation's own token, so a cancel aimed at something else is not
2585 // reported here and this one's is not left behind for the next operation.
2586 outcome->cancelled = handler.IsThisOperationCancelled();
2587
2588 // The other surfaces need this even when the pane that started it has gone.
2589 if( outcome->result == PushResult::Success )
2590 {
2592 [aCommon]()
2593 {
2594 aCommon->NotifyRefreshListeners();
2595 } );
2596 }
2597 },
2598 [this, aCommon, outcome, aRetriedAfterTrust]()
2599 {
2600 onPushDone( aCommon, static_cast<int>( outcome->result ), outcome->error, outcome->details,
2601 outcome->authFailure, outcome->hostKey, aRetriedAfterTrust, outcome->cancelled );
2602 } );
2603
2604 if( !started )
2605 setBusy( false, _( "Could not start the push." ) );
2606}
2607
2608
2609void GIT_COMMIT_PANE::onPushDone( std::shared_ptr<KIGIT_COMMON> aCommon, int aResult, const wxString& aError,
2610 const wxString& aDetails, bool aAuthFailure,
2611 const std::optional<KIGIT::HOST_KEY_FAILURE>& aHostKey, bool aRetriedAfterTrust,
2612 bool aCancelled )
2613{
2614 PushResult result = static_cast<PushResult>( aResult );
2615
2617 {
2619
2620 // The shared refresh already ran in the completion.
2621 setBusy( false, _( "Pushed to remote." ) );
2622 KIGIT::ClearSyncWarnings( aCommon.get() );
2623 return;
2624 }
2625
2626 if( result == PushResult::Busy )
2627 {
2628 setBusy( false, wxEmptyString );
2629 KIGIT::ShowBusyMessage( this );
2630 return;
2631 }
2632
2634 failure.cancelled = aCancelled;
2635 failure.authFailure = aAuthFailure;
2636 failure.hostKey = aHostKey;
2637 failure.error = aError;
2638
2639 switch( KIGIT::AnswerTransferFailure( this, m_transfer.Alive(), aCommon.get(), &m_frame->Prj(), failure,
2640 aRetriedAfterTrust, m_credentialPrompts ) )
2641 {
2642 case KIGIT::TRANSFER_RETRY::RETRY: submitPush( aCommon, aRetriedAfterTrust ); return;
2643
2644 case KIGIT::TRANSFER_RETRY::RETRY_TRUSTED: submitPush( aCommon, true ); return;
2645
2646 case KIGIT::TRANSFER_RETRY::CANCELLED: setBusy( false, _( "Cancelled." ) ); return;
2647
2648 case KIGIT::TRANSFER_RETRY::HOST_DECLINED: setBusy( false, wxEmptyString ); return;
2649
2650 case KIGIT::TRANSFER_RETRY::GONE: return;
2651
2653 }
2654
2655 // The remote moved on since the last sync. Offer to bring those changes in and push
2656 // again, rather than force over them.
2658 {
2659 // Getting their changes needs a clean tree. Files left unticked at the commit, or edits
2660 // still in an editor, block it, and offering the click anyway would only fail later.
2661 auto worktree = std::make_shared<GIT_WORKTREE_STATUS>();
2662 wxString projectPath = m_frame->Prj().GetProjectPath();
2663
2665 aCommon,
2666 [worktree, projectPath]( KIGIT_COMMON& aSession )
2667 {
2668 *worktree = ReadGitWorktreeStatus( aSession, projectPath );
2669 },
2670 [this, aCommon, worktree]()
2671 {
2672 if( !ProjectSafeToRewrite( m_frame, this, *worktree ) )
2673 return;
2674
2675 if( IsOK( this, _( "Someone else pushed changes first.\n\n"
2676 "Get their changes and push again?" ) )
2677 && aCommon == m_frame->Prj().GetGitCommon() && !aCommon->IsShuttingDown()
2678 && Pgm().GetCommonSettings()->m_Git.enableGit )
2679 {
2680 submitPull( aCommon, true );
2681 }
2682 },
2683 _( "Checking working files..." ) );
2684
2685 return;
2686 }
2687
2688 setBusy( false, _( "Push failed." ) );
2689 DisplayErrorMessage( this,
2690 aError.IsEmpty() ? KIGIT::UnexplainedFailure( KIGIT_OPERATION::PUSH, aCommon->GetRemote() )
2691 : aError,
2692 aDetails );
2693}
2694
2695
2696// The worker owns the materialized conflict files until the UI finishes resolving them. A
2697// cancelled query drops the same object, so scratch files cannot outlive an abandoned flow.
2699{
2700 std::unique_ptr<GIT_DIFF_WORKSPACE> workspace;
2701 wxString headOid;
2702 wxString theirsOid;
2703 wxString error;
2704 std::vector<KIGIT_CONFLICT_SIDES> conflicts;
2706 bool rebaseConfigured = false;
2707 bool prepared = false;
2708};
2709
2710
2711void GIT_COMMIT_PANE::resolvePullConflicts( std::shared_ptr<KIGIT_COMMON> aCommon, bool aThenPush )
2712{
2713 auto preparation = std::make_shared<MERGE_PREPARATION>();
2714
2716 aCommon,
2717 [preparation]( KIGIT_COMMON& aSession )
2718 {
2719 preparation->workspace = std::make_unique<GIT_DIFF_WORKSPACE>();
2720
2721 if( !preparation->workspace->IsOk() )
2722 return;
2723
2724 preparation->rebaseConfigured = aSession.IsPullRebaseConfigured();
2725 preparation->identity = KIGIT::ReadGitIdentity( aSession );
2726 preparation->prepared = aSession.GetMergeConflicts(
2727 preparation->workspace->Root() + wxFileName::GetPathSeparator() + wxS( "stages" ),
2728 preparation->headOid, preparation->theirsOid, preparation->conflicts, preparation->error );
2729 },
2730 [this, aCommon, aThenPush, preparation]()
2731 {
2732 finishPullConflictPreparation( aCommon, aThenPush, preparation );
2733 },
2734 _( "Preparing the merge..." ) );
2735}
2736
2737
2738void GIT_COMMIT_PANE::finishPullConflictPreparation( std::shared_ptr<KIGIT_COMMON> aCommon, bool aThenPush,
2739 std::shared_ptr<MERGE_PREPARATION> aPreparation )
2740{
2741 if( !aPreparation->workspace || !aPreparation->workspace->IsOk() )
2742 {
2743 DisplayErrorMessage( this, _( "Could not create a temporary directory for the merge." ) );
2744 return;
2745 }
2746
2747 if( !aPreparation->prepared )
2748 {
2749 DisplayErrorMessage( this, _( "Could not prepare the merge." ), aPreparation->error );
2750 return;
2751 }
2752
2753 // Editors remain usable while the repository is read and while another editor's merge
2754 // tool is open. Refuse to reload over anything typed during either interval.
2755 auto canResolve = [this, aCommon]()
2756 {
2757 if( aCommon != m_frame->Prj().GetGitCommon() || aCommon->IsShuttingDown()
2758 || !Pgm().GetCommonSettings()->m_Git.enableGit )
2759 {
2760 return false;
2761 }
2762
2763 if( EditorsDirty( m_frame->Kiway() ) )
2764 {
2765 DisplayInfoMessage( this, _( "The open editors have unsaved changes. Save or revert them before "
2766 "resolving the merge." ) );
2767 return false;
2768 }
2769
2770 return true;
2771 };
2772
2773 if( !canResolve() )
2774 return;
2775
2776 // A conflicted rebase was already abandoned by the time it got here, and settling it from
2777 // this window can only produce a merge commit. Someone who asked for rebases is told that
2778 // before one is made.
2779 if( aPreparation->rebaseConfigured )
2780 {
2781 if( OKOrCancelDialog( this, _( "Get Changes" ),
2782 _( "This project is set to rebase when getting changes, but a conflict can only be "
2783 "settled here by merging. Make a merge commit, or cancel and rebase from a git "
2784 "command line." ),
2785 wxEmptyString, _( "Make Merge Commit" ) )
2786 != wxID_OK )
2787 {
2788 setBusy( false, _( "Getting changes was cancelled. Your files are unchanged." ) );
2789 return;
2790 }
2791 }
2792
2793 if( !canResolve() )
2794 return;
2795
2796 // The merge commit needs an identity whatever the user decides about the files, so it is
2797 // asked for before any merging. Cancelling it then costs no work.
2798 if( !KIGIT::EnsureGitIdentity( this, m_frame, aCommon, aPreparation->identity ) )
2799 {
2800 setBusy( false, _( "Getting changes was cancelled. Your files are unchanged." ) );
2801 return;
2802 }
2803
2804 if( !canResolve() )
2805 return;
2806
2807 GIT_DIFF_WORKSPACE& workspace = *aPreparation->workspace;
2808 const wxString sep = wxFileName::GetPathSeparator();
2809 const wxString& headOid = aPreparation->headOid;
2810 const wxString& theirsOid = aPreparation->theirsOid;
2811 const std::vector<KIGIT_CONFLICT_SIDES>& conflicts = aPreparation->conflicts;
2812 KIGIT_ERROR_MESSAGE error;
2813
2814 std::vector<std::pair<wxString, wxString>> resolved;
2815
2816 // The version the user does not keep is still somebody's work, so it is saved under the
2817 // project's backups. Written only once every conflict is answered, so cancelling changes nothing.
2818 struct LOSING_COPY
2819 {
2820 wxString source;
2821 wxString relativeDest;
2822 };
2823
2824 std::vector<LOSING_COPY> losingCopies;
2825
2826 // Files the user merged by hand. The scratch directory holding them goes when this returns.
2827 int handMerged = 0;
2828
2829 // Each file gets one try at a merge that needs no answers, before the user is asked
2830 std::set<size_t> autoTried;
2831
2832 for( size_t ii = 0; ii < conflicts.size(); )
2833 {
2834 if( !canResolve() )
2835 return;
2836
2837 const KIGIT_CONFLICT_SIDES& conflict = conflicts[ii];
2839
2840 // The merge tool needs all three sides. A deletion is kept or undone whole, and two files
2841 // created independently have no base to merge from, so they are kept or taken whole too.
2842 // The footprint merge never shows its tool and its comparison skips fields such as keywords, so
2843 // it could drop an edit unseen.
2844 const bool mergeable = kind != KICAD_DIFF::DOC_KIND::UNKNOWN && kind != KICAD_DIFF::DOC_KIND::FOOTPRINT
2845 && conflict.hasAncestor && conflict.hasOurs && conflict.hasTheirs;
2846
2847 // Two people editing different symbols of one library collide line by line, not part by part.
2848 // The engine reports success only for a merge that keeps both sides' edits
2849 if( mergeable && kind == KICAD_DIFF::DOC_KIND::SYM_LIB && autoTried.insert( ii ).second )
2850 {
2851 wxString mergedOut = workspace.Root() + sep + wxString::Format( wxS( "a%zu_" ), ii )
2852 + wxFileName( conflict.path ).GetFullName();
2853
2854 if( KICAD_DIFF::DispatchMerge( m_frame->Kiway(), kind, conflict.ancestorFile, conflict.oursFile,
2855 conflict.theirsFile, mergedOut, false, false, nullptr )
2857 {
2858 resolved.emplace_back( conflict.path, mergedOut );
2859 ++ii;
2860 continue;
2861 }
2862 }
2863
2864 wxArrayString choices;
2865
2866 if( mergeable )
2867 choices.Add( _( "Open the merge tool" ) );
2868
2869 // A side with no base was added, not deleted. A renamed file arrives as two such entries.
2870 choices.Add( conflict.hasOurs ? _( "Keep my version" )
2871 : conflict.hasAncestor ? _( "Keep it deleted" )
2872 : _( "Leave it out" ) );
2873 choices.Add( conflict.hasTheirs ? _( "Use the remote version" )
2874 : conflict.hasAncestor ? _( "Delete it, as on the remote" )
2875 : _( "Leave it out, as on the remote" ) );
2876
2877 wxString situation;
2878
2879 if( !conflict.hasOurs && !conflict.hasAncestor )
2880 {
2881 situation = _( "'%s' exists only on the remote (%zu of %zu).\n\n"
2882 "How should it be resolved?" );
2883 }
2884 else if( !conflict.hasOurs )
2885 {
2886 situation = _( "'%s' was deleted here but changed on the remote (%zu of %zu).\n\n"
2887 "How should it be resolved?" );
2888 }
2889 else if( !conflict.hasTheirs && !conflict.hasAncestor )
2890 {
2891 situation = _( "'%s' exists only here (%zu of %zu).\n\n"
2892 "How should it be resolved?" );
2893 }
2894 else if( !conflict.hasTheirs )
2895 {
2896 situation = _( "'%s' was changed here but deleted on the remote (%zu of %zu).\n\n"
2897 "How should it be resolved?" );
2898 }
2899 else
2900 {
2901 situation = _( "'%s' was changed both here and on the remote (%zu of %zu).\n\n"
2902 "How should it be resolved?" );
2903 }
2904
2905 int sel = wxGetSingleChoiceIndex( wxString::Format( situation, conflict.path, ii + 1, conflicts.size() ),
2906 _( "Resolve Conflict" ), choices, this );
2907
2908 if( sel < 0 )
2909 {
2910 wxString warning = handMerged == 1
2911 ? _( "Stop resolving? The file you merged by hand is discarded "
2912 "with the rest." )
2913 : wxString::Format( _( "Stop resolving? The %d files you merged by "
2914 "hand are discarded with the rest." ),
2915 handMerged );
2916
2917 if( handMerged > 0 && !IsOK( this, warning ) )
2918 continue;
2919
2920 // Nothing was touched yet, so cancelling really does leave everything as it was.
2921 setBusy( false, _( "Getting changes was cancelled. Your files are unchanged." ) );
2922 return;
2923 }
2924
2925 int action = mergeable ? sel : sel + 1;
2926
2927 if( action == 0 )
2928 {
2929 wxString mergedOut = workspace.Root() + sep + wxString::Format( wxS( "m%zu_" ), ii )
2930 + wxFileName( conflict.path ).GetFullName();
2931
2934 m_frame->Kiway(), kind, conflict.ancestorFile, conflict.oursFile, conflict.theirsFile, mergedOut,
2935 /* interactive */ true, false, &reporter );
2936
2937 if( rc != 0 )
2938 {
2939 // Cancelled or failed. Offer the choices for this file again.
2940 if( rc != CLI::EXIT_CODES::ERR_CANCELLED && reporter.HasMessage() )
2941 DisplayErrorMessage( this, _( "The merge tool did not produce a result." ),
2942 reporter.GetMessages() );
2943
2944 continue;
2945 }
2946
2947 resolved.emplace_back( conflict.path, mergedOut );
2948 ++handMerged;
2949
2950 // A merged result replaces both originals, so both are kept.
2951 if( conflict.hasOurs )
2952 losingCopies.push_back( { conflict.oursFile, conflict.path + wxS( ".mine" ) } );
2953
2954 if( conflict.hasTheirs )
2955 losingCopies.push_back( { conflict.theirsFile, conflict.path + wxS( ".theirs" ) } );
2956 }
2957 else if( action == 1 )
2958 {
2959 // An empty path records the resolution "the file is deleted".
2960 resolved.emplace_back( conflict.path, conflict.hasOurs ? conflict.oursFile : wxString() );
2961
2962 if( conflict.hasTheirs )
2963 losingCopies.push_back( { conflict.theirsFile, conflict.path + wxS( ".theirs" ) } );
2964 }
2965 else
2966 {
2967 resolved.emplace_back( conflict.path, conflict.hasTheirs ? conflict.theirsFile : wxString() );
2968
2969 if( conflict.hasOurs )
2970 losingCopies.push_back( { conflict.oursFile, conflict.path + wxS( ".mine" ) } );
2971 }
2972
2973 ++ii;
2974 }
2975
2976 if( !canResolve() )
2977 return;
2978
2979 // Written before the merge is published, so a copy that cannot be made stops the merge
2980 // rather than losing the version it was meant to protect. Each merge gets its own folder,
2981 // so copies from different conflicts never meet.
2982 wxString backupDir;
2983
2984 if( !losingCopies.empty() )
2985 {
2986 backupDir = Pgm().GetSettingsManager().GetBackupRootForProject( &m_frame->Prj() ) + sep + wxS( "merge-" )
2987 + wxDateTime::UNow().Format( wxS( "%Y-%m-%dT%H-%M-%S-%l" ) );
2988 }
2989
2990 // Undoing the copies keeps every later abort honest when it says the files are unchanged.
2991 auto discardSavedCopies = [&backupDir]()
2992 {
2993 if( !backupDir.IsEmpty() )
2994 wxFileName::Rmdir( backupDir, wxPATH_RMDIR_RECURSIVE );
2995 };
2996
2997 for( const LOSING_COPY& copy : losingCopies )
2998 {
2999 wxFileName dest( backupDir + sep + copy.relativeDest );
3000
3001 if( !dest.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) || !wxCopyFile( copy.source, dest.GetFullPath(), false ) )
3002 {
3003 discardSavedCopies();
3004 setBusy( false, _( "Getting changes was cancelled. Your files are unchanged." ) );
3005 DisplayErrorMessage( this, wxString::Format( _( "Could not save the version you are replacing "
3006 "as '%s', so the merge was stopped." ),
3007 dest.GetFullPath() ) );
3008 return;
3009 }
3010 }
3011
3013
3014 // The lock was released while the user resolved, and the background fetch may hold it now.
3015 // Throwing the resolutions away would mean doing every file again, so let the user retry.
3016 while( true )
3017 {
3018 if( !canResolve() )
3019 {
3020 discardSavedCopies();
3021 return;
3022 }
3023
3024 std::unique_lock<std::mutex> lock;
3025
3026 // Saving the copies into the project wakes a status read, so give it time to let go
3027 {
3028 wxBusyCursor busy;
3029 lock = aCommon->TryLockActionFor( KIGIT_COMMON::ACTION_LOCK_WAIT );
3030 }
3031
3032 if( lock.owns_lock() )
3033 {
3034 result = aCommon->CreateMergedCommit( headOid, theirsOid, resolved, error );
3035 break;
3036 }
3037
3038 if( !IsOK( this, _( "Another git operation is in progress. Try again?" ) ) )
3039 {
3040 discardSavedCopies();
3041 setBusy( false, _( "Getting changes was cancelled. Your files are unchanged." ) );
3042 return;
3043 }
3044 }
3045
3047 {
3048 // Nothing reached the files, so the copies that would have explained it go too.
3049 discardSavedCopies();
3050 }
3051 else
3052 {
3053 // Whatever was written has to reach the editors and panels, and a partial write leaves
3054 // the saved copies as the only way back to the old version.
3056 aCommon->NotifyRefreshListeners();
3057 }
3058
3060 {
3061 DisplayErrorMessage( this, error.summary.IsEmpty() ? _( "Could not finish the merge." ) : error.summary,
3062 error.details );
3063 return;
3064 }
3065
3066 if( aThenPush )
3067 submitPush( aCommon );
3068 else if( backupDir.IsEmpty() )
3069 setBusy( false, _( "Changes merged." ) );
3070 else
3071 setBusy( false, wxString::Format( _( "Changes merged. The versions you replaced are in '%s'." ), backupDir ) );
3072}
3073
3074
3075void GIT_COMMIT_PANE::submitPull( std::shared_ptr<KIGIT_COMMON> aCommon, bool aThenPush, bool aRetriedAfterTrust )
3076{
3077 // Version control can be removed while a transfer runs, and leaving the busy state behind
3078 // would disable the panel for good.
3079 if( !aCommon->GetRepo() )
3080 {
3081 setBusy( false, wxEmptyString );
3082 return;
3083 }
3084
3085 struct CHECK
3086 {
3087 KIGIT::GIT_IDENTITY identity;
3088 GIT_WORKTREE_STATUS worktree;
3089 };
3090
3091 auto result = std::make_shared<CHECK>();
3092 wxString projectPath = m_frame->Prj().GetProjectPath();
3093
3095 aCommon,
3096 [result, projectPath]( KIGIT_COMMON& aSession )
3097 {
3098 result->identity = KIGIT::ReadGitIdentity( aSession );
3099 result->worktree = ReadGitWorktreeStatus( aSession, projectPath );
3100 },
3101 [this, aCommon, aThenPush, aRetriedAfterTrust, result]()
3102 {
3103 if( !ProjectSafeToRewrite( m_frame, this, result->worktree ) )
3104 return;
3105
3106 // A non-fast-forward pull creates a commit, so obtain its identity before
3107 // the worker can change files. The repository check was in the query above.
3108 if( !KIGIT::EnsureGitIdentity( this, m_frame, aCommon, result->identity ) )
3109 return;
3110
3111 if( aCommon != m_frame->Prj().GetGitCommon() || aCommon->IsShuttingDown() )
3112 return;
3113
3114 // The identity prompt can allow new editor changes while it is open.
3115 if( !ProjectSafeToRewrite( m_frame, this, result->worktree ) )
3116 return;
3117
3118 startPull( aCommon, aThenPush, aRetriedAfterTrust );
3119 },
3120 _( "Checking changes..." ) );
3121}
3122
3123
3124void GIT_COMMIT_PANE::startPull( std::shared_ptr<KIGIT_COMMON> aCommon, bool aThenPush, bool aRetriedAfterTrust )
3125{
3126 // Read the keyring here, where an unlock prompt can show, then come back
3127 if( deferForSecret( aCommon, _( "Getting changes..." ),
3128 [this, aCommon, aThenPush, aRetriedAfterTrust]()
3129 {
3130 startPull( aCommon, aThenPush, aRetriedAfterTrust );
3131 } ) )
3132 {
3133 return;
3134 }
3135
3136 m_transferStatus = _( "Getting changes..." );
3137 setBusy( true, m_transferStatus );
3138 m_ownHold.Begin( aCommon, m_transferStatus,
3139 [this]()
3140 {
3141 m_transfer.Cancel();
3142 } );
3143
3144 // Record what the open documents look like on disk now, so only the ones the merge actually
3145 // rewrites are reloaded afterwards.
3147
3148 EDITOR_SNAPSHOT docsBefore = m_docsBeforePull;
3149
3150 // The KIWAY outlives this pane, so the editors are still reached when the pane has gone.
3151 KIWAY* kiway = &m_frame->Kiway();
3152
3153 // Carried rather than captured by reference, because Start returns before the work runs.
3154 struct OUTCOME
3155 {
3157 wxString error;
3158 wxString details;
3159 bool authFailure = false;
3160 bool cancelled = false;
3161
3162 std::optional<KIGIT::HOST_KEY_FAILURE> hostKey;
3163 };
3164
3165 auto outcome = std::make_shared<OUTCOME>();
3166
3167 bool started = m_transfer.Start(
3168 "git pull",
3169 [aCommon, docsBefore, kiway, outcome, alive = m_transfer.Alive(),
3170 pane = this]( const KIGIT_COMMON::CANCEL_TOKEN& aToken )
3171 {
3172 GIT_PULL_HANDLER handler( aCommon.get() );
3173 handler.SetProgressReporter( std::make_unique<KIGIT_STATUS_REPORTER>(
3174 alive,
3175 [pane]( const wxString& aText )
3176 {
3177 pane->ShowTransferProgress( aText );
3178 } ) );
3179 handler.SetWaitForActionLock( true );
3180 handler.SetCancelToken( aToken );
3181 outcome->result = handler.PerformPull();
3182 KIGIT_ERROR_MESSAGE error = handler.PopError();
3183 outcome->error = error.summary;
3184 outcome->details = error.details;
3185 outcome->authFailure = handler.WasAuthFailure();
3186 outcome->hostKey = handler.GetHostKeyFailure();
3187
3188 // This operation's own token, so a cancel aimed at something else is not
3189 // reported here and this one's is not left behind for the next operation.
3190 outcome->cancelled = handler.IsThisOperationCancelled();
3191
3192 PullResult result = outcome->result;
3193
3195 [aCommon, docsBefore, result, kiway]()
3196 {
3197 // A merge that failed partway can still have written files, so the
3198 // editors are brought up to date whatever the outcome. Nothing
3199 // reloads when nothing changed on disk.
3200 ReloadOpenEditors( *kiway, docsBefore );
3201
3203 aCommon->NotifyRefreshListeners();
3204 } );
3205 },
3206 [this, aCommon, aThenPush, aRetriedAfterTrust, outcome]()
3207 {
3208 onPullDone( aCommon, static_cast<int>( outcome->result ), outcome->error, outcome->details,
3209 outcome->authFailure, outcome->hostKey, aRetriedAfterTrust, aThenPush, outcome->cancelled );
3210 } );
3211
3212 if( !started )
3213 setBusy( false, _( "Could not start getting changes." ) );
3214}
3215
3216
3217void GIT_COMMIT_PANE::onPullDone( std::shared_ptr<KIGIT_COMMON> aCommon, int aResult, const wxString& aError,
3218 const wxString& aDetails, bool aAuthFailure,
3219 const std::optional<KIGIT::HOST_KEY_FAILURE>& aHostKey, bool aRetriedAfterTrust,
3220 bool aThenPush, bool aCancelled )
3221{
3222 PullResult result = static_cast<PullResult>( aResult );
3223
3225 {
3227 KIGIT::ClearSyncWarnings( aCommon.get() );
3228
3229 // The editor reloads and the panel refresh already ran in the completion, before the
3230 // window check, so they happen even when the initiating window is gone.
3232 aCommon->NotifyRefreshListeners();
3233
3234 // Pushing afterwards belongs only to the push-was-rejected recovery. A plain Get
3235 // Changes must not publish local commits the user chose to keep local.
3236 if( aThenPush )
3237 submitPush( aCommon );
3238 else
3239 setBusy( false, result == PullResult::UpToDate ? _( "Already up to date." ) : _( "Changes received." ) );
3240
3241 return;
3242 }
3243
3245 failure.cancelled = aCancelled;
3246 failure.authFailure = aAuthFailure;
3247 failure.hostKey = aHostKey;
3248 failure.error = aError;
3249
3250 // A rejected login is not a merge problem, so offer the credentials prompt and retry,
3251 // matching the push path.
3252 switch( KIGIT::AnswerTransferFailure( this, m_transfer.Alive(), aCommon.get(), &m_frame->Prj(), failure,
3253 aRetriedAfterTrust, m_credentialPrompts ) )
3254 {
3255 case KIGIT::TRANSFER_RETRY::RETRY: submitPull( aCommon, aThenPush, aRetriedAfterTrust ); return;
3256
3257 case KIGIT::TRANSFER_RETRY::RETRY_TRUSTED: submitPull( aCommon, aThenPush, true ); return;
3258
3259 case KIGIT::TRANSFER_RETRY::CANCELLED: setBusy( false, _( "Cancelled." ) ); return;
3260
3261 case KIGIT::TRANSFER_RETRY::HOST_DECLINED: setBusy( false, wxEmptyString ); return;
3262
3263 case KIGIT::TRANSFER_RETRY::GONE: return;
3264
3266 }
3267
3268 // Conflicting changes are resolved file by file, with the visual merge for design files.
3269 // The failed merge already restored the pre-pull state, so cancelling costs nothing.
3271 {
3272 resolvePullConflicts( aCommon, aThenPush );
3273 return;
3274 }
3275
3276 // Something uncommitted appeared after the pre-pull check, or an untracked file collides
3277 // with an incoming one. This is the panel's own job to fix, not the command line's.
3279 {
3280 setBusy( false, _( "Commit your changes first." ) );
3281 aCommon->NotifyRefreshListeners();
3282
3283 // The backend names the files when it can, which the generic text cannot.
3284 if( !aError.IsEmpty() )
3285 {
3286 DisplayInfoMessage( this, aError );
3287 }
3288 else
3289 {
3290 DisplayInfoMessage( this, _( "There are changes that are not committed yet, and getting changes "
3291 "would run over them. Commit them first, then get changes again. To "
3292 "set them aside instead, use Stash Changes in the Advanced Git "
3293 "window." ) );
3294 }
3295
3296 return;
3297 }
3298
3299 // The failure may or may not have touched the working tree, so refresh the panels and
3300 // report the backend's actual error rather than guessing at a cause.
3301 setBusy( false, _( "Could not get changes." ) );
3302 aCommon->NotifyRefreshListeners();
3303 DisplayErrorMessage( this,
3304 aError.IsEmpty() ? KIGIT::UnexplainedFailure( KIGIT_OPERATION::FETCH, aCommon->GetRemote() )
3305 : aError,
3306 aDetails );
3307}
const char * name
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:106
The base frame for deriving all KiCad main window classes.
The advanced Git window: a non-modal dialog with a top bar naming the repository and branch and a sid...
static void ShowHistoryForFile(EDA_BASE_FRAME *aParent, GIT_COMMIT_PANE *aPane, const wxString &aPath)
Open the window on its History page, narrowed to the commits that changed aPath.
static void CloseForPane(GIT_COMMIT_PANE *aPane)
Close the live window if the given pane opened it, for when that pane goes away.
static void CloseActive()
Close the live window, for when the project it was filled from goes away.
static GIT_ADVANCED_DIALOG * Active()
The live window, or null when none is open.
static void ShowForFrame(EDA_BASE_FRAME *aParent, GIT_COMMIT_PANE *aPane, std::optional< GIT_ADVANCED_PAGE > aPage=std::nullopt)
Raise the one window for this session, creating it on first use.
BranchResult SwitchToBranch(const wxString &aBranchName)
Switch to the specified branch.
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)
UndoCommitResult PerformUndoLastCommit(const wxString &aExpectedBranch, const git_oid &aExpectedHead, wxString &aMessage)
wxStaticBoxSizer * m_optionsSizer
STD_BITMAP_BUTTON * m_settingsButton
FILE_CHECKLIST_CTRL * m_checklist
GIT_COMMIT_PANE_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(500, 360), long style=wxTAB_TRAVERSAL, const wxString &name=wxEmptyString)
wxString abandonLabel() const
The label the network button carries while an operation is in progress.
bool othersCanCancel() const
void updateCommitButton()
Set what the commit buttons say, and whether they are enabled, for the current state.
void onPull(wxCommandEvent &aEvent)
int m_credentialPrompts
Keyring reads and credential prompts the current request has shown, reset when it ends.
void onMessageChanged(wxCommandEvent &aEvent)
void resolvePullConflicts(std::shared_ptr< KIGIT_COMMON > aCommon, bool aThenPush)
Resolve a conflicted pull file by file, using the visual merge tool for design files,...
unsigned m_keyringRequest
UTIL::LINK m_transferLink
Follows the transfers other windows run on this pane's repository.
void ShowTransferProgress(const wxString &aText)
Show a line of transfer progress. Called from the UI thread by a KIGIT_STATUS_REPORTER.
wxString m_transferStatus
The status m_transfer began with, shown again once other windows' transfers end before it.
void Pull()
Get changes from the remote, as the Get Changes button does.
wxString GetCommitMessage() const
The message as typed. A second form on the same project shows the same text.
void onNewBranchToggled(wxCommandEvent &aEvent)
std::pair< wxString, wxString > m_undoHead
The branch and commit the last refresh showed, so Undo takes back only the commit the user saw.
void abandonOperation(std::shared_ptr< KIGIT_COMMON > aCommon)
Drop an in-progress merge or rebase and return the project to its last commit.
void BeginAmend(const wxString &aExpectedCommit=wxEmptyString)
Prepare the amend form. A history entry supplies its hash and starts with no files selected.
void finishCommit(std::shared_ptr< KIGIT_COMMON > aCommon, const COMMIT_REQUEST &aRequest)
void onUndoCommit(wxCommandEvent &aEvent)
Take back the last commit while no remote has it, keeping its changes staged and its message.
bool m_showingOthers
The busy state shows another window's transfer, which this pane releases when the last one ends.
bool m_inAdvancedWindow
True on the advanced window's Changes page, false in the docked panel.
std::function< void(const wxString &)> m_fileSelectedHandler
void setDescription(const wxString &aText)
void submitPull(std::shared_ptr< KIGIT_COMMON > aCommon, bool aThenPush, bool aRetriedAfterTrust=false)
aThenPush pushes after a successful pull, which belongs only to the rejected-push recovery flow.
void discardFile(std::shared_ptr< KIGIT_COMMON > aCommon, const wxString &aPath)
KIGIT_QUERY m_refresh
Coalesce refreshes while a repository read is running, and discard stale results.
bool othersBusy() const
The transfers on it that other windows started, leaving out this pane's own.
std::pair< int, int > m_lineStats
Lines the working tree adds and removes against HEAD, read at the last refresh.
void onSettings(wxCommandEvent &aEvent)
The gear's menu: the advanced window and the author.
bool transferCanStart()
False, with a message, while a transfer is running or a merge waits to be finished.
void updateMessageVisibility(bool aHasChanges)
Show the message field whenever a commit is possible, including a message-only amend.
bool deferForSecret(const std::shared_ptr< KIGIT_COMMON > &aCommon, const wxString &aStatus, std::function< void()> aStart)
Read the keyring before a transfer, holding the pane busy as aStatus, then call aStart unless cancell...
EDA_BASE_FRAME * m_frame
void RefreshFileList()
Read the project's git status and repopulate the list.
bool m_editorsDirty
True when an open editor held unsaved changes at the last refresh.
void finishPullConflictPreparation(std::shared_ptr< KIGIT_COMMON > aCommon, bool aThenPush, std::shared_ptr< MERGE_PREPARATION > aPreparation)
void setBusy(bool aBusy, const wxString &aStatus)
Enable or disable the controls while a network operation runs, showing a status.
wxString othersStatus() const
void ReloadAdvancedWindow()
Reload the advanced window when it is open, for a preferences change it also shows.
bool m_canAmend
Whether the current branch allows an amend. A refresh must not change an active amend into a commit.
wxString operationNoun() const
The noun for the operation in progress, for messages.
void onChecklistChanged(wxDataViewEvent &aEvent)
void populateBranches(const STATUS &aStatus)
Fill the branch dropdown from the completed snapshot.
size_t m_unpushedCount
Commits waiting to be pushed, or 0 when the branch has no upstream to count them against.
void onFileActivated(wxDataViewEvent &aEvent)
wxWindow * m_dockParent
bool Layout() override
Lay out the pane, then re-wrap the status line when the width its column got has changed.
bool m_commitButtonPushes
True while the main button reads Push, with nothing left to commit.
void ShowHistory()
Open the advanced window on its History page.
wxStaticText * m_summaryRemoved
void updateSummary()
Refresh the staged count in the changes heading, and the summary box where the wide layout has one.
void saveForCommit(std::shared_ptr< KIGIT_COMMON > aCommon, std::shared_ptr< COMMIT_REQUEST > aRequest)
void onCommit(wxCommandEvent &aEvent)
The split button's main half. It commits, or pushes when that is all there is to do.
GIT_TRANSFER_BUSY::HOLD m_ownHold
m_transfer's hold on the repository, so every other pane on it follows and can cancel it
GIT_TRANSFER_BUSY & transfers() const
The transfers on the repository this pane shows.
void showDisabledState()
Clear the list and disable every control while version control is off.
void updateDescriptionHint()
Where the platform has no hint for a multi line box, a label lies over the description box while it i...
std::function< void(bool)> m_busyChangedHandler
Told when a transfer starts and ends. Empty unless an owning window asked.
void layoutWide()
Put the file list beside the commit controls instead of above them, for a wide host,...
KIGIT_TRANSFER m_transfer
The push or pull this panel submitted last.
void OnGitTransfersChanged() override
Follow a transfer on this pane's repository beginning or ending in any window.
void onPushDone(std::shared_ptr< KIGIT_COMMON > aCommon, int aResult, const wxString &aError, const wxString &aDetails, bool aAuthFailure, const std::optional< KIGIT::HOST_KEY_FAILURE > &aHostKey, bool aRetriedAfterTrust, bool aCancelled)
std::pair< wxString, wxString > m_amendHead
The branch and commit chosen when amend started. Keep them fixed while editing.
void onChecklistContextMenu(wxDataViewEvent &aEvent)
void startPush(std::shared_ptr< KIGIT_COMMON > aCommon, const wxString &aBranch, const wxString &aHead, bool aRetriedAfterTrust)
void setStatusText(const wxString &aText)
Set the status line text and wrap it to the width of the label's column.
std::function< void()> m_messageChangedHandler
Told when the message is edited. Empty unless an owning window asked.
bool m_headDetached
True when HEAD is a commit rather than a branch, so nothing can be committed or pushed.
wxString m_statusText
Unwrapped status text, kept so it can be re-wrapped on resize.
std::vector< wxString > m_recentMessageTexts
The full messages behind the Recent messages dropdown, in its order after the caption.
wxString m_currentBranch
The branch a commit will land on, empty when detached or before the first commit.
void populateRecentMessages(const std::vector< wxString > &aMessages)
Fill the Recent messages dropdown from the completed snapshot.
void Push()
Push the local commits, as the Push button does.
int m_statusWrapWidth
The width the status text was last wrapped to, so a layout re-wraps it only when that changes.
bool layoutAndWrapStatus()
Lay out the controls, then rewrap the status line to its column's new width.
void onShowDiff(wxCommandEvent &aEvent)
bool m_operationInProgress
True while a merge or rebase is in progress. The network button then reads Abandon.
void SetCommitMessage(const wxString &aMessage)
wxStaticText * m_summaryFiles
void onThemeChanged(wxSysColourChangedEvent &aEvent)
wxMenuItem * m_commitAndPushItem
The arrow menu's entry, relabelled with the main button.
bool m_hasRepo
Whether the last completed status snapshot had a repository.
void SetFileSelectedHandler(std::function< void(const wxString &)> aHandler)
Called with the path of the file the user selects in the list, or empty when none is.
void onCommitAndPush(wxCommandEvent &aEvent)
GIT_COMMIT_PANE(EDA_BASE_FRAME *aParent)
int m_minDockWidth
The widest row's minimum width, measured before anything is hidden.
GitOperation m_operation
Which operation, so the button and the explanation can name it.
~GIT_COMMIT_PANE() override
std::set< wxString > m_shownPaths
Paths shown in the list at the last refresh, so a refresh can tell which files the user deliberately ...
void onPullDone(std::shared_ptr< KIGIT_COMMON > aCommon, int aResult, const wxString &aError, const wxString &aDetails, bool aAuthFailure, const std::optional< KIGIT::HOST_KEY_FAILURE > &aHostKey, bool aRetriedAfterTrust, bool aThenPush, bool aCancelled)
void onRecentMessage(wxCommandEvent &aEvent)
void runActionQuery(std::shared_ptr< KIGIT_COMMON > aCommon, std::function< void(KIGIT_COMMON &)> aWork, std::function< void()> aDone, const wxString &aStatus)
Read an action's prerequisites off the UI thread, then resume only in the same project.
void startPull(std::shared_ptr< KIGIT_COMMON > aCommon, bool aThenPush, bool aRetriedAfterTrust)
bool dropKeyringWait()
Forget a keyring wait without touching the busy state. True when one was pending.
void onAmendToggled(wxCommandEvent &aEvent)
void onIdle(wxIdleEvent &aEvent)
int m_dockMinHeight
The controls' minimum height from the last layout, applied to the AUI pane at idle time.
bool m_listenerAttached
True once this panel has attached its refresh listener to a session at least once.
void syncListener()
Register a refresh listener with the project's current git session, re-registering if the session cha...
bool m_keyringWait
A push or pull waits on the keyring. The count fences off an answer from a cancelled wait.
size_t m_upstreamAhead
Commits the upstream has that this project does not, which Get Changes brings in.
void applyTheme()
Set the icons and colours that follow the light or dark theme.
void confirmDiscardFile(std::shared_ptr< KIGIT_COMMON > aCommon, const wxString &aPath, bool aTracked, bool aConflicted, wxString aRoot)
KIGIT_QUERY m_actionQuery
EDITOR_SNAPSHOT m_docsBeforePull
On-disk identity of the open documents, taken before a pull so only the ones the merge rewrote are re...
wxStaticText * m_descriptionHint
The description box's hint, a label laid over it while it is empty.
void updateSummaryCount()
Show how many of the summary's 72 columns are left, once that is 10 or fewer.
void applyStatus(const STATUS &aStatus)
Apply a completed repository snapshot on the UI thread.
void submitPush(std::shared_ptr< KIGIT_COMMON > aCommon, bool aRetriedAfterTrust=false)
void finishAbandonOperation(std::shared_ptr< KIGIT_COMMON > aCommon, const std::vector< wxString > &aOutside)
std::weak_ptr< KIGIT_COMMON > m_listenerSession
The git session this panel registered a refresh listener with, weak so it does not keep the session a...
wxHyperlinkCtrl * m_historyLink
Opens the History page from the docked panel. Never shown inside the advanced window.
void updateDockMinHeight()
Give the AUI pane the controls' minimum height, so a dock never squeezes them.
void doCommit(bool aAndPush)
Commit the checked files (or amend the last commit when the amend box is ticked), then push when aAnd...
wxStaticText * m_summaryAdded
void showTrustCommand(const wxString &aCommand)
Show a command to copy under the status line, or hide the row when aCommand is empty.
GitUserConfig GetUserConfig()
Get user configuration (name and email) from git config Falls back to common settings if not found in...
A private scratch directory for extracting committed file versions to diff, removed when this object ...
const wxString & Root() const
The scratch directory, for callers that lay out their own files (e.g. footprint libraries).
The transfers running on one repository, so every window can show and cancel the others'.
wxString Status(const HOLD &aExcept) const
The status of the latest live transfer other than aExcept's, or empty when none is.
void CancelAll()
Call each live transfer's cancel once. They stay live until their owners end them.
bool CanCancel(const HOLD &aExcept) const
True while a live transfer other than aExcept's has a cancel that has not been called.
bool IsBusy(const HOLD &aExcept) const
True while a transfer other than aExcept's is live.
wxColour ToColour() const
Definition color4d.cpp:221
static wxString LfsRefusal(KIGIT_COMMON *aCommon)
Return a refusal message for LFS files or an unknown project folder, otherwise empty.
The project's git session.
static bool DeferForSecret(const std::shared_ptr< KIGIT_COMMON > &aCommon, const std::weak_ptr< bool > &aOwner, std::function< void()> aRetry)
Read the remote's secret from the keyring on the UI thread without blocking it, so an unlock prompt c...
std::pair< int, int > GetWorkingTreeLineStats(const std::set< wxString > &aPaths) const
std::shared_ptr< std::atomic< bool > > CANCEL_TOKEN
One token per operation.
wxString GetLastCommitMessage() const
wxString GetCurrentBranchName() const
wxString GetGitRootDirectory() const
bool IsOperationInProgress() const
True while a merge, rebase, cherry-pick or revert is in progress, which refuses commits.
bool IsPullRebaseConfigured() const
True when the repository is set to rebase rather than merge when getting changes.
git_repository * GetRepo() const
std::vector< wxString > GetRecentCommitMessages(size_t aMax) const
bool CreateBranch(const wxString &aName, const wxString &aFrom=wxEmptyString)
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,...
bool StartUnbornBranch(const wxString &aName)
Point HEAD at a branch that does not exist yet, so the first commit creates it.
bool IsHeadUnborn() const
True while the repository has no commits, so HEAD names a branch that does not exist yet.
static constexpr std::chrono::milliseconds ACTION_LOCK_WAIT
Long enough for a status read to finish, short enough that a window does not look hung.
wxString GetHeadCommitId() const
Full commit ID at HEAD, or empty for an unborn or missing HEAD.
bool HasPushAndPullRemote() const
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.
static wxString GetLastGitError()
libgit2's last message, without credentials from any URL it quotes, so it is safe to show or trace.
bool HasLocalCommits() const
True when HEAD has commits its upstream does not, or has no upstream yet.
GitOperation OperationInProgress() const
Which operation that is, so the panel can name it.
std::vector< KIGIT_BRANCH_INFO > GetBranches() const
Local and remote branches with their tip commits.
bool DeleteBranch(const wxString &aName)
bool IsPathConflicted(const wxString &aPath) const
True while aPath is one of the files a merge or rebase stopped on.
bool IsHeadDetached() const
True when HEAD points at a commit rather than a branch, as after checking out a tag.
KIGIT_ERROR_MESSAGE PopError()
Take the newest error with its details. Both are empty when none is queued.
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:348
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
wxString GetBackupRootForProject(const PROJECT *aProject=nullptr) const
Resolve the backup root directory for a project, honoring the active BACKUP_LOCATION preference.
A wrapper for reporting to a wxString object.
Definition reporter.h:242
bool SaveClipboard(const std::string &aTextUTF8)
Store information to the system clipboard.
Definition clipboard.cpp:32
int OKOrCancelDialog(wxWindow *aParent, const wxString &aWarning, const wxString &aMessage, const wxString &aDetailedMessage, const wxString &aOKLabel, const wxString &aCancelLabel, bool *aApplyToAll)
Display a warning dialog with aMessage and returns the user response.
Definition confirm.cpp:165
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition confirm.cpp:274
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition confirm.cpp:245
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
#define CHECK(x)
#define _(s)
Base window classes and related definitions.
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
MergeCommitResult
Definition git_backend.h:83
UndoCommitResult
Definition git_backend.h:67
@ TargetChanged
The branch or its last commit is no longer the one the caller saw.
Definition git_backend.h:74
@ Published
A remote-tracking branch already holds the commit, so taking it back would rewrite shared history.
Definition git_backend.h:71
static wxString amendRefusal(KIGIT_COMMON &aCommon, const std::pair< wxString, wxString > &aExpectedHead)
static bool moveToNewBranch(KIGIT_COMMON &aCommon, const wxString &aName, wxString &aError, wxString &aDetail)
static std::pair< wxString, wxString > commitHead(git_repository *aRepo)
static void dropNewBranch(KIGIT_COMMON &aCommon, const wxString &aName, const wxString &aPrevious)
static KIGIT::PROMPT_ANSWER refusal(const wxWeakRef< wxWindow > &aParent, bool aHadParent)
PullResult
PushResult
@ Busy
Another git operation held the action lock, so nothing was pushed.
bool PrepareEditorsForGitOperation(EDA_BASE_FRAME *aFrame, GIT_EDITOR_PREP aPurpose, bool *aSavedEditors)
Offer to save unsaved schematic and board edits before a git operation.
std::vector< wxString > ChangedTrackedFilesOutsideProject(KIGIT_COMMON &aCommon, const wxString &aProjectPath)
Repository relative paths of tracked files changed outside the project directory, which the checklist...
EDITOR_SNAPSHOT CaptureOpenEditorDocs(KIWAY &aKiway)
Record the on-disk identity of the open documents, before an operation that may rewrite them.
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...
void ChangeGitIgnore(EDA_BASE_FRAME *aFrame, wxWindow *aParent, GIT_IGNORE_CHANGE aChange, const std::vector< GIT_IGNORE_TARGET > &aTargets)
Write a change to the project's ignored files and refresh every Git surface.
void ReloadOpenEditors(KIWAY &aKiway, const EDITOR_SNAPSHOT &aBefore)
Tell the open board and schematic editors to reload from disk.
GIT_WORKTREE_STATUS ReadGitWorktreeStatus(KIGIT_COMMON &aCommon, const wxString &aProjectPath)
Read tracked changes and Git LFS using a captured project path.
bool DocumentEditorsDirty(KIWAY &aKiway)
Unsaved schematic or board edits can be saved for a commit, even with no changes on disk.
void ShowGitFileDiff(EDA_BASE_FRAME *aFrame, const wxString &aRelativePath)
Open the diff for a changed file, comparing the committed version at HEAD with the working copy.
bool ProjectSafeToRewrite(EDA_BASE_FRAME *aFrame, wxWindow *aParent, const GIT_WORKTREE_STATUS &aStatus, bool aAllowTrackedChanges)
Combine the repository snapshot with live editor state and explain any refusal.
bool EditorsDirty(KIWAY &aKiway)
Unsaved document or library edits block operations that rewrite files. Call on the UI thread.
@ IGNORE_PATH
Ignore the paths themselves.
@ IGNORE_EXTENSION
Ignore every file sharing the paths' extension.
@ COMMIT
Saving dirty editors for a commit also saves the project file.
std::string source
std::string message
GitOperation
static const int ERR_CANCELLED
The user cancelled the operation.
Definition exit_codes.h:45
static const int SUCCESS
Definition exit_codes.h:29
int DispatchMerge(KIWAY &aKiway, DOC_KIND aKind, const wxString &aAncestor, const wxString &aOurs, const wxString &aTheirs, const wxString &aOutput, bool aInteractive, bool aSingleFile, REPORTER *aReporter)
Run a 3-way document/library merge by calling the owning kiface's KIFACE_MERGE_DOCUMENT function expo...
DOC_KIND DocKindFromExtension(const wxString &aPath)
Map a path's extension to a DOC_KIND (.kicad_pcb -> PCB, .kicad_sch -> SCH, .kicad_sym -> SYM_LIB,...
DOC_KIND
Document type a diff/merge entry point should route to, derived from a file path's extension.
void ClearSyncWarnings(wxWindow *aWindow)
Clear the background fetch's warnings from the frame holding aWindow.
void SortBranchesForDisplay(std::vector< KIGIT_BRANCH_INFO > &aBranches)
Put the current branch first, then local and remote branches with the newest tips first.
void SplitCommitMessage(const wxString &aMessage, wxString &aSummary, wxString &aDescription)
Split a commit message into its first line and the description after the first blank line.
wxString BranchNameError(const wxString &aName)
Empty when aName is a branch name git would accept, otherwise why it would not, in the words to show ...
GIT_IDENTITY ReadGitIdentity(KIGIT_COMMON &aCommon)
Read on a worker while holding the session's action lock.
bool EnsureGitIdentity(wxWindow *aParent, EDA_BASE_FRAME *aFrame, const std::shared_ptr< KIGIT_COMMON > &aCommon, const GIT_IDENTITY &aIdentity)
Open the same editor when the worker snapshot has no usable Git identity.
std::unique_lock< std::mutex > WaitForActionLock(KIGIT_COMMON &aCommon, wxWindow *aParent)
TryLockAction that first waits a moment for a status read or fetch to let go.
APIEXPORT wxString ExtensionIgnoreRule(const wxString &aProjectRelPath)
The rule that ignores every file sharing a path's extension, or nothing when it has none.
wxString ComposeCommitMessage(const wxString &aSummary, const wxString &aDescription, const wxString &aSignOff)
Join a summary line, an optional description and an optional sign-off into one commit message.
void ShowBusyMessage(wxWindow *aParent)
Show a busy message for a user action. UI thread only.
TRANSFER_RETRY AnswerTransferFailure(wxWindow *aParent, const std::weak_ptr< bool > &aAlive, KIGIT_COMMON *aCommon, PROJECT *aProject, const TRANSFER_FAILURE &aFailure, bool aRetriedAfterTrust, int &aPrompts)
Answer a failed transfer the way every window does.
std::unique_lock< std::mutex > TryLockAction(KIGIT_COMMON &aCommon, wxWindow *aParent)
Try the action lock and show a busy message if it is unavailable.
APIEXPORT IGNORE_STATE IgnoreState(KIGIT_COMMON &aCommon, const wxString &aProjectRelPath, bool aIsDirectory)
What git's rules and its index say about a project path, so the user is offered only what would take ...
@ RETRY_TRUSTED
Run it again, now that the server's key is trusted.
@ GONE
The window closed during a prompt, so the caller must not touch it.
@ CANCELLED
Stop and say so, the user cancelled the transfer or a prompt.
@ RETRY
Run the transfer again.
@ HOST_DECLINED
Stop without a message, the user chose not to trust the server.
bool EditGitIdentity(wxWindow *aParent, EDA_BASE_FRAME *aFrame, const std::shared_ptr< KIGIT_COMMON > &aCommon, const GIT_IDENTITY &aIdentity)
Edit the repository's author and refresh Git views after saving.
APIEXPORT wxString UnexplainedFailure(KIGIT_OPERATION aOperation, const wxString &aUrl)
The summary for an operation that failed without saying why, naming the server it was talking to.
void CallOnUi(std::function< void()> aFn)
Run aFn on the UI thread.
bool MoveToTrash(const wxString &aPath, wxString &aError)
Move the specified file/directory to the trash bin/recycle bin.
void EllipsizeChoiceBox(wxChoice *aChoice)
Configure a wxChoice control to ellipsize the shown text in the button with the ellipses placed at th...
Definition wxgtk/ui.cpp:436
bool IsDarkTheme()
Determine if the desktop interface is currently using a dark theme or a light theme.
Definition wxgtk/ui.cpp:57
KICOMMON_API wxString WrapText(wxWindow *aWindow, const wxString &aText, int aWidth)
Break text into lines no wider than aWidth pixels in aWindow's font.
KICOMMON_API void FollowSystemLinkColour(wxHyperlinkCtrl *aLink)
Keep a hyperlink in the system link colour across a light or dark switch.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
What the open editors and the project settings looked like on disk before an operation that may rewri...
One file row in a FILE_CHECKLIST_CTRL.
wxString path
Row identity, and what the row shows.
std::pair< wxString, wxString > head
std::vector< KIGIT_CONFLICT_SIDES > conflicts
std::unique_ptr< GIT_DIFF_WORKSPACE > workspace
std::pair< int, int > lineStats
std::vector< KIGIT_BRANCH_INFO > branches
std::vector< FILE_CHECKLIST_ENTRY > entries
std::pair< wxString, wxString > head
std::vector< wxString > recentMessages
One path an ignore change applies to, relative to the project folder with forward slashes.
Repository state used before an operation that requires a clean working tree.
Diff colors with defaults for light backgrounds.
Definition diff_scene.h:278
static DIFF_COLOR_THEME ForText(bool aDarkTheme)
Resolve change colors for UI text. Pass the desktop theme captured on the UI thread.
Repository values and whether Git can use them to record a commit.
bool tracked
The path, or a file inside it, is in the index, so a new rule would do nothing.
Why a transfer to a remote failed.
bool cancelled
The user cancelled the transfer.
std::optional< HOST_KEY_FAILURE > hostKey
The server's key is unknown or has changed.
bool authFailure
The remote refused every credential offered.
wxString error
Shown above the credential fields.
wxString theirsFile
Extracted remote version, an empty file when absent.
wxString ancestorFile
Extracted common-ancestor version, an empty file when absent.
wxString oursFile
Extracted local version, an empty file when absent.
bool hasOurs
False when the local side deleted the file.
wxString path
Repository-relative path of the conflicted file.
bool hasTheirs
False when the remote side deleted the file.
bool hasAncestor
False when the file did not exist in the common ancestor.
A summary the user can act on, with the raw text that explains it kept apart for the details.
std::string path
IbisParser parser & reporter
wxString result
Test unit parsing edge cases and error handling.
Functions to provide common constants and other functions to assist in making a consistent UI.
Definition of file extensions used in Kicad.