KiCad PCB EDA Suite
Loading...
Searching...
No Matches
git_status_entries.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
22#include <fstream>
23#include <map>
24#include <memory>
25#include <optional>
26#include <set>
27#include <sys/stat.h>
28#include <mutex>
29#include <vector>
30
31#include <wx/choicdlg.h>
32#include <wx/dir.h>
33#include <wx/filename.h>
34#include <wx/richmsgdlg.h>
35#include <wx/weakref.h>
36
37#include <reporter.h>
38
39#include <confirm.h>
46#include <git/text_diff.h>
49#include <eda_base_frame.h>
50#include <frame_type.h>
52#include <git/kigit_ignore.h>
55#include <i18n_utility.h>
56#include <kiway.h>
57#include <kiway_player.h>
58#include <mail_type.h>
59#include <pgm_base.h>
60#include <project.h>
66
67
68// Fill the status label, icon and color. Return false for changes the checklist does not show.
69static bool statusToDisplay( KIGIT_COMMON::GIT_STATUS aStatus, wxString& aWord, BITMAPS& aIcon, wxColour& aColour,
70 const KICAD_DIFF::DIFF_COLOR_THEME& aTheme )
71{
72 switch( aStatus )
73 {
75 aWord = _( "Modified" );
77 aColour = aTheme.modified.ToColour();
78 return true;
81 aWord = _( "New" );
82 aIcon = BITMAPS::git_add;
83 aColour = aTheme.added.ToColour();
84 return true;
86 aWord = _( "Deleted" );
87 aIcon = BITMAPS::git_delete;
88 aColour = aTheme.removed.ToColour();
89 return true;
91 aWord = _( "Conflict" );
93 aColour = aTheme.conflict.ToColour();
94 return true;
95 default: return false;
96 }
97}
98
99
100std::vector<FILE_CHECKLIST_ENTRY> BuildGitChangeEntries( KIGIT_COMMON& aCommon, const wxString& aProjectPath,
101 bool aDarkTheme )
102{
103 std::vector<FILE_CHECKLIST_ENTRY> entries;
104
105 const std::optional<wxString> prefix = aCommon.GetProjectPrefix();
106
107 if( !prefix )
108 return entries;
109
110 GIT_STATUS_HANDLER handler( &aCommon );
111 wxString workDir = handler.GetWorkingDirectory();
112
113 std::map<wxString, FileStatus> statusMap = handler.GetFileStatus( *prefix, /* changed only */ true );
115
116 for( const auto& [path, fileStatus] : statusMap )
117 {
118 wxString word;
120 wxColour colour;
121
122 if( !statusToDisplay( fileStatus.status, word, icon, colour, theme ) )
123 continue;
124
126 continue;
127
128 // The commit handler stages paths relative to the working directory.
129 wxString relativePath = path;
130
131 if( relativePath.StartsWith( workDir ) )
132 relativePath = relativePath.Mid( workDir.length() );
133
134#ifdef __WINDOWS__
135 relativePath.Replace( wxS( "\\" ), wxS( "/" ) );
136#endif
137
138 // Only files git does not know at all are hidden. One that is tracked, or staged to be,
139 // is carried by a commit and blocks a merge, so hiding it would leave the user with
140 // nothing to commit and no way forward.
141 bool untracked = ( fileStatus.gitStatus & GIT_STATUS_WT_NEW )
142 && !( fileStatus.gitStatus & GIT_STATUS_INDEX_NEW );
143
144 if( untracked )
145 {
146 // Use the session prefix so a project opened through a symlink has the same paths.
147 const wxString pathPrefix = relativePath.Left( prefix->length() );
148
149#ifdef __WINDOWS__
150 bool inProject = pathPrefix.CmpNoCase( *prefix ) == 0;
151#else
152 bool inProject = pathPrefix == *prefix;
153#endif
154
155 if( inProject
156 && KIGIT::PROJECT_GIT_UTILS::IsTransientGitFile( wxFileName( relativePath.Mid( prefix->length() ) ) ) )
157 {
158 continue;
159 }
160 }
161
163 entry.section = _( "Changes" );
164 entry.path = relativePath;
165 entry.status = word;
166 entry.statusColour = colour;
167 entry.icon = icon;
168 entry.checked = true;
169 entries.push_back( entry );
170 }
171
172 return entries;
173}
174
175
176namespace
177{
178
179struct EDITOR_DOC
180{
181 FRAME_T frameType;
182 MAIL_T reloadMail;
183 MAIL_T settingsMail;
184};
185
186
187const EDITOR_DOC g_editorDocs[] = {
190};
191
192
193// Nanosecond stamp on POSIX, because wxFileName truncates to whole seconds there. A same-size
194// rewrite in the same second as the save before it would otherwise be missed.
195bool makeFileStamp( const wxFileName& aFn, FILE_STAMP& aOut )
196{
197 if( !aFn.IsOk() || !aFn.FileExists() )
198 return false;
199
200 wxString path = aFn.GetFullPath();
201
202#ifdef __WINDOWS__
203 aOut.modified = aFn.GetModificationTime().GetValue().GetValue();
204#else
205 struct stat st;
206
207 if( stat( path.fn_str(), &st ) != 0 )
208 return false;
209
210#ifdef __APPLE__
211 aOut.modified = static_cast<long long>( st.st_mtimespec.tv_sec ) * 1000000000LL + st.st_mtimespec.tv_nsec;
212#else
213 aOut.modified = static_cast<long long>( st.st_mtim.tv_sec ) * 1000000000LL + st.st_mtim.tv_nsec;
214#endif
215#endif
216
217 aOut.size = static_cast<long long>( aFn.GetSize().GetValue() );
218 return true;
219}
220
221
222// Add aFn to the snapshot when it exists on disk.
223void addFileToSnapshot( DOCUMENT_SNAPSHOT& aSnapshot, const wxFileName& aFn )
224{
225 FILE_STAMP stamp;
226
227 if( makeFileStamp( aFn, stamp ) )
228 aSnapshot.files[aFn.GetFullPath()] = stamp;
229}
230
231
232// A schematic document spans every sheet file, not just the root the frame names.
233DOCUMENT_SNAPSHOT documentSnapshot( KIWAY& aKiway, FRAME_T aFrameType )
234{
236 KIWAY_PLAYER* player = aKiway.Player( aFrameType, false );
237
238 if( !player )
239 return result;
240
241 addFileToSnapshot( result, wxFileName( player->GetCurrentFileName() ) );
242
243 if( aFrameType == FRAME_SCH )
244 {
245 // A shared hierarchy can reference sheets above the project directory, and a pull can
246 // rewrite anything in the repository, so scan from the repository root.
247 wxString scanRoot = player->Prj().GetGitCommon()->GetProjectDir();
248
249 if( scanRoot.IsEmpty() )
250 scanRoot = player->Prj().GetProjectPath();
251
252 if( !scanRoot.IsEmpty() )
253 {
254 wxArrayString sheetFiles;
255 wxDir::GetAllFiles( scanRoot, &sheetFiles, wxS( "*.kicad_sch" ), wxDIR_FILES | wxDIR_DIRS );
256 sheetFiles.Sort();
257
258 for( const wxString& sheet : sheetFiles )
259 addFileToSnapshot( result, wxFileName( sheet ) );
260 }
261 }
262
263 return result;
264}
265
266// A pull or branch switch can change the settings files on their own, and the loaded settings
267// object would write the old values back on the next save.
268DOCUMENT_SNAPSHOT settingsSnapshot()
269{
271 PROJECT& prj = Pgm().GetSettingsManager().Prj();
272
273 if( prj.GetProjectFullName().IsEmpty() )
274 return result;
275
276 wxFileName prl( prj.GetProjectFullName() );
278
279 addFileToSnapshot( result, wxFileName( prj.GetProjectFullName() ) );
280 addFileToSnapshot( result, prl );
281 return result;
282}
283
284
285// The files whose on-disk identity differs, including those present in only one snapshot.
286std::set<wxString> changedFilesBetween( const DOCUMENT_SNAPSHOT& aBefore, const DOCUMENT_SNAPSHOT& aAfter )
287{
288 std::set<wxString> changed;
289
290 for( const auto& [path, stamp] : aBefore.files )
291 {
292 auto it = aAfter.files.find( path );
293
294 if( it == aAfter.files.end() || it->second != stamp )
295 changed.insert( path );
296 }
297
298 for( const auto& [path, stamp] : aAfter.files )
299 {
300 if( !aBefore.files.count( path ) )
301 changed.insert( path );
302 }
303
304 return changed;
305}
306
307} // namespace
308
309
311{
312 EDITOR_SNAPSHOT before;
313
314 for( const EDITOR_DOC& doc : g_editorDocs )
315 before.editors[doc.frameType] = documentSnapshot( aKiway, doc.frameType );
316
317 before.settings = settingsSnapshot();
318
319 return before;
320}
321
322
323void ReloadOpenEditors( KIWAY& aKiway, const EDITOR_SNAPSHOT& aBefore )
324{
325 // Reread the settings first, so a reloading editor gets the fresh values and the next save
326 // does not write the old ones back.
327 bool settingsChanged = !changedFilesBetween( aBefore.settings, settingsSnapshot() ).empty();
328
329 if( settingsChanged )
330 {
331 PROJECT& prj = Pgm().GetSettingsManager().Prj();
332
335 }
336
337 const DOCUMENT_SNAPSHOT noFiles;
338
339 for( const EDITOR_DOC& doc : g_editorDocs )
340 {
341 if( !aKiway.Player( doc.frameType, false ) )
342 continue;
343
344 // Reloading throws away undo history and the view state, so only do it for a document
345 // whose file actually changed on disk.
346 auto it = aBefore.editors.find( doc.frameType );
347 const DOCUMENT_SNAPSHOT& before = it == aBefore.editors.end() ? noFiles : it->second;
348 std::set<wxString> changed = changedFilesBetween( before, documentSnapshot( aKiway, doc.frameType ) );
349
350 if( changed.empty() )
351 {
352 // Settings that changed on their own still have to reach the live editor: the board
353 // caches resolved netclasses per net, and routing would keep using the old values.
354 if( settingsChanged )
355 {
356 std::string settingsPayload;
357 aKiway.ExpressMail( doc.frameType, doc.settingsMail, settingsPayload );
358 }
359
360 continue;
361 }
362
363 // The editor skips the reload when no changed file belongs to its document. The schematic
364 // snapshot spans the repository, and another project's change must not cost this one its undo.
365 wxString joined;
366
367 for( const wxString& path : changed )
368 joined += path + wxS( "\n" );
369
370 std::string payload = joined.utf8_string();
371 aKiway.ExpressMail( doc.frameType, doc.reloadMail, payload );
372 }
373}
374
375
376namespace
377{
378
379// Keep window trackers together on the UI thread. Worker dispatch copies only this context's
380// shared pointer, so it never adds or removes weak-reference nodes on a live window.
381struct WORKTREE_QUERY_CONTEXT
382{
383 WORKTREE_QUERY_CONTEXT( EDA_BASE_FRAME* aFrame, wxWindow* aParent ) :
384 frame( aFrame ),
385 parent( aParent ? aParent : aFrame ),
386 session( aFrame->Prj().GetGitCommon() )
387 {
388 }
389
390 bool IsAlive() const
391 {
392 return frame.get() && parent.get() && !frame->IsBeingDeleted() && !parent->IsBeingDeleted();
393 }
394
395 bool IsCurrent() const
396 {
397 return IsAlive() && !session->IsShuttingDown() && frame->Prj().GetGitCommon() == session
399 && !frame->Prj().GetLocalSettings().m_GitIntegrationDisabled;
400 }
401
402 wxWeakRef<EDA_BASE_FRAME> frame;
403 wxWeakRef<wxWindow> parent;
404 std::shared_ptr<KIGIT_COMMON> session;
405};
406
407
408// These checks precede UI confirmations, so they are snapshots rather than part of a write
409// transaction. The backend still validates the working tree under the mutation's own lock.
410void checkProjectWorktree( EDA_BASE_FRAME* aFrame, wxWindow* aParent, KIGIT_QUERY& aQuery,
411 std::function<void( const wxString&, const GIT_WORKTREE_STATUS& )> aReady,
412 std::function<void()> aFinished = {} )
413{
414 struct OUTCOME
415 {
416 GIT_WORKTREE_STATUS worktree;
417 wxString currentBranch;
418 };
419
420 wxString projectPath = aFrame->Prj().GetProjectPath();
421 auto context = std::make_shared<WORKTREE_QUERY_CONTEXT>( aFrame, aParent );
422 auto outcome = std::make_shared<OUTCOME>();
423
424 aQuery.Run(
425 context->session,
426 [outcome, projectPath]( KIGIT_COMMON& aCommon )
427 {
428 outcome->currentBranch = aCommon.GetCurrentBranchName();
429 outcome->worktree = ReadGitWorktreeStatus( aCommon, projectPath );
430 },
431 [context, outcome, aReady, aFinished]()
432 {
433 auto proceed = [&]()
434 {
435 if( !context->IsCurrent() )
436 {
437 return;
438 }
439
440 if( !ProjectSafeToRewrite( context->frame, context->parent, outcome->worktree ) )
441 return;
442
443 aReady( outcome->currentBranch, outcome->worktree );
444 };
445
446 proceed();
447
448 if( aFinished && context->IsAlive() )
449 {
450 aFinished();
451 }
452 } );
453}
454
455} // namespace
456
457
458void ProjectClearOfUncommittedWork( EDA_BASE_FRAME* aFrame, wxWindow* aParent, KIGIT_QUERY& aQuery,
459 std::function<void( const GIT_WORKTREE_STATUS& )> aReady )
460{
461 checkProjectWorktree( aFrame, aParent, aQuery,
462 [aReady]( const wxString&, const GIT_WORKTREE_STATUS& aStatus )
463 {
464 aReady( aStatus );
465 } );
466}
467
468
469void SwitchProjectToBranch( EDA_BASE_FRAME* aFrame, wxWindow* aParent, const wxString& aBranch, KIGIT_QUERY& aQuery,
470 std::function<void()> aFinished )
471{
472 if( aBranch.IsEmpty() )
473 {
474 if( aFinished )
475 aFinished();
476
477 return;
478 }
479
480 auto context = std::make_shared<WORKTREE_QUERY_CONTEXT>( aFrame, aParent );
481
482 checkProjectWorktree(
483 aFrame, aParent, aQuery,
484 [context, aBranch]( const wxString& aCurrentBranch, const GIT_WORKTREE_STATUS& aStatus )
485 {
486 const wxWeakRef<EDA_BASE_FRAME>& frame = context->frame;
487 const wxWeakRef<wxWindow>& parent = context->parent;
488 const std::shared_ptr<KIGIT_COMMON>& common = context->session;
489
490 if( aBranch == aCurrentBranch )
491 return;
492
493 if( !IsOK( parent, wxString::Format( _( "Switch to branch '%s'? This replaces the project files "
494 "on disk with that branch's version." ),
495 aBranch ) ) )
496 {
497 return;
498 }
499
500 // The confirmation runs a nested event loop and may have closed the project.
501 if( !context->IsCurrent() )
502 {
503 return;
504 }
505
506 // The confirmation may have allowed new edits. Saving them here would create
507 // the uncommitted files that the checkout refuses to overwrite.
508 if( !ProjectSafeToRewrite( frame, parent, aStatus ) )
509 return;
510
511 if( !context->IsCurrent() )
512 {
513 return;
514 }
515
516 EDITOR_SNAPSHOT docsBefore = CaptureOpenEditorDocs( frame->Kiway() );
518 KIGIT_ERROR_MESSAGE resultError;
519
520 {
521 std::unique_lock<std::mutex> lock = KIGIT::TryLockAction( *common, parent );
522
523 if( !lock.owns_lock() )
524 return;
525
526 GIT_BRANCH_HANDLER handler( common.get() );
527 result = handler.SwitchToBranch( aBranch );
528 resultError = handler.PopError();
529
530 // The next transfer must use the new branch's upstream and credentials.
531 // Update them before releasing the same lock that protects the checkout.
533 common->UpdateCurrentBranchInfo();
534 }
535
537 {
538 DisplayInfoMessage( parent, resultError.summary );
539 return;
540 }
541
543 {
544 if( resultError.summary.IsEmpty() )
545 {
546 DisplayErrorMessage( parent,
547 wxString::Format( _( "Could not switch to branch '%s'." ), aBranch ),
549 }
550 else
551 {
552 DisplayErrorMessage( parent, resultError.summary, resultError.details );
553 }
554
555 return;
556 }
557
558 ReloadOpenEditors( frame->Kiway(), docsBefore );
559 common->NotifyRefreshListeners();
560 },
561 std::move( aFinished ) );
562}
563
564
565namespace
566{
567
568enum class EDITOR_SCOPE
569{
570 DOCUMENTS,
571 LIBRARIES,
572 ALL
573};
574
575
576struct GIT_EDITOR
577{
578 FRAME_T frameType;
579 const wxChar* label;
580 MAIL_T saveMail;
581 bool library;
582};
583
584
585const GIT_EDITOR g_gitEditors[] = {
586 { FRAME_SCH, _HKI( "Schematic Editor" ), MAIL_SCH_SAVE, false },
587 { FRAME_PCB_EDITOR, _HKI( "PCB Editor" ), MAIL_PCB_SAVE, false },
588 { FRAME_SCH_SYMBOL_EDITOR, _HKI( "Symbol Editor" ), MAIL_LIB_SAVE_ALL, true },
589 { FRAME_FOOTPRINT_EDITOR, _HKI( "Footprint Editor" ), MAIL_LIB_SAVE_ALL, true },
590};
591
592
593// Keep editor identifiers across prompts, since a prompt can outlive an editor window.
594std::vector<const GIT_EDITOR*> dirtyEditors( KIWAY& aKiway, EDITOR_SCOPE aScope )
595{
596 std::vector<const GIT_EDITOR*> dirty;
597
598 for( const GIT_EDITOR& editor : g_gitEditors )
599 {
600 bool document = !editor.library;
601
602 if( ( aScope == EDITOR_SCOPE::DOCUMENTS && !document ) || ( aScope == EDITOR_SCOPE::LIBRARIES && document ) )
603 {
604 continue;
605 }
606
607 KIWAY_PLAYER* player = aKiway.Player( editor.frameType, false );
608
609 if( !player )
610 continue;
611
612 // A library editor's inactive tabs are invisible to IsContentModified
613 if( editor.library )
614 {
615 std::string payload;
616 aKiway.ExpressMail( editor.frameType, MAIL_LIB_HAS_UNSAVED, payload );
617
618 if( payload == "yes" )
619 dirty.push_back( &editor );
620 }
621 else if( player->IsContentModified() )
622 {
623 dirty.push_back( &editor );
624 }
625 }
626
627 return dirty;
628}
629
630
631enum class EDITOR_SAVE
632{
633 NONE_NEEDED,
634 SAVED,
635 CANCELLED
636};
637
638
640EDITOR_SAVE saveEditorsBeforeRewrite( EDA_BASE_FRAME* aFrame, wxWindow* aParent, EDITOR_SCOPE aScope )
641{
642 std::vector<const GIT_EDITOR*> dirty = dirtyEditors( aFrame->Kiway(), aScope );
643
644 if( dirty.empty() )
645 return EDITOR_SAVE::NONE_NEEDED;
646
647 wxString listed;
648
649 for( const GIT_EDITOR* editor : dirty )
650 listed += wxString::Format( wxS( "\n - %s" ), wxGetTranslation( editor->label ) );
651
652 bool libraries = aScope == EDITOR_SCOPE::LIBRARIES;
653 wxString message = libraries ? _( "The following editors have unsaved library changes:%s\n\n"
654 "This rewrites files on disk. Save the libraries first, "
655 "otherwise the next save would overwrite what arrives." )
656 : _( "The following editors have unsaved changes:%s\n\n"
657 "This rewrites those files on disk. They must be saved "
658 "first, otherwise the next save would overwrite what "
659 "arrives." );
660
661 wxRichMessageDialog dlg( aParent, wxString::Format( message, listed ),
662 libraries ? _( "Unsaved Library Changes" ) : _( "Unsaved Changes" ),
663 wxYES_NO | wxYES_DEFAULT | wxICON_WARNING | wxCENTER );
664 dlg.SetYesNoLabels( libraries ? _( "&Save All and Continue" ) : _( "&Save and Continue" ), _( "Cancel" ) );
665
666 if( dlg.ShowModal() != wxID_YES )
667 return EDITOR_SAVE::CANCELLED;
668
669 for( const GIT_EDITOR* editor : dirty )
670 {
671 std::string payload;
672 aFrame->Kiway().ExpressMail( editor->frameType, editor->saveMail, payload );
673
674 if( payload != "success" )
675 {
676 DisplayErrorMessage( aParent,
677 wxString::Format( _( "Could not save %s." ), wxGetTranslation( editor->label ) ) );
678 return EDITOR_SAVE::CANCELLED;
679 }
680 }
681
682 return EDITOR_SAVE::SAVED;
683}
684
685
686std::vector<wxString> dirtyEditorNames( KIWAY& aKiway, EDITOR_SCOPE aScope )
687{
688 std::vector<wxString> names;
689
690 for( const GIT_EDITOR* editor : dirtyEditors( aKiway, aScope ) )
691 names.push_back( wxGetTranslation( editor->label ) );
692
693 return names;
694}
695
696} // namespace
697
698
700{
701 return !dirtyEditors( aKiway, EDITOR_SCOPE::DOCUMENTS ).empty();
702}
703
704
705bool EditorsDirty( KIWAY& aKiway )
706{
707 return !dirtyEditors( aKiway, EDITOR_SCOPE::ALL ).empty();
708}
709
710
711std::vector<wxString> LibraryEditorsWithUnsavedChanges( KIWAY& aKiway )
712{
713 return dirtyEditorNames( aKiway, EDITOR_SCOPE::LIBRARIES );
714}
715
716
717std::vector<wxString> ChangedTrackedFilesOutsideProject( KIGIT_COMMON& aCommon, const wxString& aProjectPath )
718{
719 std::vector<wxString> paths;
720
721 if( !aCommon.GetRepo() )
722 return paths;
723
724 GIT_STATUS_HANDLER handler( &aCommon );
725 wxString workDir = handler.GetWorkingDirectory();
726
727 for( const auto& [path, fileStatus] : handler.GetFileStatus( wxEmptyString, /* changed only */ true ) )
728 {
729 // The display status groups untracked and staged new files together. Only raw flags
730 // distinguish changes to tracked files from untracked siblings that do not block this.
731 if( ( fileStatus.gitStatus & ~( GIT_STATUS_WT_NEW | GIT_STATUS_IGNORED ) ) == GIT_STATUS_CURRENT )
732 {
733 continue;
734 }
735
737 continue;
738
739 wxString relativePath = path;
740
741 if( relativePath.StartsWith( workDir ) )
742 relativePath = relativePath.Mid( workDir.length() );
743
744 paths.push_back( relativePath );
745 }
746
747 return paths;
748}
749
750
751GIT_WORKTREE_STATUS ReadGitWorktreeStatus( KIGIT_COMMON& aCommon, const wxString& aProjectPath )
752{
753 GIT_WORKTREE_STATUS status;
754
755 if( !aCommon.GetRepo() )
756 return status;
757
758 status.hasTrackedChanges = aCommon.HasUncommittedTrackedChanges( &status.checked );
760
761 // A sibling project's tracked edits block the same repository-wide rewrite.
762 if( status.hasTrackedChanges )
763 status.outsideProject = ChangedTrackedFilesOutsideProject( aCommon, aProjectPath );
764
765 return status;
766}
767
768
769wxString GIT_WORKTREE_STATUS::RefusalMessage( const std::vector<wxString>& aUnsavedEditors,
770 bool aAllowTrackedChanges ) const
771{
772 if( !aUnsavedEditors.empty() )
773 {
774 wxString listed;
775
776 for( const wxString& name : aUnsavedEditors )
777 listed += wxString::Format( wxS( "\n - %s" ), name );
778
779 wxString message = aAllowTrackedChanges
780 ? _( "The following editors have unsaved changes:%s\n\n"
781 "Save or discard those changes before stashing." )
782 : _( "The following editors have unsaved changes:%s\n\n"
783 "Save or discard those changes first. If saving leaves uncommitted "
784 "files, commit or stash them before trying again." );
785
786 return wxString::Format( message, listed );
787 }
788
789 if( !checked )
790 return _( "Could not check the working files. Try again before rewriting project files." );
791
792 if( !lfsMessage.IsEmpty() )
793 return lfsMessage;
794
795 if( !hasTrackedChanges || aAllowTrackedChanges )
796 return wxEmptyString;
797
798 if( !outsideProject.empty() )
799 {
800 wxString listed;
801
802 for( const wxString& path : outsideProject )
803 listed += wxS( "\n " ) + path;
804
805 return wxString::Format( _( "There are uncommitted changes elsewhere in this repository:%s\n\n"
806 "Commit or discard them from that project first, then try again." ),
807 listed );
808 }
809
810 return _( "There are changes that are not committed yet, and this would run over them. "
811 "Commit them first, or set them aside with Stash Changes." );
812}
813
814
815bool ProjectSafeToRewrite( EDA_BASE_FRAME* aFrame, wxWindow* aParent, const GIT_WORKTREE_STATUS& aStatus,
816 bool aAllowTrackedChanges )
817{
818 wxWindow* parent = aParent ? aParent : aFrame;
819
820 switch( saveEditorsBeforeRewrite( aFrame, parent, EDITOR_SCOPE::LIBRARIES ) )
821 {
822 case EDITOR_SAVE::CANCELLED: return false;
823 case EDITOR_SAVE::NONE_NEEDED: break;
824
825 case EDITOR_SAVE::SAVED:
826 // aStatus predates the save, and the saved edits are now uncommitted changes of their own
827 DisplayInfoMessage( parent, aAllowTrackedChanges
828 ? _( "The libraries were saved. Choose the command again to continue." )
829 : _( "The libraries were saved. Commit those changes, or set them "
830 "aside with Stash Changes, then choose the command again." ) );
831 return false;
832 }
833
834 std::vector<wxString> unsaved = dirtyEditorNames( aFrame->Kiway(), EDITOR_SCOPE::ALL );
835 wxString message = aStatus.RefusalMessage( unsaved, aAllowTrackedChanges );
836
837 if( message.IsEmpty() )
838 return true;
839
840 DisplayInfoMessage( parent, message );
841 return false;
842}
843
844
845bool PrepareEditorsForGitOperation( EDA_BASE_FRAME* aFrame, GIT_EDITOR_PREP aPurpose, bool* aSavedEditors )
846{
847 if( aSavedEditors )
848 *aSavedEditors = false;
849
850 // Rewriting a file an editor holds would let its next save overwrite what arrived, so the only choices
851 // are to save or to cancel
852 if( aPurpose == GIT_EDITOR_PREP::WORKING_TREE )
853 {
854 for( EDITOR_SCOPE scope : { EDITOR_SCOPE::LIBRARIES, EDITOR_SCOPE::DOCUMENTS } )
855 {
856 EDITOR_SAVE saved = saveEditorsBeforeRewrite( aFrame, aFrame, scope );
857
858 if( saved == EDITOR_SAVE::CANCELLED )
859 return false;
860
861 if( saved == EDITOR_SAVE::SAVED && aSavedEditors )
862 *aSavedEditors = true;
863 }
864
865 return true;
866 }
867
868 std::vector<const GIT_EDITOR*> dirty = dirtyEditors( aFrame->Kiway(), EDITOR_SCOPE::DOCUMENTS );
869
870 if( dirty.empty() )
871 return true;
872
873 wxString listed;
874
875 for( const GIT_EDITOR* editor : dirty )
876 listed += wxString::Format( wxS( "\n - %s" ), wxGetTranslation( editor->label ) );
877
878 wxRichMessageDialog dlg( aFrame,
879 wxString::Format( _( "The following editors have unsaved changes:%s\n\n"
880 "Save them and review the updated file list before committing?" ),
881 listed ),
882 _( "Unsaved Changes" ), wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxICON_WARNING | wxCENTER );
883 dlg.SetYesNoCancelLabels( _( "&Save and Review" ), _( "Commit &Anyway" ), _( "Cancel" ) );
884
885 int answer = dlg.ShowModal();
886
887 if( answer == wxID_CANCEL )
888 return false;
889
890 if( answer == wxID_YES )
891 {
892 for( const GIT_EDITOR* editor : dirty )
893 {
894 std::string payload;
895 aFrame->Kiway().ExpressMail( editor->frameType, editor->saveMail, payload );
896
897 if( payload != "success" )
898 {
899 DisplayErrorMessage( aFrame,
900 wxString::Format( _( "Could not save %s." ), wxGetTranslation( editor->label ) ) );
901 return false;
902 }
903 }
904
905 // Include project changes from saving editors only when the user chose to save.
906 aFrame->GetSettingsManager()->SaveProject();
907
908 if( aSavedEditors )
909 *aSavedEditors = true;
910 }
911
912 return true;
913}
914
915
917{
918 m_root.MakeDirectory( wxS( "kicad_gitdiff_" ), 0700 );
919}
920
921
922wxString GIT_DIFF_WORKSPACE::Materialize( git_repository* aRepo, const wxString& aRef, const wxString& aRelPath,
924{
925 if( !IsOk() )
926 return wxEmptyString;
927
928 const wxString sep = wxFileName::GetPathSeparator();
929
930 // A schematic root sheet references its sub-sheet files by relative path, so check out the
931 // whole tree and the sub-sheets come along. A board is self-contained, so write just the blob.
932 if( aKind == KICAD_DIFF::DOC_KIND::SCH )
933 {
934 wxString dir = Root() + sep + wxString::Format( wxS( "s%d" ), m_slot++ );
935
936 if( !KIGIT::PROJECT_GIT_UTILS::WriteTreeToDir( aRepo, aRef, dir ) )
937 return wxEmptyString;
938
939 wxString path = dir + sep + aRelPath;
940
941 return wxFileName::FileExists( path ) ? path : wxString( wxEmptyString );
942 }
943
944 wxString path = Root() + sep + wxString::Format( wxS( "s%d_" ), m_slot++ ) + wxFileName( aRelPath ).GetFullName();
945
946 if( !KIGIT::PROJECT_GIT_UTILS::WriteBlobToFile( aRepo, aRef, aRelPath, path ) )
947 return wxEmptyString;
948
949 return path;
950}
951
952
953namespace
954{
955
961struct MODAL_GIT_DIFF_REQUEST
962{
963 MODAL_GIT_DIFF_REQUEST( EDA_BASE_FRAME* aFrame, wxWindow* aParent ) :
964 frame( aFrame ),
965 parent( aParent ),
966 session( aFrame->Prj().GetGitCommon() )
967 {
968 }
969
970 bool IsCurrent() const
971 {
972 return frame.get() && parent.get() && !frame->IsBeingDeleted() && !parent->IsBeingDeleted()
973 && frame->Prj().GetGitCommon() == session && !session->IsShuttingDown();
974 }
975
976 wxWeakRef<EDA_BASE_FRAME> frame;
977 wxWeakRef<wxWindow> parent;
978 std::shared_ptr<KIGIT_COMMON> session;
979 KIGIT_QUERY query;
980};
981
982
983struct MODAL_GIT_DIFF_RESULT
984{
985 std::unique_ptr<GIT_DIFF_WORKSPACE> workspace;
986 GIT_FILE_SIDES sides;
987 std::vector<KIGIT::TEXT_DIFF_LINE> textLines;
988 bool ready = false;
989};
990
991
992std::string readDiffText( const wxString& aPath )
993{
994 if( aPath.IsEmpty() )
995 return {};
996
997 std::ifstream in( aPath.fn_str(), std::ios::binary );
998 return std::string( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
999}
1000
1001
1002// A named file can be loaded directly. Otherwise ShowGitCommitDiff obtains the choice first.
1003// An empty commit hash compares HEAD with the working copy.
1004void loadModalGitDiff( const std::shared_ptr<MODAL_GIT_DIFF_REQUEST>& aRequest, const wxString& aRelativePath,
1005 const wxString& aCommitHash )
1006{
1007 auto result = std::make_shared<MODAL_GIT_DIFF_RESULT>();
1008 result->sides.error = _( "Could not compare this file." );
1009
1010 aRequest->query.Run(
1011 aRequest->session,
1012 [result, aRelativePath, aCommitHash]( KIGIT_COMMON& aCommon )
1013 {
1014 result->workspace = std::make_unique<GIT_DIFF_WORKSPACE>();
1015
1016 if( !result->workspace->IsOk() )
1017 {
1018 result->sides.error = _( "Could not create a temporary directory for the diff." );
1019 return;
1020 }
1021
1022 bool materialized =
1023 aCommitHash.IsEmpty()
1024 ? MaterializeWorkingFile( aCommon, *result->workspace, aRelativePath, result->sides )
1025 : MaterializeCommitFile( aCommon, *result->workspace, aCommitHash, aRelativePath,
1026 result->sides );
1027
1028 if( !materialized )
1029 return;
1030
1031 if( result->sides.kind == KICAD_DIFF::DOC_KIND::UNKNOWN )
1032 {
1033 std::string before = readDiffText( result->sides.before );
1034 std::string after = readDiffText( result->sides.after );
1035
1036 if( KIGIT::TextLooksBinary( before ) || KIGIT::TextLooksBinary( after ) )
1037 {
1038 result->sides.error = wxString::Format(
1039 _( "'%s' is not a plain text file. KiCad compares design files and text files "
1040 "only, so there is no comparison to show." ),
1041 aRelativePath );
1042 return;
1043 }
1044
1045 result->textLines =
1047 }
1048
1049 result->ready = true;
1050 },
1051 [aRequest, result, aRelativePath, aCommitHash]()
1052 {
1053 if( !aRequest->IsCurrent() )
1054 return;
1055
1056 wxWindow* parent = aRequest->parent.get();
1057
1058 if( !result->ready )
1059 {
1060 if( !result->sides.error.IsEmpty() )
1061 DisplayInfoMessage( parent, result->sides.error );
1062
1063 return;
1064 }
1065
1066 if( result->sides.kind == KICAD_DIFF::DOC_KIND::UNKNOWN )
1067 {
1068 DIALOG_TEXT_DIFF dlg( parent, aRelativePath, result->textLines );
1069 dlg.ShowModal();
1070 return;
1071 }
1072
1073 wxString beforeLabel = aCommitHash.IsEmpty()
1074 ? _( "BASE (HEAD)" )
1075 : wxString::Format( _( "PARENT (of %s)" ), aCommitHash );
1076 wxString afterLabel = aCommitHash.IsEmpty() ? _( "WORKING (changes)" )
1077 : wxString::Format( _( "COMMIT (%s)" ), aCommitHash );
1078
1079 // The owning kiface loads and displays documents on the UI thread. Keep the
1080 // scratch files alive until the modal comparison has closed.
1082 KICAD_DIFF::DispatchOpenDiffDialog( aRequest->frame->Kiway(), result->sides.kind, result->sides.before,
1083 result->sides.after, beforeLabel, afterLabel, parent, &reporter );
1084
1085 if( aRequest->IsCurrent() && reporter.HasMessage() )
1086 DisplayErrorMessage( parent, _( "Could not open the diff." ), reporter.GetMessages() );
1087 } );
1088}
1089
1090} // namespace
1091
1092
1093void ChangeGitIgnore( EDA_BASE_FRAME* aFrame, wxWindow* aParent, GIT_IGNORE_CHANGE aChange,
1094 const std::vector<GIT_IGNORE_TARGET>& aTargets )
1095{
1096 std::shared_ptr<KIGIT_COMMON> common = aFrame->Prj().GetGitCommon();
1097
1098 if( !common->GetRepo() || aTargets.empty() )
1099 return;
1100
1101 const bool ignoring = aChange == GIT_IGNORE_CHANGE::IGNORE_PATH || aChange == GIT_IGNORE_CHANGE::IGNORE_EXTENSION;
1102 const bool byExtension =
1104 const wxFileName ignoreFile = KIGIT::ProjectIgnoreFile( aFrame->Prj().GetProjectPath() );
1105
1106 std::vector<wxString> rules;
1107
1108 for( const GIT_IGNORE_TARGET& target : aTargets )
1109 {
1110 wxString rule = byExtension ? KIGIT::ExtensionIgnoreRule( target.path )
1111 : KIGIT::PathIgnoreRule( target.path, target.isDirectory );
1112
1113 if( !rule.IsEmpty() )
1114 rules.push_back( rule );
1115 }
1116
1117 if( rules.empty() )
1118 return;
1119
1120 wxString error;
1121 bool written = ignoring ? KIGIT::AddIgnoreRules( ignoreFile, rules, wxEmptyString, error )
1122 : KIGIT::RemoveIgnoreRules( ignoreFile, rules, error );
1123
1124 if( !written )
1125 {
1126 DisplayErrorMessage( aParent, _( "Could not change which files are ignored." ), error );
1127 return;
1128 }
1129
1130 common->NotifyRefreshListeners();
1131
1132 if( ignoring )
1133 return;
1134
1135 std::vector<wxString> stillIgnored;
1136
1137 {
1138 // Only to explain the result, so a busy repository is not worth waiting for.
1139 std::unique_lock<std::mutex> lock = common->TryLockAction();
1140
1141 if( !lock.owns_lock() )
1142 return;
1143
1144 for( const GIT_IGNORE_TARGET& target : aTargets )
1145 {
1146 if( KIGIT::IgnoreState( *common, target.path, target.isDirectory ).ignored )
1147 stillIgnored.push_back( target.path );
1148 }
1149 }
1150
1151 if( stillIgnored.empty() )
1152 return;
1153
1154 const wxString message =
1155 stillIgnored.size() == 1
1156 ? wxString::Format( _( "'%s' is still ignored by another rule." ), stillIgnored.front() )
1157 : wxString::Format( _( "%zu of the selected files are still ignored by another rule." ),
1158 stillIgnored.size() );
1159
1160 DisplayInfoMessage( aParent, message,
1161 wxString::Format( _( "That rule covers more than this, so it was left in "
1162 "place. Edit '%s' to change it." ),
1163 ignoreFile.GetFullPath() ) );
1164}
1165
1166
1167void ShowGitFileDiff( EDA_BASE_FRAME* aFrame, const wxString& aRelativePath )
1168{
1169 auto request = std::make_shared<MODAL_GIT_DIFF_REQUEST>( aFrame, aFrame );
1170 loadModalGitDiff( request, aRelativePath, wxEmptyString );
1171}
1172
1173
1174bool MaterializeWorkingFile( KIGIT_COMMON& aCommon, GIT_DIFF_WORKSPACE& aWorkspace, const wxString& aRelativePath,
1175 GIT_FILE_SIDES& aSides )
1176{
1177 git_repository* repo = aCommon.GetRepo();
1178
1179 if( !repo )
1180 return false;
1181
1182 aSides.kind = KICAD_DIFF::DocKindFromExtension( aRelativePath );
1183
1184 GIT_STATUS_HANDLER handler( &aCommon );
1185 aSides.after = handler.GetWorkingDirectory() + aRelativePath;
1186
1187 // A new file has no committed version, so that side stays empty and shows as added.
1188 bool inHead = aCommon.IsPathInHead( aRelativePath );
1189
1190 if( inHead )
1191 aSides.before = aWorkspace.Materialize( repo, wxT( "HEAD" ), aRelativePath, aSides.kind );
1192
1193 if( inHead && aSides.before.IsEmpty() )
1194 {
1195 aSides.error = wxString::Format( _( "Could not read the committed version of '%s'." ), aRelativePath );
1196 return false;
1197 }
1198
1199 // A deleted file has no working copy, so an empty path makes the loader synthesize an empty
1200 // document instead of failing on a file that is gone.
1201 if( !wxFileName::FileExists( aSides.after ) )
1202 aSides.after.clear();
1203
1204 return true;
1205}
1206
1207
1208void ShowGitCommitDiff( EDA_BASE_FRAME* aFrame, const wxString& aCommitHash, wxWindow* aParentWindow,
1209 const wxString& aRelativePath )
1210{
1211 auto request = std::make_shared<MODAL_GIT_DIFF_REQUEST>( aFrame, aParentWindow ? aParentWindow : aFrame );
1212
1213 // A caller that named a file knows its own list, which for a stash also holds the files
1214 // that were untracked. Those are not in the parent-to-commit diff used by the chooser.
1215 if( !aRelativePath.IsEmpty() )
1216 {
1217 loadModalGitDiff( request, aRelativePath, aCommitHash );
1218 return;
1219 }
1220
1221 auto changedPaths = std::make_shared<std::vector<wxString>>();
1222
1223 request->query.Run(
1224 request->session,
1225 [changedPaths, aCommitHash]( KIGIT_COMMON& aCommon )
1226 {
1227 git_repository* repo = aCommon.GetRepo();
1228 wxString parentRef;
1229 git_object* commitObj = nullptr;
1230
1231 // A root commit has no parent, so compare it against the empty tree.
1232 if( git_revparse_single( &commitObj, repo, aCommitHash.utf8_string().c_str() ) == GIT_OK )
1233 {
1234 if( git_object_type( commitObj ) == GIT_OBJECT_COMMIT
1235 && git_commit_parentcount( reinterpret_cast<git_commit*>( commitObj ) ) > 0 )
1236 {
1237 parentRef = aCommitHash + wxT( "^" );
1238 }
1239
1240 git_object_free( commitObj );
1241 }
1242
1243 for( const KIGIT::CHANGED_FILE& file : KIGIT::CompareRefs( repo, parentRef, aCommitHash ) )
1244 changedPaths->push_back( file.path );
1245 },
1246 [request, changedPaths, aCommitHash]()
1247 {
1248 if( !request->IsCurrent() )
1249 return;
1250
1251 wxWindow* parent = request->parent.get();
1252
1253 if( changedPaths->empty() )
1254 {
1255 DisplayInfoMessage( parent, _( "This commit has no file changes to show." ) );
1256 return;
1257 }
1258
1259 wxString chosen = changedPaths->front();
1260
1261 if( changedPaths->size() > 1 )
1262 {
1263 wxArrayString choices;
1264
1265 for( const wxString& path : *changedPaths )
1266 choices.Add( path );
1267
1268 int sel = wxGetSingleChoiceIndex( _( "This commit changed more than one file. "
1269 "Select one to compare:" ),
1270 _( "Select File to Compare" ), choices, parent );
1271
1272 if( sel < 0 )
1273 return;
1274
1275 chosen = ( *changedPaths )[sel];
1276 }
1277
1278 // A modal chooser may have processed a project close or switch.
1279 if( request->IsCurrent() )
1280 loadModalGitDiff( request, chosen, aCommitHash );
1281 } );
1282}
1283
1284
1285bool MaterializeCommitFile( KIGIT_COMMON& aCommon, GIT_DIFF_WORKSPACE& aWorkspace, const wxString& aCommitHash,
1286 const wxString& aRelativePath, GIT_FILE_SIDES& aSides )
1287{
1288 // The caller may have run a chooser since it last looked, so the project may have closed.
1289 git_repository* repo = aCommon.GetRepo();
1290
1291 if( !repo )
1292 return false;
1293
1294 // A root commit has no "<hash>^". An empty base ref compares it against the empty tree, so
1295 // its files show as added.
1296 wxString parentRef;
1297 git_object* commitObj = nullptr;
1298 unsigned parentCount = 0;
1299
1300 if( git_revparse_single( &commitObj, repo, aCommitHash.utf8_string().c_str() ) == GIT_OK )
1301 {
1302 if( git_object_type( commitObj ) == GIT_OBJECT_COMMIT )
1303 parentCount = git_commit_parentcount( reinterpret_cast<git_commit*>( commitObj ) );
1304
1305 if( parentCount > 0 )
1306 parentRef = aCommitHash + wxT( "^" );
1307
1308 git_object_free( commitObj );
1309 }
1310
1311 for( const KIGIT::CHANGED_FILE& file : KIGIT::CompareRefs( repo, parentRef, aCommitHash ) )
1312 {
1313 if( file.path != aRelativePath )
1314 continue;
1315
1316 aSides.kind = KICAD_DIFF::DocKindFromExtension( file.path );
1317
1318 // Only the side that exists is written out.
1319 bool hasParent = file.status != KIGIT::FILE_CHANGE_STATUS::ADDED;
1320 bool hasCommit = file.status != KIGIT::FILE_CHANGE_STATUS::REMOVED;
1321
1322 if( hasParent )
1323 {
1324 wxString parentPath = file.oldPath.IsEmpty() ? file.path : file.oldPath;
1325 aSides.before = aWorkspace.Materialize( repo, parentRef, parentPath, aSides.kind );
1326 }
1327
1328 if( hasCommit )
1329 aSides.after = aWorkspace.Materialize( repo, aCommitHash, file.path, aSides.kind );
1330
1331 if( ( hasParent && aSides.before.IsEmpty() ) || ( hasCommit && aSides.after.IsEmpty() ) )
1332 {
1333 aSides.error = _( "Could not read this commit's file contents." );
1334 return false;
1335 }
1336
1337 return true;
1338 }
1339
1340 // A stash keeps the files that were untracked when it was taken in a third parent, so they
1341 // are missing from the diff above. Nothing came before them, so only one side has content.
1342 if( parentCount > 2 )
1343 {
1344 aSides.kind = KICAD_DIFF::DocKindFromExtension( aRelativePath );
1345 aSides.after = aWorkspace.Materialize( repo, aCommitHash + wxT( "^3" ), aRelativePath, aSides.kind );
1346
1347 if( !aSides.after.IsEmpty() )
1348 return true;
1349 }
1350
1351 aSides.error = wxString::Format( _( "This commit did not change '%s'." ), aRelativePath );
1352 return false;
1353}
const char * name
BITMAPS
A list of all bitmap identifiers.
@ INVALID_BITMAP
Read-only line diff, for the file types that have no visual diff.
The base frame for deriving all KiCad main window classes.
SETTINGS_MANAGER * GetSettingsManager() const
virtual wxString GetCurrentFileName() const
Get the full filename + path of the currently opened file in the frame.
virtual bool IsContentModified() const
Get if the contents of the frame have been modified since the last save.
BranchResult SwitchToBranch(const wxString &aBranchName)
Switch to the specified branch.
A private scratch directory for extracting committed file versions to diff, removed when this object ...
bool IsOk() const
True when the scratch directory was created.
const wxString & Root() const
The scratch directory, for callers that lay out their own files (e.g. footprint libraries).
wxString Materialize(git_repository *aRepo, const wxString &aRef, const wxString &aRelPath, KICAD_DIFF::DOC_KIND aKind)
Extract aRelPath at aRef into a uniquely named slot and return the path to load, or an empty string w...
SCOPED_TEMP_PATH m_root
std::map< wxString, FileStatus > GetFileStatus(const wxString &aPathspec=wxEmptyString, bool aChangedOnly=false)
Get detailed file status for all files in the specified path.
wxString GetWorkingDirectory()
Get the repository working directory path.
virtual bool LoadFromFile(const wxString &aDirectory="")
Loads the backing file from disk and then calls Load()
wxColour ToColour() const
Definition color4d.cpp:221
static bool WriteBlobToFile(git_repository *aRepo, const wxString &aRef, const wxString &aPath, const wxString &aDestPath)
Write a file as it exists at a git ref to a path on disk, so a committed version can be diffed.
static bool IsTransientGitFile(const wxFileName &aFile)
Match a project-relative path against the shared transient patterns.
static bool WriteTreeToDir(git_repository *aRepo, const wxString &aRef, const wxString &aDestDir)
Check out a whole tree into a directory, leaving the repository's working copy and index alone.
static bool IsWithinProjectPath(const wxString &aAbsPath, const wxString &aProjectPath)
Test whether an absolute file path lives inside the current project directory.
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.
bool HasUncommittedTrackedChanges(bool *aReadOk=nullptr) const
std::optional< wxString > GetProjectPrefix() const
Project folder relative to the repository, with a trailing slash.
git_repository * GetRepo() const
wxString GetProjectDir() const
Return the path set by SetProjectDir(), or the repository's working directory.
bool IsPathInHead(const wxString &aPath)
True when the working directory relative path exists in the HEAD commit's tree.
static wxString GetLastGitError()
libgit2's last message, without credentials from any URL it quotes, so it is safe to show or trace.
KIGIT_ERROR_MESSAGE PopError()
Take the newest error with its details. Both are empty when none is queued.
Read repository state without blocking the UI.
void Run(std::shared_ptr< KIGIT_COMMON > aSession, std::function< void(KIGIT_COMMON &)> aWork, std::function< void()> aDone)
Run aWork under the session's action lock on a worker, then aDone on the UI thread.
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
KIWAY & Kiway() const
Return a reference to the KIWAY that this object has an opportunity to participate in.
A wxFrame capable of the OpenProjectFiles function, meaning it can load a portion of a KiCad project.
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:348
virtual KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=nullptr)
Return the KIWAY_PLAYER* given a FRAME_T.
Definition kiway.cpp:407
virtual void ExpressMail(FRAME_T aDestination, MAIL_T aCommand, std::string &aPayload, wxWindow *aSource=nullptr, bool aFromOtherThread=false)
Send aPayload to aDestination from aSource.
Definition kiway.cpp:511
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:600
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
bool LoadFromFile(const wxString &aDirectory="") override
Loads the backing file from disk and then calls Load()
Container for project specific data.
Definition project.h:63
virtual std::shared_ptr< KIGIT_COMMON > GetGitCommon() const
This project's Git session, created empty on first use.
Definition project.cpp:85
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:271
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:277
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition project.h:207
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:201
bool SaveProject(const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
Save a loaded project.
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
A wrapper for reporting to a wxString object.
Definition reporter.h:242
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 _(s)
Base window classes and related definitions.
FRAME_T
The set of EDA_BASE_FRAME derivatives, typically stored in EDA_BASE_FRAME::m_Ident.
Definition frame_type.h:29
@ FRAME_PCB_EDITOR
Definition frame_type.h:38
@ FRAME_SCH_SYMBOL_EDITOR
Definition frame_type.h:31
@ FRAME_SCH
Definition frame_type.h:30
@ FRAME_FOOTPRINT_EDITOR
Definition frame_type.h:39
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...
void ShowGitCommitDiff(EDA_BASE_FRAME *aFrame, const wxString &aCommitHash, wxWindow *aParentWindow, const wxString &aRelativePath)
Open the diff for what a commit changed, comparing it against its parent.
EDITOR_SNAPSHOT CaptureOpenEditorDocs(KIWAY &aKiway)
Record the on-disk identity of the open documents, before an operation that may rewrite them.
bool MaterializeWorkingFile(KIGIT_COMMON &aCommon, GIT_DIFF_WORKSPACE &aWorkspace, const wxString &aRelativePath, GIT_FILE_SIDES &aSides)
Write the committed version of a file into aWorkspace and name its working copy beside it.
bool MaterializeCommitFile(KIGIT_COMMON &aCommon, GIT_DIFF_WORKSPACE &aWorkspace, const wxString &aCommitHash, const wxString &aRelativePath, GIT_FILE_SIDES &aSides)
Write both sides of one file a commit changed into aWorkspace, the parent's version and the commit's.
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.
std::vector< wxString > LibraryEditorsWithUnsavedChanges(KIWAY &aKiway)
Names of the library editors holding unsaved changes.
void ProjectClearOfUncommittedWork(EDA_BASE_FRAME *aFrame, wxWindow *aParent, KIGIT_QUERY &aQuery, std::function< void(const GIT_WORKTREE_STATUS &)> aReady)
Check the working tree and Git LFS on a worker, then run aReady on the UI thread when the operation c...
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.
static bool statusToDisplay(KIGIT_COMMON::GIT_STATUS aStatus, wxString &aWord, BITMAPS &aIcon, wxColour &aColour, const KICAD_DIFF::DIFF_COLOR_THEME &aTheme)
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.
void SwitchProjectToBranch(EDA_BASE_FRAME *aFrame, wxWindow *aParent, const wxString &aBranch, KIGIT_QUERY &aQuery, std::function< void()> aFinished)
Check the working tree on a worker, then confirm switching to aBranch and recheck unsaved editors.
bool EditorsDirty(KIWAY &aKiway)
Unsaved document or library edits block operations that rewrite files. Call on the UI thread.
GIT_IGNORE_CHANGE
Which change to the project's ignored files a menu item asks for.
@ IGNORE_PATH
Ignore the paths themselves.
@ KEEP_EXTENSION
Stop ignoring every file sharing the paths' extension.
@ IGNORE_EXTENSION
Ignore every file sharing the paths' extension.
GIT_EDITOR_PREP
What the caller is about to do, which decides the wording and whether the project file is written.
@ WORKING_TREE
The working files are about to be rewritten, by a pull, branch switch or stash.
static const std::string ProjectLocalSettingsFileExtension
Some functions to handle hotkeys in KiCad.
std::string message
PROJECT & Prj()
Definition kicad.cpp:730
static std::vector< std::string > changedPaths(git_repository *aRepo)
MAIL_T
The set of mail types sendable via KIWAY::ExpressMail() and supplied as the aCommand parameter to tha...
Definition mail_type.h:34
@ MAIL_SCH_SAVE
Definition mail_type.h:38
@ MAIL_LIB_HAS_UNSAVED
Definition mail_type.h:70
@ MAIL_PCB_RELOAD
Definition mail_type.h:62
@ MAIL_SCH_PROJECT_SETTINGS_CHANGED
Definition mail_type.h:63
@ MAIL_PCB_SAVE
Definition mail_type.h:39
@ MAIL_PCB_PROJECT_SETTINGS_CHANGED
Definition mail_type.h:64
@ MAIL_SCH_RELOAD
Definition mail_type.h:61
@ MAIL_LIB_SAVE_ALL
Definition mail_type.h:69
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.
int DispatchOpenDiffDialog(KIWAY &aKiway, DOC_KIND aKind, const wxString &aFileA, const wxString &aFileB, const wxString &aLabelA, const wxString &aLabelB, wxWindow *aParent, REPORTER *aReporter)
Open DIALOG_KICAD_DIFF on two files by calling the owning kiface's KIFACE_OPEN_DIFF_DIALOG function e...
@ ALL
All except INITIAL_ADD.
Definition view_item.h:55
std::vector< CHANGED_FILE > CompareRefs(git_repository *aRepo, const wxString &aBaseRef, const wxString &aHeadRef)
Compare two git refs (branch / tag / commit OID) within a repository and return the per-file change l...
std::vector< wxString > SplitTextLines(const std::string &aContent)
Tolerates CRLF endings and content that is not valid UTF-8.
Definition text_diff.cpp:28
APIEXPORT bool AddIgnoreRules(const wxFileName &aIgnoreFile, const std::vector< wxString > &aRules, const wxString &aHeader, wxString &aError)
Append rules to an ignore file, creating it with aHeader as a comment when it is not there.
APIEXPORT wxFileName ProjectIgnoreFile(const wxString &aProjectPath)
The ignore file that covers a project.
APIEXPORT bool RemoveIgnoreRules(const wxFileName &aIgnoreFile, const std::vector< wxString > &aRules, wxString &aError)
Remove rules from an ignore file.
APIEXPORT wxString ExtensionIgnoreRule(const wxString &aProjectRelPath)
The rule that ignores every file sharing a path's extension, or nothing when it has none.
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 ...
std::vector< TEXT_DIFF_LINE > BuildTextDiff(const std::vector< wxString > &aOld, const std::vector< wxString > &aNew)
Every line of both sides appears once. There are no hunks and nothing is elided.
Definition text_diff.cpp:77
APIEXPORT wxString PathIgnoreRule(const wxString &aProjectRelPath, bool aIsDirectory)
The rule that ignores one path and nothing else.
@ CANCELLED
Stop and say so, the user cancelled the transfer or a prompt.
#define _HKI(x)
Definition page_info.cpp:40
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
void Format(OUTPUTFORMATTER *out, int aNestLevel, int aCtl, const CPTREE &aTree)
Output a PTREE into s-expression format via an OUTPUTFORMATTER derivative.
Definition ptree.cpp:194
The files making up one open document, each with its on-disk identity.
std::map< wxString, FILE_STAMP > files
What the open editors and the project settings looked like on disk before an operation that may rewri...
std::map< FRAME_T, DOCUMENT_SNAPSHOT > editors
DOCUMENT_SNAPSHOT settings
One file row in a FILE_CHECKLIST_CTRL.
BITMAPS icon
wxString path
Row identity, and what the row shows.
wxColour statusColour
Text colour for the status, or the default when not set.
wxString section
wxString status
Free text, e.g. "Modified".
bool checked
On-disk identity of one file, used to tell whether a git operation rewrote it.
long long modified
Modification time, nanoseconds where the platform provides them.
The two sides of one file, written out for a comparison.
KICAD_DIFF::DOC_KIND kind
wxString before
Empty when the file did not exist on that side.
wxString error
Why the sides could not be written, when they could not.
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.
std::vector< wxString > outsideProject
wxString RefusalMessage(const std::vector< wxString > &aUnsavedEditors, bool aAllowTrackedChanges=false) const
Empty when rewriting is allowed.
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.
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.
Definition of file extensions used in Kicad.