KiCad PCB EDA Suite
Loading...
Searching...
No Matches
local_history.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
20#include <local_history.h>
22#include <history_lock.h>
23#include <paths.h>
25#include <lockfile.h>
28#include <pgm_base.h>
29#include <thread_pool.h>
30#include <trace_helpers.h>
31#include <project.h>
33#include <confirm.h>
34#include <progress_reporter.h>
35#include <kiid.h>
36
37#include <kiplatform/io.h>
38
39#include <git2.h>
40#include <git2/sys/odb_backend.h>
41#include <gestfich.h>
42#include <wx/filename.h>
43#include <wx/filefn.h>
44#include <wx/ffile.h>
45#include <wx/dir.h>
46#include <wx/datetime.h>
47#include <wx/log.h>
48#include <wx/msgdlg.h>
49#include <wx/utils.h>
50
51#include <fstream>
52#include <iterator>
53#include <vector>
54#include <string>
55#include <memory>
56#include <algorithm>
57#include <set>
58#include <map>
59#include <functional>
60#include <chrono>
61#include <cstring>
62
63// Resolve the local-history storage directory for @p aProjectPath, honoring the
64static wxString historyPath( const wxString& aProjectPath )
65{
66 return Pgm().GetSettingsManager().GetLocalHistoryDirForPath( aProjectPath );
67}
68
69
70// Join a saver-supplied relative path with the on-disk storage root for the
71// active backup format and location. Forward slashes in @p aRelativePath are
72// preserved so libgit2 paths remain platform-neutral.
73static wxString joinHistoryDestination( const wxString& aHistoryRoot,
74 const wxString& aRelativePath )
75{
76 wxFileName fn( aRelativePath );
77
78 if( fn.IsAbsolute() )
79 return fn.GetFullPath(); // Defensive: should not happen with the new contract.
80
81 // Prepend the history root while preserving any subdirectories supplied by the saver
82 // (e.g. hierarchical sheet "sub/sheet.kicad_sch" must land at
83 // "<root>/sub/sheet.kicad_sch", not "<root>/sheet.kicad_sch").
84 wxArrayString dirs = fn.GetDirs();
85
86 wxFileName dst;
87 dst.AssignDir( aHistoryRoot );
88
89 for( const wxString& d : dirs )
90 dst.AppendDir( d );
91
92 dst.SetFullName( fn.GetFullName() );
93 return dst.GetFullPath();
94}
95
96
97static const wxString AUTOSAVE_PREFIX = wxS( "_autosave-" );
98
99// Loose bytes that trigger a background compaction when the history has no size limit
100static const size_t UNLIMITED_HISTORY_LOOSE_BYTES = 25 * 1024 * 1024;
101
102
103static bool readFileContent( const wxString& aPath, std::string& aContent )
104{
105 // Not wxFFile, which shows an error dialog for a file that was never saved
106 std::ifstream file( aPath.fn_str(), std::ios::binary );
107
108 if( !file )
109 return false;
110
111 aContent.assign( std::istreambuf_iterator<char>( file ), std::istreambuf_iterator<char>() );
112
113 return !file.bad();
114}
115
116
117// Older versions staged autosaves through a copy of each file beside .git. Nothing reads those
118// copies, and they count against the size limit
119static void removeLegacyWorkingCopies( git_repository* aRepo, const wxString& aHistoryRoot )
120{
121 wxDir histDir( aHistoryRoot );
122 wxString name;
123 bool hasCopies = false;
124 bool cont = histDir.IsOpened()
125 && histDir.GetFirst( &name, wxEmptyString, wxDIR_FILES | wxDIR_DIRS | wxDIR_HIDDEN );
126
127 // Runs on every autosave, so skip the tree walk once nothing but our own files remain
128 while( cont && !hasCopies )
129 {
130 hasCopies = name != wxS( ".git" ) && name != wxS( ".gitignore" ) && name != wxS( "README.txt" );
131 cont = histDir.GetNext( &name );
132 }
133
134 if( !hasCopies )
135 return;
136
137 git_oid headOid;
138 git_commit* head = nullptr;
139 git_tree* tree = nullptr;
140
141 if( git_reference_name_to_id( &headOid, aRepo, "HEAD" ) != 0 || git_commit_lookup( &head, aRepo, &headOid ) != 0 )
142 return;
143
144 if( git_commit_tree( &tree, head ) == 0 )
145 {
146 struct WALK_STATE
147 {
148 wxString root;
149 std::vector<wxString> dirs;
150 } state{ aHistoryRoot, {} };
151
152 git_tree_walk(
153 tree, GIT_TREEWALK_POST,
154 []( const char* aDir, const git_tree_entry* aEntry, void* aPayload ) -> int
155 {
156 auto* walkState = static_cast<WALK_STATE*>( aPayload );
157 wxString rel = wxString::FromUTF8( aDir ) + wxString::FromUTF8( git_tree_entry_name( aEntry ) );
158
159 if( rel.Contains( wxS( ".." ) ) )
160 return 0;
161
162 wxString path = joinHistoryDestination( walkState->root, rel );
163
164 if( git_tree_entry_type( aEntry ) == GIT_OBJECT_TREE )
165 walkState->dirs.push_back( path );
166 else if( wxFileExists( path ) )
167 wxRemoveFile( path );
168
169 return 0;
170 },
171 &state );
172
173 // Post-order walk lists children first, so nested dirs empty out before their parents.
174 // A dir still holding user files fails to delete, which must not raise an error dialog
175 wxLogNull suppressRmdirErrors;
176
177 for( const wxString& dir : state.dirs )
178 {
179 if( wxDirExists( dir ) )
180 wxRmdir( dir );
181 }
182
183 git_tree_free( tree );
184 }
185
186 git_commit_free( head );
187}
188
189
190// Compare two files byte-for-byte.
191static bool filesContentEqual( const wxString& aPathA, const wxString& aPathB )
192{
193 wxFFile fileA( aPathA, wxS( "rb" ) );
194 wxFFile fileB( aPathB, wxS( "rb" ) );
195
196 if( !fileA.IsOpened() || !fileB.IsOpened() )
197 return false;
198
199 wxFileOffset lenA = fileA.Length();
200 wxFileOffset lenB = fileB.Length();
201
202 if( lenA < 0 || lenB < 0 || lenA != lenB )
203 return false;
204
205 constexpr size_t chunkSize = 64 * 1024;
206 std::vector<char> bufA( chunkSize );
207 std::vector<char> bufB( chunkSize );
208
209 while( !fileA.Eof() )
210 {
211 size_t readA = fileA.Read( bufA.data(), chunkSize );
212 size_t readB = fileB.Read( bufB.data(), chunkSize );
213
214 if( readA != readB )
215 return false;
216
217 if( readA > 0 && std::memcmp( bufA.data(), bufB.data(), readA ) != 0 )
218 return false;
219
220 if( fileA.Error() || fileB.Error() )
221 return false;
222 }
223
224 return true;
225}
226
227
228// Resolve the autosave-file destination for a given relative path. In PROJECT_DIR
229// mode the file lives next to the original (or under the same subdir for nested
230// schematic sheets) with an "_autosave-" prefix on the basename. In USER_DIR mode
231// the file mirrors the project tree under the user data root with no name munging
232// -- the per-project hash subdirectory already isolates autosave content.
233static wxString resolveAutosaveDestination( const wxString& aAutosaveRoot,
234 const wxString& aRelativePath,
235 BACKUP_LOCATION aLocation )
236{
237 wxFileName rel( aRelativePath );
238 wxFileName dst;
239 dst.AssignDir( aAutosaveRoot );
240
241 for( const wxString& d : rel.GetDirs() )
242 dst.AppendDir( d );
243
244 if( aLocation == BACKUP_LOCATION::PROJECT_DIR )
245 dst.SetFullName( AUTOSAVE_PREFIX + rel.GetFullName() );
246 else
247 dst.SetFullName( rel.GetFullName() );
248
249 return dst.GetFullPath();
250}
251
252
253// Compute the source-file path that an autosave destination corresponds to.
254// In PROJECT_DIR mode the source is the same directory minus the "_autosave-"
255// prefix. In USER_DIR mode the source is the original under the project tree.
256static wxString sourceForAutosaveFile( const wxString& aAutosavePath,
257 const wxString& aProjectPath,
258 const wxString& aAutosaveRoot,
259 BACKUP_LOCATION aLocation )
260{
261 wxFileName autosave( aAutosavePath );
262
263 if( aLocation == BACKUP_LOCATION::PROJECT_DIR )
264 {
265 wxString name = autosave.GetFullName();
266
267 if( !name.StartsWith( AUTOSAVE_PREFIX ) )
268 return wxEmptyString;
269
270 autosave.SetFullName( name.Mid( AUTOSAVE_PREFIX.length() ) );
271 return autosave.GetFullPath();
272 }
273
274 if( !aAutosavePath.StartsWith( aAutosaveRoot ) )
275 return wxEmptyString;
276
277 wxString rel = aAutosavePath.Mid( aAutosaveRoot.length() );
278 wxFileName projFn( aProjectPath, wxEmptyString );
279
280 return projFn.GetPathWithSep() + rel;
281}
282
283
284static bool commitSnapshotForProject( const wxString& aProjectPath, const std::vector<wxString>& aFiles,
285 const wxString& aTitle );
286
287
288// Single point of control: git local history is active only when backups are enabled and
289// the backup format is incremental. In zip mode we leave any pre-existing .history
290// dormant on disk and skip all write/commit operations so we do not keep extending a
291// history the user has switched off. Read-only paths (HistoryExists, RestoreCommit,
292// ShowRestoreDialog) intentionally bypass this gate so users can still browse dormant
293// history after switching back.
295{
297}
298
299
300// Local history is project-scoped. When pcbnew or eeschema is launched
301// standalone without a project, save paths can land anywhere on the
302// filesystem (e.g. /tmp), and walking those directories to feed libgit2
303// would be catastrophic.
304static bool isProjectDirectory( const wxString& aProjectPath )
305{
306 if( aProjectPath.IsEmpty() || !wxDirExists( aProjectPath ) )
307 return false;
308
309 wxDir dir( aProjectPath );
310 wxString name;
311
312 return dir.IsOpened()
313 && dir.GetFirst( &name, wxString( wxS( "*." ) ) + FILEEXT::ProjectFileExtension, wxDIR_FILES );
314}
315
316
317// Top-level project entries that must survive a restore unchanged: git/history metadata, the
318// transient restore staging directories (current and any timestamped retained copies), and
319// the per-project zip backup directory produced by SETTINGS_MANAGER::BackupProject (named
320// "<projectname>-backups").
321static bool isRestoreProtectedEntry( const wxString& aName )
322{
323 return aName == wxS( ".history" ) || aName == wxS( ".history_old" )
324 || aName.StartsWith( wxS( ".history_old_" ) )
325 || aName == wxS( ".git" ) || aName == wxS( "_restore_backup" )
326 || aName.StartsWith( wxS( "_restore_backup_" ) ) || aName == wxS( "_restore_temp" )
327 || aName == wxS( "_restore_discard" ) || aName.EndsWith( PROJECT_BACKUPS_DIR_SUFFIX );
328}
329
333
335{
336 // Some libgit2 releases ignore the cancel from the progress callback, so this can still wait
337 // for the pack write to finish
338 m_cancelCompaction.store( true );
339
340 if( m_compactFuture.valid() )
341 m_compactFuture.wait();
342
344}
345
346void LOCAL_HISTORY::NoteFileChange( const wxString& aFile )
347{
348 wxFileName fn( aFile );
349
350 if( fn.GetFullName() == wxS( "fp-info-cache" ) || !localHistoryEnabled() )
351 return;
352
353 m_pendingFiles.insert( fn.GetFullPath() );
354}
355
356
358 const void* aSaverObject,
359 const std::function<void( const wxString&, std::vector<HISTORY_FILE_DATA>& )>& aSaver,
360 const std::weak_ptr<void>& aLifetime )
361{
362 if( m_savers.find( aSaverObject ) != m_savers.end() )
363 {
364 wxLogTrace( traceAutoSave, wxS( "[history] Saver %p already registered, skipping" ), aSaverObject );
365 return;
366 }
367
368 SAVER_ENTRY entry;
369 entry.saver = aSaver;
370 entry.lifetime = aLifetime;
371
372 // The token is alive here, so lock() succeeding marks this saver for liveness tracking. When
373 // the owning document is later freed the token expires and the saver-runner drops the saver.
374 entry.tracked = aLifetime.lock() != nullptr;
375
376 m_savers[aSaverObject] = std::move( entry );
377 wxLogTrace( traceAutoSave, wxS( "[history] Registered saver %p (total=%zu)" ), aSaverObject, m_savers.size() );
378}
379
380
382{
383 RegisterSaver( aProject,
384 [aProject]( const wxString& aProjectPath, std::vector<HISTORY_FILE_DATA>& aFileData )
385 {
386 // ZIP-mode recovery only offers boards and schematics
387 if( Pgm().GetCommonSettings()->AutosaveUsesLocalHistory() )
388 aProject->SaveToHistory( aProjectPath, aFileData );
389 },
390 aProject->GetHistoryLifetimeToken() );
391}
392
393
395{
396 std::vector<const void*> expired;
397
398 // A tracked saver whose owning document has been freed must be dropped before any saver runs;
399 // probing the freed object is itself the autosave-saver use-after-free we are guarding against.
400 for( const auto& [saverObject, entry] : m_savers )
401 {
402 if( entry.tracked && entry.lifetime.expired() )
403 expired.push_back( saverObject );
404 }
405
406 for( const void* obj : expired )
407 m_savers.erase( obj );
408}
409
410
411void LOCAL_HISTORY::UnregisterSaver( const void* aSaverObject )
412{
414
415 auto it = m_savers.find( aSaverObject );
416
417 if( it != m_savers.end() )
418 {
419 m_savers.erase( it );
420 wxLogTrace( traceAutoSave, wxS( "[history] Unregistered saver %p (total=%zu)" ),
421 aSaverObject, m_savers.size() );
422 }
423}
424
425
427{
429 m_savers.clear();
430 wxLogTrace( traceAutoSave, wxS( "[history] Cleared all savers" ) );
431}
432
433
434bool LOCAL_HISTORY::RunRegisteredSaversAndCommit( const wxString& aProjectPath, const wxString& aTitle,
435 const wxString& aTagFileType )
436{
437 if( !localHistoryEnabled() )
438 {
439 wxLogTrace( traceAutoSave, wxS( "Local history disabled, returning" ) );
440 return true;
441 }
442
443 if( !isProjectDirectory( aProjectPath ) )
444 return false;
445
446 Init( aProjectPath );
447
448 wxLogTrace( traceAutoSave,
449 wxS( "[history] RunRegisteredSaversAndCommit start project='%s' title='%s' savers=%zu tag='%s'" ),
450 aProjectPath, aTitle, m_savers.size(), aTagFileType );
451
452 if( m_savers.empty() )
453 {
454 wxLogTrace( traceAutoSave, wxS( "[history] no savers registered; skipping") );
455 return false;
456 }
457
458 // Manual save must land; autosave is droppable because another tick will retry.
459 if( !aTagFileType.IsEmpty() )
460 {
462 }
463 else if( m_saveInProgress.load( std::memory_order_acquire ) )
464 {
465 wxLogTrace( traceAutoSave, wxS( "[history] previous save still in progress; skipping cycle" ) );
466 return false;
467 }
468
470
471 // Phase 1 (UI thread): call savers to collect serialized data
472 std::vector<HISTORY_FILE_DATA> fileData;
473
474 for( const auto& [saverObject, entry] : m_savers )
475 {
476 size_t before = fileData.size();
477 entry.saver( aProjectPath, fileData );
478 wxLogTrace( traceAutoSave, wxS( "[history] saver %p produced %zu entries (total=%zu)" ),
479 saverObject, fileData.size() - before, fileData.size() );
480 }
481
482 // Reject entries with an empty or absolute relativePath; the saver contract requires
483 // a project-relative path so we can stage it into the index or write it under the
484 // autosave-files root without ambiguity.
485 fileData.erase( std::remove_if( fileData.begin(), fileData.end(),
486 []( const HISTORY_FILE_DATA& entry )
487 {
488 if( entry.relativePath.IsEmpty() || wxFileName( entry.relativePath ).IsAbsolute() )
489 {
490 wxLogTrace( traceAutoSave, wxS( "[history] filtered out entry with invalid path: '%s'" ),
491 entry.relativePath );
492 return true;
493 }
494 return false;
495 } ),
496 fileData.end() );
497
498 if( fileData.empty() )
499 {
500 wxLogTrace( traceAutoSave, wxS( "[history] saver set produced no entries; skipping" ) );
501 return false;
502 }
503
504 // Phase 2: submit Prettify + file I/O + git to background thread
505 m_saveInProgress.store( true, std::memory_order_release );
506
507 m_pendingFuture = GetKiCadThreadPool().submit_task(
508 [this, projectPath = aProjectPath, title = aTitle, tagFileType = aTagFileType,
509 data = std::move( fileData )]() mutable -> bool
510 {
511 SNAPSHOT_COMMIT_RESULT result = commitInBackground( projectPath, title, data,
512 !tagFileType.IsEmpty() );
513
514 // A save with nothing new still anchors Last_Save at HEAD, but a failed one must not
515 if( !tagFileType.IsEmpty() && result != SNAPSHOT_COMMIT_RESULT::Error )
516 TagSave( projectPath, tagFileType );
517
518 m_saveInProgress.store( false, std::memory_order_release );
520 } );
521
522 // Manual save must complete (commit + tag)
523 if( !aTagFileType.IsEmpty() )
524 {
525 WaitForPendingSave();
526 }
527 else
528 {
529 // Pack long before the close-time size check would, so closing rarely has anything to do
530 unsigned long long limit = Pgm().GetCommonSettings()->m_Backup.limit_total_size;
531 scheduleCompaction( aProjectPath, limit > 0 ? (size_t) ( limit / 4 ) : UNLIMITED_HISTORY_LOOSE_BYTES );
532 }
533
534 return true;
535}
536
537
538bool LOCAL_HISTORY::RunRegisteredSaversAsAutosaveFiles( const wxString& aProjectPath )
539{
540 if( !Pgm().GetCommonSettings()->m_Backup.enabled )
541 return true;
542
543 if( m_savers.empty() )
544 {
545 wxLogTrace( traceAutoSave, wxS( "[autosave] no savers registered; skipping" ) );
546 return false;
547 }
548
551 wxString autosaveRoot = mgr.GetAutosaveRootForProject( mgr.GetProjectForPath( aProjectPath ) );
552
553 if( !PATHS::EnsurePathExists( autosaveRoot ) )
554 {
555 wxLogTrace( traceAutoSave, wxS( "[autosave] cannot create autosave root '%s'" ), autosaveRoot );
556 return false;
557 }
558
560
561 std::vector<HISTORY_FILE_DATA> fileData;
562
563 for( const auto& [saverObject, entry] : m_savers )
564 entry.saver( aProjectPath, fileData );
565
566 bool anyWritten = false;
567
568 for( HISTORY_FILE_DATA& entry : fileData )
569 {
570 if( entry.removed || entry.relativePath.IsEmpty() || wxFileName( entry.relativePath ).IsAbsolute() )
571 continue;
572
573 wxString dst = resolveAutosaveDestination( autosaveRoot, entry.relativePath, location );
574 wxFileName dstFn( dst );
575
576 if( !PATHS::EnsurePathExists( dstFn.GetPath() ) )
577 {
578 wxLogTrace( traceAutoSave, wxS( "[autosave] cannot create dir '%s'" ), dstFn.GetPath() );
579 continue;
580 }
581
582 std::string buf;
583
584 if( !entry.content.empty() )
585 {
586 buf = std::move( entry.content );
587
588 if( entry.prettify )
589 KICAD_FORMAT::Prettify( buf, entry.formatMode );
590 }
591 else if( !entry.sourcePath.IsEmpty() )
592 {
593 wxFFile src( entry.sourcePath, wxS( "rb" ) );
594
595 if( !src.IsOpened() )
596 continue;
597
598 wxFileOffset len = src.Length();
599
600 if( len < 0 )
601 continue;
602
603 buf.resize( static_cast<size_t>( len ) );
604
605 if( len > 0 && src.Read( buf.data(), buf.size() ) != buf.size() )
606 {
607 buf.clear();
608 continue;
609 }
610 }
611 else
612 {
613 continue;
614 }
615
616 wxString err;
617
618 if( KIPLATFORM::IO::AtomicWriteFile( dst, buf.data(), buf.size(), &err ) )
619 {
620 anyWritten = true;
621 wxLogTrace( traceAutoSave, wxS( "[autosave] wrote %zu bytes to '%s'" ), buf.size(), dst );
622 }
623 else
624 {
625 wxLogTrace( traceAutoSave, wxS( "[autosave] write failed for '%s': %s" ), dst, err );
626 }
627 }
628
629 return anyWritten;
630}
631
632
633// Enumerate every (autosave, source) pair under the per-project autosave root, without
634// any modification-time filter. Callers that want only files newer than their source
635// (the recovery-prompt path) apply that filter themselves; cleanup callers want the
636// full list so they can remove leftover autosave files even when the source has been
637// re-saved and is newer.
638std::vector<std::pair<wxString, wxString>>
639LOCAL_HISTORY::CollectAutosaveFilePairs( const wxString& aAutosaveRoot, const wxString& aProjectPath,
640 BACKUP_LOCATION aLocation )
641{
642 std::vector<std::pair<wxString, wxString>> results;
643
644 if( !wxDirExists( aAutosaveRoot ) )
645 return results;
646
647 DIR_LOOP_GUARD guard( aAutosaveRoot );
648
649 if( !guard.IsRooted() )
650 return results;
651
652 std::function<void( const wxString& )> walk =
653 [&]( const wxString& aDir )
654 {
655 wxDir d( aDir );
656
657 if( !d.IsOpened() )
658 return;
659
660 wxString name;
661 bool cont = d.GetFirst( &name );
662
663 while( cont )
664 {
665 wxFileName fn( aDir, name );
666 wxString fullPath = fn.GetFullPath();
667
668 if( wxDirExists( fullPath ) )
669 {
670 if( aLocation == BACKUP_LOCATION::PROJECT_DIR
671 && ( name == wxS( ".history" ) || name.EndsWith( wxS( "-backups" ) ) ) )
672 {
673 cont = d.GetNext( &name );
674 continue;
675 }
676
677 if( guard.ShouldDescend( fullPath ) )
678 walk( fullPath );
679 }
680 else if( aLocation != BACKUP_LOCATION::PROJECT_DIR
681 || fn.GetFullName().StartsWith( AUTOSAVE_PREFIX ) )
682 {
683 wxString src = sourceForAutosaveFile( fullPath, aProjectPath, aAutosaveRoot,
684 aLocation );
685
686 if( !src.IsEmpty() )
687 results.emplace_back( fullPath, src );
688 }
689
690 cont = d.GetNext( &name );
691 }
692 };
693
694 walk( aAutosaveRoot );
695 return results;
696}
697
698
699static std::vector<std::pair<wxString, wxString>>
700findAutosaveFilePairs( const wxString& aProjectPath )
701{
704 wxString autosaveRoot = mgr.GetAutosaveRootForProject( mgr.GetProjectForPath( aProjectPath ) );
705
706 return LOCAL_HISTORY::CollectAutosaveFilePairs( autosaveRoot, aProjectPath, location );
707}
708
709
710std::vector<std::pair<wxString, wxString>>
711LOCAL_HISTORY::FindStaleAutosaveFiles( const wxString& aProjectPath, const std::vector<wxString>& aExtensions ) const
712{
713 std::vector<std::pair<wxString, wxString>> results;
714
715 if( aExtensions.empty() )
716 return results;
717
718 for( auto& pair : findAutosaveFilePairs( aProjectPath ) )
719 {
720 wxFileName srcFn( pair.second );
721 bool match = false;
722
723 for( const wxString& ext : aExtensions )
724 {
725 if( srcFn.GetExt().IsSameAs( ext, false ) )
726 {
727 match = true;
728 break;
729 }
730 }
731
732 if( !match )
733 continue;
734
735 wxDateTime srcTime;
736
737 if( srcFn.FileExists() )
738 srcTime = srcFn.GetModificationTime();
739
740 wxDateTime autosaveTime = wxFileName( pair.first ).GetModificationTime();
741
742 // mtime is only a pre-filter; cloud-sync clients bump the byte-identical autosave's
743 // mtime past the source, so confirm the content actually diverges (issue 24126).
744 bool stale = !srcTime.IsValid()
745 || ( autosaveTime.IsLaterThan( srcTime )
746 && !filesContentEqual( pair.first, pair.second ) );
747
748 if( stale )
749 results.emplace_back( std::move( pair ) );
750 }
751
752 return results;
753}
754
755
756void LOCAL_HISTORY::RemoveAutosaveFiles( const wxString& aProjectPath ) const
757{
758 // After a successful manual save the source typically has a newer mtime than its
759 // autosave, so we cannot rely on FindStaleAutosaveFiles() here -- we need to remove
760 // every autosave file associated with the project regardless of mtime.
761 for( const auto& [autosavePath, srcPath] : findAutosaveFilePairs( aProjectPath ) )
762 {
763 if( wxFileExists( autosavePath ) )
764 wxRemoveFile( autosavePath );
765 }
766}
767
768
769void LOCAL_HISTORY::RemoveAutosaveFiles( const wxString& aProjectPath,
770 const std::vector<wxString>& aSourcePaths ) const
771{
772 if( aSourcePaths.empty() )
773 return;
774
775 std::vector<wxFileName> targets;
776 targets.reserve( aSourcePaths.size() );
777
778 for( const wxString& src : aSourcePaths )
779 {
780 if( !src.IsEmpty() )
781 targets.emplace_back( src );
782 }
783
784 if( targets.empty() )
785 return;
786
787 for( const auto& [autosavePath, srcPath] : findAutosaveFilePairs( aProjectPath ) )
788 {
789 wxFileName srcFn( srcPath );
790 bool match = false;
791
792 for( const wxFileName& target : targets )
793 {
794 if( srcFn.SameAs( target ) )
795 {
796 match = true;
797 break;
798 }
799 }
800
801 if( match && wxFileExists( autosavePath ) )
802 wxRemoveFile( autosavePath );
803 }
804}
805
806
807SNAPSHOT_COMMIT_RESULT LOCAL_HISTORY::commitInBackground( const wxString& aProjectPath, const wxString& aTitle,
808 const std::vector<HISTORY_FILE_DATA>& aFileData,
809 bool aIsManualSave )
810{
811 wxLogTrace( traceAutoSave, wxS( "[history] background: writing %zu entries for '%s'" ),
812 aFileData.size(), aProjectPath );
813
814 wxString hist = historyPath( aProjectPath );
815
816 if( !PATHS::EnsurePathExists( hist ) )
817 {
818 wxLogTrace( traceAutoSave, wxS( "[history] background: cannot create history root '%s'" ), hist );
820 }
821
822 struct STAGED_FILE
823 {
824 wxString relativePath;
825 std::string content;
826 bool removed = false;
827 };
828
829 std::vector<STAGED_FILE> staged;
830
831 for( const HISTORY_FILE_DATA& entry : aFileData )
832 {
833 STAGED_FILE file{ entry.relativePath, std::string(), entry.removed };
834
835 if( file.removed )
836 {
837 staged.push_back( std::move( file ) );
838 continue;
839 }
840
841 if( !entry.content.empty() )
842 {
843 file.content = entry.content;
844
845 if( entry.prettify )
846 KICAD_FORMAT::Prettify( file.content, entry.formatMode );
847 }
848 else if( entry.sourcePath.IsEmpty() )
849 {
850 continue;
851 }
852 else if( !readFileContent( entry.sourcePath, file.content ) )
853 {
854 // Committing the rest would record a snapshot that silently lacks this file
855 wxLogTrace( traceAutoSave, wxS( "[history] background: cannot read '%s'" ), entry.sourcePath );
857 }
858
859 staged.push_back( std::move( file ) );
860 }
861
862 // Acquire locks using hybrid locking strategy
863 HISTORY_LOCK_MANAGER lock( aProjectPath );
864
865 if( !lock.IsLocked() )
866 {
867 wxLogTrace( traceAutoSave, wxS( "[history] background: failed to acquire lock: %s" ), lock.GetLockError() );
869 }
870
871 git_repository* repo = lock.GetRepository();
872 git_index* index = lock.GetIndex();
873
874 removeLegacyWorkingCopies( repo, hist );
875
876 // Stage from memory. A copy on disk would sit beside .git and count against the size limit
877 for( const STAGED_FILE& file : staged )
878 {
879 wxString rel = file.relativePath;
880 rel.Replace( wxS( "\\" ), wxS( "/" ) );
881
882 std::string path = rel.utf8_string();
883
884 // The index keeps every file an earlier snapshot staged, so a deleted one must be dropped
885 if( file.removed )
886 {
887 if( git_index_remove_bypath( index, path.c_str() ) != 0 )
888 {
889 wxLogTrace( traceAutoSave, wxS( "[history] background: failed to unstage '%s'" ), rel );
890 git_index_read( index, true );
892 }
893
894 continue;
895 }
896
897 git_index_entry indexEntry = {};
898 indexEntry.mode = GIT_FILEMODE_BLOB;
899 indexEntry.path = path.c_str();
900
901 if( git_index_add_from_buffer( index, &indexEntry, file.content.data(), file.content.size() ) != 0 )
902 {
903 // Leave the index as HEAD had it rather than commit the old content under a new snapshot
904 wxLogTrace( traceAutoSave, wxS( "[history] background: failed to stage '%s'" ), rel );
905 git_index_read( index, true );
907 }
908 }
909
910 // Compare index to HEAD; if no diff -> abort to avoid empty commit.
911 git_oid head_oid;
912 git_commit* head_commit = nullptr;
913 git_tree* head_tree = nullptr;
914
915 bool headExists = ( git_reference_name_to_id( &head_oid, repo, "HEAD" ) == 0 )
916 && ( git_commit_lookup( &head_commit, repo, &head_oid ) == 0 )
917 && ( git_commit_tree( &head_tree, head_commit ) == 0 );
918
919 git_tree* rawIndexTree = nullptr;
920 git_oid index_tree_oid;
921
922 if( git_index_write_tree( &index_tree_oid, index ) != 0 )
923 {
924 if( head_tree )
925 git_tree_free( head_tree );
926
927 if( head_commit )
928 git_commit_free( head_commit );
929
930 wxLogTrace( traceAutoSave, wxS("[history] background: failed to write index tree" ) );
932 }
933
934 git_tree_lookup( &rawIndexTree, repo, &index_tree_oid );
935 std::unique_ptr<git_tree, decltype( &git_tree_free )> indexTree( rawIndexTree, &git_tree_free );
936
937 bool hasChanges = true;
938
939 if( headExists )
940 {
941 git_diff* diff = nullptr;
942
943 if( git_diff_tree_to_tree( &diff, repo, head_tree, indexTree.get(), nullptr ) == 0 )
944 {
945 hasChanges = git_diff_num_deltas( diff ) > 0;
946 wxLogTrace( traceAutoSave, wxS( "[history] background: diff deltas=%u" ),
947 (unsigned) git_diff_num_deltas( diff ) );
948 git_diff_free( diff );
949 }
950 }
951 else
952 {
953 // No HEAD: skip commit if staged matches disk, so an idle autosave on a fresh
954 // project doesn't leave an untagged HEAD that triggers a no-op restore prompt.
955 bool stagedMatchesDisk = true;
956
957 for( const STAGED_FILE& file : staged )
958 {
959 wxFileName diskPath( file.relativePath );
960 std::string diskContent;
961
962 diskPath.MakeAbsolute( aProjectPath );
963
964 const bool matchesDisk = file.removed ? !diskPath.FileExists()
965 : readFileContent( diskPath.GetFullPath(), diskContent )
966 && diskContent == file.content;
967
968 if( !matchesDisk )
969 {
970 stagedMatchesDisk = false;
971 break;
972 }
973 }
974
975 if( stagedMatchesDisk && !aIsManualSave )
976 {
977 wxLogTrace( traceAutoSave, wxS( "[history] background: first commit; staged matches disk -- skipping" ) );
978 hasChanges = false;
979 }
980 }
981
982 if( head_tree )
983 git_tree_free( head_tree );
984
985 if( head_commit )
986 git_commit_free( head_commit );
987
988 if( !hasChanges )
989 {
990 wxLogTrace( traceAutoSave, wxS("[history] background: no changes detected; no commit") );
991
992 // Manual save matching HEAD: amend the prior message so the user's explicit save
993 // shows in the history dialog. Skip if HEAD already has this title.
994 if( !aTitle.IsEmpty() && aTitle != wxS( "Autosave" ) )
995 {
996 git_oid head_oid_amend;
997
998 if( git_reference_name_to_id( &head_oid_amend, repo, "HEAD" ) == 0 )
999 {
1000 git_commit* head_commit_amend = nullptr;
1001
1002 if( git_commit_lookup( &head_commit_amend, repo, &head_oid_amend ) == 0 )
1003 {
1004 wxString existingMsg = wxString::FromUTF8( git_commit_message( head_commit_amend ) );
1005 existingMsg.Trim( true ).Trim( false );
1006
1007 if( existingMsg != aTitle )
1008 {
1009 git_oid amended_oid;
1010 int amend_rc = git_commit_amend( &amended_oid, head_commit_amend, "HEAD", nullptr, nullptr,
1011 nullptr, aTitle.mb_str().data(), nullptr );
1012
1013 if( amend_rc == 0 )
1014 wxLogTrace( traceAutoSave, wxS( "[history] background: amended HEAD message '%s' -> '%s'" ),
1015 existingMsg, aTitle );
1016 else
1017 wxLogTrace( traceAutoSave, wxS( "[history] background: amend failed rc=%d" ), amend_rc );
1018 }
1019
1020 git_commit_free( head_commit_amend );
1021 }
1022 }
1023 }
1024
1026 }
1027
1028 git_signature* rawSig = nullptr;
1029 git_signature_now( &rawSig, "KiCad", "[email protected]" );
1030 std::unique_ptr<git_signature, decltype( &git_signature_free )> sig( rawSig, &git_signature_free );
1031
1032 git_commit* parent = nullptr;
1033 git_oid parent_id;
1034 int parents = 0;
1035
1036 if( git_reference_name_to_id( &parent_id, repo, "HEAD" ) == 0 )
1037 {
1038 if( git_commit_lookup( &parent, repo, &parent_id ) == 0 )
1039 parents = 1;
1040 }
1041
1042 wxString msg = aTitle.IsEmpty() ? wxString( "Autosave" ) : aTitle;
1043 git_oid commit_id;
1044 const git_commit* constParent = parent;
1045
1046 int rc = git_commit_create( &commit_id, repo, "HEAD", sig.get(), sig.get(), nullptr,
1047 msg.mb_str().data(), indexTree.get(), parents,
1048 parents ? &constParent : nullptr );
1049
1050 if( rc == 0 )
1051 {
1052 wxLogTrace( traceAutoSave, wxS( "[history] background: commit created %s (%s entries=%zu)" ),
1053 wxString::FromUTF8( git_oid_tostr_s( &commit_id ) ), msg, aFileData.size() );
1054 }
1055 else
1056 {
1057 wxLogTrace( traceAutoSave, wxS( "[history] background: commit failed rc=%d" ), rc );
1058 }
1059
1060 if( parent )
1061 git_commit_free( parent );
1062
1063 git_index_write( index );
1065}
1066
1067
1069{
1070 if( m_pendingFuture.valid() )
1071 {
1072 wxLogTrace( traceAutoSave, wxS( "[history] waiting for pending background save" ) );
1073 m_pendingFuture.get();
1074 }
1075}
1076
1077
1079{
1080 std::vector<wxString> files( m_pendingFiles.begin(), m_pendingFiles.end() );
1081 m_pendingFiles.clear();
1082 return CommitSnapshot( files, wxS( "Autosave" ) );
1083}
1084
1085
1086bool LOCAL_HISTORY::Init( const wxString& aProjectPath )
1087{
1088 if( !isProjectDirectory( aProjectPath ) )
1089 return false;
1090
1091 if( !localHistoryEnabled() )
1092 return true;
1093
1094 wxString hist = historyPath( aProjectPath );
1095
1096 if( !wxDirExists( hist ) )
1097 {
1098 wxLogNull suppressSysErrorPopups;
1099
1100 // EnsurePathExists creates intermediate directories as needed, which is required
1101 // for USER_DIR mode where the parent (e.g., ~/.config/kicad/<ver>/local_history/)
1102 // may not yet exist. In PROJECT_DIR mode it falls back to a single mkdir.
1103 if( !PATHS::EnsurePathExists( hist ) )
1104 return false;
1105 }
1106
1107 git_repository* rawRepo = nullptr;
1108
1109 if( git_repository_open( &rawRepo, hist.mb_str().data() ) != 0 )
1110 {
1111 if( git_repository_init( &rawRepo, hist.mb_str().data(), 0 ) != 0 )
1112 return false;
1113
1114 wxFileName ignoreFile( hist, wxS( ".gitignore" ) );
1115 if( !ignoreFile.FileExists() )
1116 {
1117 wxFFile f( ignoreFile.GetFullPath(), wxT( "w" ) );
1118 if( f.IsOpened() )
1119 {
1120 f.Write( wxS( "# KiCad local history exclusions. Edit to add your own rules.\n"
1121 "fp-info-cache\n"
1122 "*-backups/\n" ) );
1123 f.Close();
1124 }
1125 }
1126
1127 wxFileName readmeFile( hist, wxS( "README.txt" ) );
1128
1129 if( !readmeFile.FileExists() )
1130 {
1131 wxFFile f( readmeFile.GetFullPath(), wxT( "w" ) );
1132
1133 if( f.IsOpened() )
1134 {
1135 f.Write( wxS( "KiCad Local History Directory\n"
1136 "=============================\n\n"
1137 "This directory contains automatic snapshots of your project files.\n"
1138 "KiCad periodically saves copies of your work here, allowing you to\n"
1139 "recover from accidental changes or data loss.\n\n"
1140 "You can browse and restore previous versions through KiCad's\n"
1141 "File > Local History menu.\n\n"
1142 "To disable this feature:\n"
1143 " Preferences > Common > Project Backup > Enable automatic backups\n\n"
1144 "This directory can be safely deleted if you no longer need the\n"
1145 "history, but doing so will permanently remove all saved snapshots.\n" ) );
1146 f.Close();
1147 }
1148 }
1149 }
1150
1151 git_repository_free( rawRepo );
1152
1153 return true;
1154}
1155
1156
1157// Helper function to commit files using an already-acquired lock
1158
1159
1161 const wxString& aHistoryPath, const wxString& aProjectPath,
1162 const std::vector<wxString>& aFiles, const wxString& aTitle )
1163{
1164 std::vector<std::string> filesArrStr;
1165
1166 for( const wxString& file : aFiles )
1167 {
1168 wxFileName src( file );
1169 wxString relPath;
1170
1171 if( src.GetFullPath().StartsWith( aProjectPath + wxFILE_SEP_PATH ) )
1172 relPath = src.GetFullPath().Mid( aProjectPath.length() + 1 );
1173 else
1174 relPath = src.GetFullName(); // Fallback (should not normally happen)
1175
1176 relPath.Replace( "\\", "/" ); // libgit2 needs forward slashes on all platforms
1177 std::string relPathStr = relPath.ToStdString();
1178
1179 unsigned int status = 0;
1180 int rc = git_status_file( &status, repo, relPathStr.data() );
1181
1182 if( rc == 0 && status != 0 )
1183 {
1184 wxLogTrace( traceAutoSave, wxS( "File %s status %d " ), relPath, status );
1185 filesArrStr.emplace_back( relPathStr );
1186 }
1187 else if( rc != 0 )
1188 {
1189 wxLogTrace( traceAutoSave, wxS( "File %s status error %d " ), relPath, rc );
1190 filesArrStr.emplace_back( relPathStr ); // Add anyway even if the file is untracked.
1191 }
1192 }
1193
1194 std::vector<char*> cStrings( filesArrStr.size() );
1195
1196 for( size_t i = 0; i < filesArrStr.size(); i++ )
1197 cStrings[i] = filesArrStr[i].data();
1198
1199 git_strarray filesArrGit;
1200 filesArrGit.count = filesArrStr.size();
1201 filesArrGit.strings = cStrings.data();
1202
1203 if( filesArrStr.size() == 0 )
1204 {
1205 wxLogTrace( traceAutoSave, wxS( "No changes, skipping" ) );
1207 }
1208
1209 int rc = git_index_add_all( index, &filesArrGit, GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH | GIT_INDEX_ADD_FORCE, NULL,
1210 NULL );
1211 wxLogTrace( traceAutoSave, wxS( "Adding %zu files, rc %d" ), filesArrStr.size(), rc );
1212
1213 if( rc != 0 )
1215
1216 git_oid tree_id;
1217 if( git_index_write_tree( &tree_id, index ) != 0 )
1219
1220 git_tree* rawTree = nullptr;
1221 git_tree_lookup( &rawTree, repo, &tree_id );
1222 std::unique_ptr<git_tree, decltype( &git_tree_free )> tree( rawTree, &git_tree_free );
1223
1224 git_signature* rawSig = nullptr;
1225 git_signature_now( &rawSig, "KiCad", "[email protected]" );
1226 std::unique_ptr<git_signature, decltype( &git_signature_free )> sig( rawSig,
1227 &git_signature_free );
1228
1229 git_commit* rawParent = nullptr;
1230 git_oid parent_id;
1231 int parents = 0;
1232
1233 if( git_reference_name_to_id( &parent_id, repo, "HEAD" ) == 0 )
1234 {
1235 git_commit_lookup( &rawParent, repo, &parent_id );
1236 parents = 1;
1237 }
1238
1239 std::unique_ptr<git_commit, decltype( &git_commit_free )> parent( rawParent,
1240 &git_commit_free );
1241
1242 git_tree* rawParentTree = nullptr;
1243
1244 if( parent )
1245 git_commit_tree( &rawParentTree, parent.get() );
1246
1247 std::unique_ptr<git_tree, decltype( &git_tree_free )> parentTree( rawParentTree, &git_tree_free );
1248
1249 git_diff* rawDiff = nullptr;
1250 git_diff_tree_to_index( &rawDiff, repo, parentTree.get(), index, nullptr );
1251 std::unique_ptr<git_diff, decltype( &git_diff_free )> diff( rawDiff, &git_diff_free );
1252
1253 size_t numChangedFiles = git_diff_num_deltas( diff.get() );
1254
1255 if( numChangedFiles == 0 )
1256 {
1257 wxLogTrace( traceAutoSave, wxS( "No actual changes in tree, skipping commit" ) );
1259 }
1260
1261 wxString msg;
1262
1263 if( !aTitle.IsEmpty() )
1264 msg << aTitle << wxS( ": " );
1265
1266 msg << numChangedFiles << wxS( " files changed" );
1267
1268 for( size_t i = 0; i < numChangedFiles; ++i )
1269 {
1270 const git_diff_delta* delta = git_diff_get_delta( diff.get(), i );
1271 git_patch* rawPatch = nullptr;
1272 git_patch_from_diff( &rawPatch, diff.get(), i );
1273 std::unique_ptr<git_patch, decltype( &git_patch_free )> patch( rawPatch,
1274 &git_patch_free );
1275 size_t context = 0, adds = 0, dels = 0;
1276 git_patch_line_stats( &context, &adds, &dels, patch.get() );
1277 size_t updated = std::min( adds, dels );
1278 adds -= updated;
1279 dels -= updated;
1280 msg << wxS( "\n" ) << wxString::FromUTF8( delta->new_file.path )
1281 << wxS( " " ) << adds << wxS( "/" ) << dels << wxS( "/" ) << updated;
1282 }
1283
1284 git_oid commit_id;
1285 git_commit* parentPtr = parent.get();
1286 const git_commit* constParentPtr = parentPtr;
1287 if( git_commit_create( &commit_id, repo, "HEAD", sig.get(), sig.get(), nullptr, msg.mb_str().data(), tree.get(),
1288 parents, parentPtr ? &constParentPtr : nullptr )
1289 != 0 )
1290 {
1292 }
1293
1294 git_index_write( index );
1296}
1297
1298
1299// Internal entry point used when the project root is already known. The public
1300// CommitSnapshot() derives the project from aFiles[0], which is unsafe when the
1301// caller has collected files recursively (the first entry can live in a subdirectory).
1302static bool commitSnapshotForProject( const wxString& aProjectPath, const std::vector<wxString>& aFiles,
1303 const wxString& aTitle )
1304{
1305 wxString hist = historyPath( aProjectPath );
1306
1307 HISTORY_LOCK_MANAGER lock( aProjectPath );
1308
1309 if( !lock.IsLocked() )
1310 {
1311 wxLogTrace( traceAutoSave, wxS( "[history] commitSnapshotForProject failed to acquire lock: %s" ),
1312 lock.GetLockError() );
1313 return false;
1314 }
1315
1316 return commitSnapshotWithLock( lock.GetRepository(), lock.GetIndex(), hist, aProjectPath, aFiles, aTitle )
1318}
1319
1320
1321bool LOCAL_HISTORY::CommitSnapshot( const std::vector<wxString>& aFiles, const wxString& aTitle )
1322{
1323 if( aFiles.empty() || !localHistoryEnabled() )
1324 {
1325 return true;
1326 }
1327
1328 wxString proj = wxFileName( aFiles[0] ).GetPath();
1329
1330 if( !isProjectDirectory( proj ) )
1331 return false;
1332
1333 Init( proj );
1334 return commitSnapshotForProject( proj, aFiles, aTitle );
1335}
1336
1337
1338// Limit snapshots to KiCad project artifacts (kicad_* extensions and the no-extension
1339// lib-tables) so unrelated files in the project dir don't end up in .history.
1340static bool isKiCadProjectFile( const wxFileName& aFile )
1341{
1342 wxString name = aFile.GetFullName();
1343
1344 if( name == wxS( "sym-lib-table" ) || name == wxS( "fp-lib-table" ) )
1345 return true;
1346
1347 return aFile.GetExt().StartsWith( wxS( "kicad_" ) );
1348}
1349
1350
1351// Helper to collect KiCad project files (excluding .history, backups, transient caches,
1352// and any non-KiCad files such as user PDFs or notes).
1353// Skips subtrees that contain a kicad_pro file since they belong to nested projects.
1354static void collectProjectFiles( const wxString& aProjectPath, std::vector<wxString>& aFiles )
1355{
1356 wxDir dir( aProjectPath );
1357
1358 if( !dir.IsOpened() )
1359 return;
1360
1361 // Same loop hazard as the autosave scan: a project directory holding a root-escape
1362 // symlink would otherwise recurse across the whole filesystem.
1363 DIR_LOOP_GUARD guard( aProjectPath );
1364
1365 if( !guard.IsRooted() )
1366 return;
1367
1368 // Collect recursively. Flag top-level to avoid hitting the same logic for nested projects
1369 std::function<void( const wxString&, bool )> collect =
1370 [&]( const wxString& path, bool topLevel )
1371 {
1372 if( !topLevel && isProjectDirectory( path ) )
1373 {
1374 wxLogTrace( traceAutoSave,
1375 wxS( "[history] collectProjectFiles: Skipping nested project at %s" ),
1376 path );
1377 return;
1378 }
1379
1380 wxString name;
1381 wxDir d( path );
1382
1383 if( !d.IsOpened() )
1384 return;
1385
1386 bool cont = d.GetFirst( &name );
1387
1388 while( cont )
1389 {
1390 if( topLevel && isRestoreProtectedEntry( name ) )
1391 {
1392 cont = d.GetNext( &name );
1393 continue;
1394 }
1395
1396 wxFileName fn( path, name );
1397 wxString fullPath = fn.GetFullPath();
1398
1399 if( wxFileName::DirExists( fullPath ) )
1400 {
1401 if( guard.ShouldDescend( fullPath ) )
1402 collect( fullPath, false );
1403 }
1404 else if( fn.FileExists() && fn.GetFullName() != wxS( "fp-info-cache" ) && isKiCadProjectFile( fn ) )
1405 {
1406 aFiles.push_back( fn.GetFullPath() );
1407 }
1408
1409 cont = d.GetNext( &name );
1410 }
1411 };
1412
1413 collect( aProjectPath, true );
1414}
1415
1416
1417bool LOCAL_HISTORY::CommitFullProjectSnapshot( const wxString& aProjectPath, const wxString& aTitle )
1418{
1419 if( !isProjectDirectory( aProjectPath ) || !localHistoryEnabled() )
1420 return false;
1421
1422 std::vector<wxString> files;
1423 collectProjectFiles( aProjectPath, files );
1424
1425 if( files.empty() )
1426 return false;
1427
1428 Init( aProjectPath );
1429 return commitSnapshotForProject( aProjectPath, files, aTitle );
1430}
1431
1432bool LOCAL_HISTORY::HistoryExists( const wxString& aProjectPath )
1433{
1434 return wxDirExists( historyPath( aProjectPath ) );
1435}
1436
1437// Add a Save_<type>_N tag and move Last_Save_<type> to the current HEAD using an already-open
1438// repo. Shared by TagSave and the restore path, the latter holds the history lock itself and so
1439// cannot go through TagSave (which would try to re-acquire it).
1440static bool tagSaveAtHead( git_repository* repo, const wxString& aFileType )
1441{
1442 if( !repo )
1443 return false;
1444
1445 git_oid head;
1446 if( git_reference_name_to_id( &head, repo, "HEAD" ) != 0 )
1447 return false;
1448
1449 wxString tagName;
1450 int i = 1;
1451 git_reference* ref = nullptr;
1452 do
1453 {
1454 tagName.Printf( wxS( "Save_%s_%d" ), aFileType, i++ );
1455 } while( git_reference_lookup( &ref, repo, ( wxS( "refs/tags/" ) + tagName ).mb_str().data() ) == 0 );
1456
1457 git_oid tag_oid;
1458 git_object* head_obj = nullptr;
1459 git_object_lookup( &head_obj, repo, &head, GIT_OBJECT_COMMIT );
1460 git_tag_create_lightweight( &tag_oid, repo, tagName.mb_str().data(), head_obj, 0 );
1461 git_object_free( head_obj );
1462
1463 wxString lastName;
1464 lastName.Printf( wxS( "Last_Save_%s" ), aFileType );
1465 if( git_reference_lookup( &ref, repo, ( wxS( "refs/tags/" ) + lastName ).mb_str().data() ) == 0 )
1466 {
1467 git_reference_delete( ref );
1468 git_reference_free( ref );
1469 }
1470
1471 git_oid last_tag_oid;
1472 git_object* head_obj2 = nullptr;
1473 git_object_lookup( &head_obj2, repo, &head, GIT_OBJECT_COMMIT );
1474 git_tag_create_lightweight( &last_tag_oid, repo, lastName.mb_str().data(), head_obj2, 0 );
1475 git_object_free( head_obj2 );
1476
1477 return true;
1478}
1479
1480
1481bool LOCAL_HISTORY::TagSave( const wxString& aProjectPath, const wxString& aFileType )
1482{
1483 if( !localHistoryEnabled() )
1484 return true;
1485
1486 if( !isProjectDirectory( aProjectPath ) )
1487 return false;
1488
1489 HISTORY_LOCK_MANAGER lock( aProjectPath );
1490
1491 if( !lock.IsLocked() )
1492 {
1493 wxLogTrace( traceAutoSave, wxS( "[history] TagSave: Failed to acquire lock for %s" ), aProjectPath );
1494 return false;
1495 }
1496
1497 return tagSaveAtHead( lock.GetRepository(), aFileType );
1498}
1499
1500bool LOCAL_HISTORY::HeadNewerThanLastSave( const wxString& aProjectPath )
1501{
1502 wxString hist = historyPath( aProjectPath );
1503 git_repository* repo = nullptr;
1504
1505 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
1506 return false;
1507
1508 git_oid head_oid;
1509 if( git_reference_name_to_id( &head_oid, repo, "HEAD" ) != 0 )
1510 {
1511 git_repository_free( repo );
1512 return false;
1513 }
1514
1515 git_commit* head_commit = nullptr;
1516 git_commit_lookup( &head_commit, repo, &head_oid );
1517 git_time_t head_time = git_commit_time( head_commit );
1518
1519 git_strarray tags;
1520 git_tag_list_match( &tags, "Last_Save_*", repo );
1521 git_time_t save_time = 0;
1522
1523 for( size_t i = 0; i < tags.count; ++i )
1524 {
1525 git_reference* ref = nullptr;
1526 if( git_reference_lookup( &ref, repo,
1527 ( wxS( "refs/tags/" ) +
1528 wxString::FromUTF8( tags.strings[i] ) ).mb_str().data() ) == 0 )
1529 {
1530 const git_oid* oid = git_reference_target( ref );
1531 git_commit* c = nullptr;
1532 if( git_commit_lookup( &c, repo, oid ) == 0 )
1533 {
1534 git_time_t t = git_commit_time( c );
1535 if( t > save_time )
1536 save_time = t;
1537 git_commit_free( c );
1538 }
1539 git_reference_free( ref );
1540 }
1541 }
1542
1543 git_strarray_free( &tags );
1544 git_commit_free( head_commit );
1545 git_repository_free( repo );
1546
1547 // If there are no Last_Save tags but there IS a HEAD commit, we have autosaved
1548 // data that was never explicitly saved - offer to restore
1549 if( save_time == 0 )
1550 return true;
1551
1552 return head_time > save_time;
1553}
1554
1555bool LOCAL_HISTORY::CommitDuplicateOfLastSave( const wxString& aProjectPath, const wxString& aFileType,
1556 const wxString& aMessage )
1557{
1558 if( !localHistoryEnabled() )
1559 return true;
1560
1561 if( !isProjectDirectory( aProjectPath ) )
1562 return false;
1563
1564 HISTORY_LOCK_MANAGER lock( aProjectPath );
1565
1566 if( !lock.IsLocked() )
1567 {
1568 wxLogTrace( traceAutoSave, wxS( "[history] CommitDuplicateOfLastSave: Failed to acquire lock for %s" ), aProjectPath );
1569 return false;
1570 }
1571
1572 git_repository* repo = lock.GetRepository();
1573
1574 if( !repo )
1575 return false;
1576
1577 wxString lastName; lastName.Printf( wxS("Last_Save_%s"), aFileType );
1578 git_reference* lastRef = nullptr;
1579 if( git_reference_lookup( &lastRef, repo, ( wxS("refs/tags/") + lastName ).mb_str().data() ) != 0 )
1580 return false; // no tag to duplicate
1581 std::unique_ptr<git_reference, decltype( &git_reference_free )> lastRefPtr( lastRef, &git_reference_free );
1582
1583 const git_oid* lastOid = git_reference_target( lastRef );
1584 git_commit* lastCommit = nullptr;
1585 if( git_commit_lookup( &lastCommit, repo, lastOid ) != 0 )
1586 return false;
1587 std::unique_ptr<git_commit, decltype( &git_commit_free )> lastCommitPtr( lastCommit, &git_commit_free );
1588
1589 git_tree* lastTree = nullptr;
1590 git_commit_tree( &lastTree, lastCommit );
1591 std::unique_ptr<git_tree, decltype( &git_tree_free )> lastTreePtr( lastTree, &git_tree_free );
1592
1593 // Parent will be current HEAD (to keep linear history)
1594 git_oid headOid;
1595 git_commit* headCommit = nullptr;
1596 int parents = 0;
1597 const git_commit* parentArray[1];
1598 if( git_reference_name_to_id( &headOid, repo, "HEAD" ) == 0 &&
1599 git_commit_lookup( &headCommit, repo, &headOid ) == 0 )
1600 {
1601 parentArray[0] = headCommit;
1602 parents = 1;
1603 }
1604
1605 git_signature* sigRaw = nullptr;
1606 git_signature_now( &sigRaw, "KiCad", "[email protected]" );
1607 std::unique_ptr<git_signature, decltype( &git_signature_free )> sig( sigRaw, &git_signature_free );
1608
1609 wxString msg = aMessage.IsEmpty() ? wxS("Discard unsaved ") + aFileType : aMessage;
1610 git_oid newCommitOid;
1611 int rc = git_commit_create( &newCommitOid, repo, "HEAD", sig.get(), sig.get(), nullptr,
1612 msg.mb_str().data(), lastTree, parents, parents ? parentArray : nullptr );
1613 if( headCommit ) git_commit_free( headCommit );
1614 if( rc != 0 )
1615 return false;
1616
1617 // Move Last_Save tag to new commit
1618 git_reference* existing = nullptr;
1619 if( git_reference_lookup( &existing, repo, ( wxS("refs/tags/") + lastName ).mb_str().data() ) == 0 )
1620 {
1621 git_reference_delete( existing );
1622 git_reference_free( existing );
1623 }
1624 git_object* newCommitObj = nullptr;
1625 if( git_object_lookup( &newCommitObj, repo, &newCommitOid, GIT_OBJECT_COMMIT ) == 0 )
1626 {
1627 git_tag_create_lightweight( &newCommitOid, repo, lastName.mb_str().data(), newCommitObj, 0 );
1628 git_object_free( newCommitObj );
1629 }
1630 return true;
1631}
1632
1633static size_t dirSizeRecursive( const wxString& path )
1634{
1635 size_t total = 0;
1636 wxDir dir( path );
1637 if( !dir.IsOpened() )
1638 return 0;
1639 wxString name;
1640 bool cont = dir.GetFirst( &name );
1641 while( cont )
1642 {
1643 wxFileName fn( path, name );
1644 wxString fullPath = fn.GetFullPath();
1645
1646 if( wxFileName::DirExists( fullPath ) )
1647 total += dirSizeRecursive( fullPath );
1648 else if( fn.FileExists() )
1649 total += (size_t) fn.GetSize().GetValue();
1650 cont = dir.GetNext( &name );
1651 }
1652 return total;
1653}
1654
1655static std::vector<wxString> listPackFiles( const wxString& aPackDir )
1656{
1657 std::vector<wxString> packs;
1658 wxDir packDir( aPackDir );
1659
1660 if( !packDir.IsOpened() )
1661 return packs;
1662
1663 wxString name;
1664 bool cont = packDir.GetFirst( &name, wxEmptyString, wxDIR_FILES );
1665
1666 while( cont )
1667 {
1668 if( name.EndsWith( wxS( ".pack" ) ) || name.EndsWith( wxS( ".idx" ) ) )
1669 packs.push_back( aPackDir + wxFileName::GetPathSeparator() + name );
1670
1671 cont = packDir.GetNext( &name );
1672 }
1673
1674 std::sort( packs.begin(), packs.end() );
1675 return packs;
1676}
1677
1678
1679static bool writePack( git_packbuilder* aPb, const wxString& aPackDir, PROGRESS_REPORTER* aReporter,
1680 const std::atomic<bool>* aCancel = nullptr )
1681{
1682 struct PROGRESS_STATE
1683 {
1685 const std::atomic<bool>* cancel;
1686 } state{ aReporter, aCancel };
1687
1688 // Leave libgit2 single threaded. Its threads split the one long delta chain a KiCad history
1689 // holds per file, so each split starts from a full copy and the pack grows several times over
1690 if( aReporter || aCancel )
1691 {
1692 git_packbuilder_set_callbacks(
1693 aPb,
1694 []( int aStage, uint32_t aCurrent, uint32_t aTotal, void* aPayload )
1695 {
1696 auto* progress = static_cast<PROGRESS_STATE*>( aPayload );
1697
1698 if( progress->reporter )
1699 {
1700 if( aTotal > 0 )
1701 progress->reporter->SetCurrentProgress( (double) aCurrent / aTotal );
1702
1703 progress->reporter->KeepRefreshing();
1704 }
1705
1706 return progress->cancel && progress->cancel->load() ? -1 : 0;
1707 },
1708 &state );
1709 }
1710
1711 std::string packDir = aPackDir.utf8_string();
1712
1713 return git_packbuilder_write( aPb, aPackDir.IsEmpty() ? nullptr : packDir.c_str(), 0, nullptr, nullptr ) == 0;
1714}
1715
1716
1717// Loose objects outside the new pack are only deleted once this much older than the walk. Writing
1718// an object that already exists refreshes its mtime, so anything a commit still needs is newer
1719static const time_t UNREACHABLE_LOOSE_EXPIRY_SECONDS = 24 * 60 * 60;
1720
1721
1722// Delete the loose objects the pack at aPackIndex holds, plus expired unreachable ones. Checking
1723// membership instead of clearing every loose dir keeps objects a concurrent commit wrote after the walk
1724static void pruneLooseObjects( const wxString& aObjectsPath, const wxString& aPackIndex, time_t aWalkStart )
1725{
1726 git_odb* packOdb = nullptr;
1727 git_odb_backend* backend = nullptr;
1728
1729 if( git_odb_new( &packOdb ) != 0 )
1730 return;
1731
1732 if( git_odb_backend_one_pack( &backend, aPackIndex.utf8_string().c_str() ) != 0 )
1733 {
1734 git_odb_free( packOdb );
1735 return;
1736 }
1737
1738 if( git_odb_add_backend( packOdb, backend, 1 ) != 0 )
1739 {
1740 backend->free( backend );
1741 git_odb_free( packOdb );
1742 return;
1743 }
1744
1745 wxLogNull suppressRmdirErrors;
1746 wxDir objDir( aObjectsPath );
1747 wxString fanout;
1748 bool contDir = objDir.IsOpened() && objDir.GetFirst( &fanout, wxEmptyString, wxDIR_DIRS );
1749
1750 while( contDir )
1751 {
1752 wxString fanoutPath = aObjectsPath + wxFileName::GetPathSeparator() + fanout;
1753 wxDir looseDir( fanoutPath );
1754 wxString rest;
1755 bool contFile = fanout.length() == 2 && looseDir.IsOpened()
1756 && looseDir.GetFirst( &rest, wxEmptyString, wxDIR_FILES );
1757
1758 while( contFile )
1759 {
1760 git_oid oid;
1761 wxString loosePath = fanoutPath + wxFileName::GetPathSeparator() + rest;
1762
1763 if( git_oid_fromstr( &oid, ( fanout + rest ).utf8_string().c_str() ) == 0
1764 && ( git_odb_exists( packOdb, &oid )
1765 || wxFileModificationTime( loosePath ) < aWalkStart - UNREACHABLE_LOOSE_EXPIRY_SECONDS ) )
1766 {
1767 wxRemoveFile( loosePath );
1768 }
1769
1770 contFile = looseDir.GetNext( &rest );
1771 }
1772
1773 if( fanout.length() == 2 && !wxDir( fanoutPath ).HasFiles() )
1774 wxRmdir( fanoutPath );
1775
1776 contDir = objDir.GetNext( &fanout );
1777 }
1778
1779 git_odb_free( packOdb );
1780}
1781
1782
1783// Pack every object reachable from the refs into aPackDir, or the repository's own pack dir when
1784// empty. Returns the new pack's file stem, or an empty string on failure
1785static wxString buildPack( git_repository* aRepo, const wxString& aPackDir, PROGRESS_REPORTER* aReporter,
1786 const std::atomic<bool>* aCancel )
1787{
1788 git_packbuilder* pb = nullptr;
1789 git_revwalk* walk = nullptr;
1790
1791 if( git_packbuilder_new( &pb, aRepo ) != 0 )
1792 return wxEmptyString;
1793
1794 if( git_revwalk_new( &walk, aRepo ) != 0 )
1795 {
1796 git_packbuilder_free( pb );
1797 return wxEmptyString;
1798 }
1799
1800 // Walk every ref so pruning cannot drop objects only a Save_/Last_Save_ tag still holds
1801 bool ok = git_revwalk_push_glob( walk, "refs/*" ) == 0 && git_revwalk_push_head( walk ) == 0;
1802 int rc = 0;
1803 git_oid oid;
1804
1805 while( ok && ( rc = git_revwalk_next( &oid, walk ) ) == 0 )
1806 ok = git_packbuilder_insert_commit( pb, &oid ) == 0;
1807
1808 git_revwalk_free( walk );
1809
1810 // A walk cut short by an error would write a partial pack that then supersedes complete ones
1811 wxString stem;
1812
1813 if( ok && rc == GIT_ITEROVER && writePack( pb, aPackDir, aReporter, aCancel ) )
1814 {
1815#if ( LIBGIT2_VER_MAJOR > 1 ) || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 4 )
1816 const char* newPackName = git_packbuilder_name( pb );
1817#else
1818 char hex[GIT_OID_HEXSZ + 1];
1819 hex[GIT_OID_HEXSZ] = '\0';
1820 git_oid_fmt( hex, git_packbuilder_hash( pb ) );
1821
1822 const char* newPackName = strlen( hex ) > 0 ? hex : nullptr;
1823#endif
1824
1825 if( newPackName )
1826 stem = wxS( "pack-" ) + wxString::FromUTF8( newPackName );
1827 }
1828
1829 git_packbuilder_free( pb );
1830 return stem;
1831}
1832
1833
1834// Pack names are content addressed, so an unchanged repo rewrites the same file; exclude it
1835static std::vector<wxString> supersededBy( const std::vector<wxString>& aPriorPacks, const wxString& aNewStem )
1836{
1837 std::vector<wxString> superseded;
1838
1839 for( const wxString& pack : aPriorPacks )
1840 {
1841 if( wxFileName( pack ).GetName() != aNewStem )
1842 superseded.push_back( pack );
1843 }
1844
1845 return superseded;
1846}
1847
1848
1849// Pack loose objects and prune them, like git gc, under the caller's history lock. Superseded packs
1850// are returned for the caller to delete once it drops the repo, since libgit2 keeps them open
1852 std::vector<wxString>* aSupersededPacks )
1853{
1854 wxString sep = wxFileName::GetPathSeparator();
1855 wxString objPath = wxString::FromUTF8( git_repository_path( aRepo ) ) + wxS( "objects" );
1856 wxString packDir = objPath + sep + wxS( "pack" );
1857
1858 std::vector<wxString> priorPacks = listPackFiles( packDir );
1859 time_t walkStart = wxDateTime::Now().GetTicks();
1860 wxString stem = buildPack( aRepo, wxEmptyString, aReporter, nullptr );
1861
1862 if( stem.IsEmpty() )
1863 return false;
1864
1865 *aSupersededPacks = supersededBy( priorPacks, stem );
1866 pruneLooseObjects( objPath, packDir + sep + stem + wxS( ".idx" ), walkStart );
1867 return true;
1868}
1869
1870
1871bool LOCAL_HISTORY::EnforceSizeLimit( const wxString& aProjectPath, size_t aMaxBytes, PROGRESS_REPORTER* aReporter )
1872{
1873 return enforceSizeLimit( aProjectPath, historyPath( aProjectPath ), aMaxBytes, aReporter );
1874}
1875
1876
1877bool LOCAL_HISTORY::enforceSizeLimit( const wxString& aProjectPath, const wxString& aHistoryPath, size_t aMaxBytes,
1878 PROGRESS_REPORTER* aReporter )
1879{
1880 if( aMaxBytes == 0 )
1881 return false;
1882
1883 if( !wxDirExists( aHistoryPath ) )
1884 return false;
1885
1886 size_t current = dirSizeRecursive( aHistoryPath );
1887
1888 if( current <= aMaxBytes )
1889 return true; // within limit
1890
1891 HISTORY_LOCK_MANAGER lock( aProjectPath, aHistoryPath );
1892
1893 if( !lock.IsLocked() )
1894 {
1895 wxLogTrace( traceAutoSave, wxS( "[history] EnforceSizeLimit: Failed to acquire lock for %s" ), aProjectPath );
1896 return false;
1897 }
1898
1899 git_repository* repo = lock.GetRepository();
1900
1901 if( !repo )
1902 return false;
1903
1904 removeLegacyWorkingCopies( repo, aHistoryPath );
1905 current = dirSizeRecursive( aHistoryPath );
1906
1907 if( current <= aMaxBytes )
1908 return true;
1909
1910 if( aReporter )
1911 aReporter->Report( _( "Compacting local history..." ) );
1912
1913 // Pack loose objects first. Can bring size within limit without a full rebuild.
1914 std::vector<wxString> supersededPacks;
1915 compactRepository( repo, aReporter, &supersededPacks );
1916
1917 // libgit2 holds the packs open, so release the repository before deleting them
1918 lock.ReleaseRepository();
1919
1920 for( const wxString& pack : supersededPacks )
1921 {
1922 if( !wxRemoveFile( pack ) )
1923 wxLogTrace( traceAutoSave, wxS( "[history] could not remove %s" ), pack );
1924 }
1925
1926 current = dirSizeRecursive( aHistoryPath );
1927
1928 // Settle below the limit so the following sessions do not each pay for another full repack
1929 const size_t target = aMaxBytes / 4 * 3;
1930
1931 if( current <= target )
1932 return true; // within limit after compaction
1933
1934 repo = lock.ReopenRepository();
1935
1936 if( !repo )
1937 return false;
1938
1939 // Collect commits newest-first using revwalk
1940 git_revwalk* walk = nullptr;
1941 git_revwalk_new( &walk, repo );
1942 git_revwalk_sorting( walk, GIT_SORT_TIME );
1943 git_revwalk_push_head( walk );
1944 std::vector<git_oid> commits;
1945 git_oid oid;
1946
1947 while( git_revwalk_next( &oid, walk ) == 0 )
1948 commits.push_back( oid );
1949
1950 git_revwalk_free( walk );
1951
1952 if( commits.empty() )
1953 return true;
1954
1955 // Determine set of newest commits to keep based on blob sizes.
1956 std::set<git_oid, bool ( * )( const git_oid&, const git_oid& )> seenBlobs(
1957 []( const git_oid& a, const git_oid& b )
1958 {
1959 return memcmp( &a, &b, sizeof( git_oid ) ) < 0;
1960 } );
1961
1962 // The plain file copies beside .git are rewritten by every save, so they cannot be trimmed away
1963 wxString gitDir = wxString::FromUTF8( git_repository_path( repo ) );
1964 size_t gitBytes = dirSizeRecursive( gitDir );
1965 size_t copyBytes = current > gitBytes ? current - gitBytes : 0;
1966 size_t budget = target > copyBytes ? target - copyBytes : 0;
1967
1968 size_t keptBytes = 0;
1969 std::vector<git_oid> keep;
1970
1971 git_odb* odb = nullptr;
1972 git_repository_odb( &odb, repo );
1973
1974 std::function<size_t( git_tree* )> accountTree =
1975 [&]( git_tree* tree )
1976 {
1977 size_t added = 0;
1978 size_t cnt = git_tree_entrycount( tree );
1979
1980 for( size_t i = 0; i < cnt; ++i )
1981 {
1982 const git_tree_entry* entry = git_tree_entry_byindex( tree, i );
1983
1984 if( git_tree_entry_type( entry ) == GIT_OBJECT_BLOB )
1985 {
1986 const git_oid* bid = git_tree_entry_id( entry );
1987
1988 if( seenBlobs.find( *bid ) == seenBlobs.end() )
1989 {
1990 size_t len = 0;
1991 git_object_t type = GIT_OBJECT_ANY;
1992
1993 if( odb && git_odb_read_header( &len, &type, odb, bid ) == 0 )
1994 added += len;
1995
1996 seenBlobs.insert( *bid );
1997 }
1998 }
1999 else if( git_tree_entry_type( entry ) == GIT_OBJECT_TREE )
2000 {
2001 git_tree* sub = nullptr;
2002
2003 if( git_tree_lookup( &sub, repo, git_tree_entry_id( entry ) ) == 0 )
2004 {
2005 added += accountTree( sub );
2006 git_tree_free( sub );
2007 }
2008 }
2009 }
2010
2011 return added;
2012 };
2013
2014 for( const git_oid& cOid : commits )
2015 {
2016 git_commit* c = nullptr;
2017
2018 if( git_commit_lookup( &c, repo, &cOid ) != 0 )
2019 continue;
2020
2021 git_tree* tree = nullptr;
2022 git_commit_tree( &tree, c );
2023 size_t add = accountTree( tree );
2024 git_tree_free( tree );
2025 git_commit_free( c );
2026
2027 if( keep.empty() || keptBytes + add <= budget )
2028 {
2029 keep.push_back( cOid );
2030 keptBytes += add;
2031 }
2032 else
2033 break; // stop once limit exceeded
2034 }
2035
2036 if( keep.empty() )
2037 keep.push_back( commits.front() );
2038
2039 if( odb )
2040 git_odb_free( odb );
2041
2042 // Collect tags we want to preserve (Save_*/Last_Save_*). We'll recreate them if their
2043 // target commit is retained. Also ensure tagged commits are ALWAYS kept.
2044 std::vector<std::pair<wxString, git_oid>> tagTargets;
2045 std::set<git_oid, bool ( * )( const git_oid&, const git_oid& )> taggedCommits(
2046 []( const git_oid& a, const git_oid& b )
2047 {
2048 return memcmp( &a, &b, sizeof( git_oid ) ) < 0;
2049 } );
2050 git_strarray tagList;
2051
2052 if( git_tag_list( &tagList, repo ) == 0 )
2053 {
2054 for( size_t i = 0; i < tagList.count; ++i )
2055 {
2056 wxString name = wxString::FromUTF8( tagList.strings[i] );
2057 if( name.StartsWith( wxS("Save_") ) || name.StartsWith( wxS("Last_Save_") ) )
2058 {
2059 git_reference* tref = nullptr;
2060
2061 if( git_reference_lookup( &tref, repo, ( wxS( "refs/tags/" ) + name ).mb_str().data() ) == 0 )
2062 {
2063 const git_oid* toid = git_reference_target( tref );
2064
2065 if( toid )
2066 {
2067 tagTargets.emplace_back( name, *toid );
2068 taggedCommits.insert( *toid );
2069
2070 // Ensure this tagged commit is in the keep list
2071 bool found = false;
2072 for( const auto& k : keep )
2073 {
2074 if( memcmp( &k, toid, sizeof( git_oid ) ) == 0 )
2075 {
2076 found = true;
2077 break;
2078 }
2079 }
2080
2081 if( !found )
2082 {
2083 // Add tagged commit to keep list (even if it exceeds size limit)
2084 keep.push_back( *toid );
2085 wxLogTrace( traceAutoSave, wxS( "[history] EnforceSizeLimit: Preserving tagged commit %s" ),
2086 name );
2087 }
2088 }
2089
2090 git_reference_free( tref );
2091 }
2092 }
2093 }
2094 git_strarray_free( &tagList );
2095 }
2096
2097 // Rebuild trimmed repo in temp dir
2098 wxFileName trimFn( aHistoryPath + wxS("_trim"), wxEmptyString );
2099 wxString trimPath = trimFn.GetPath();
2100
2101 if( wxDirExists( trimPath ) )
2102 wxFileName::Rmdir( trimPath, wxPATH_RMDIR_RECURSIVE );
2103
2104 wxMkdir( trimPath );
2105 git_repository* newRepo = nullptr;
2106
2107 if( git_repository_init( &newRepo, trimPath.mb_str().data(), 0 ) != 0 )
2108 return false;
2109
2110 wxString newPackDir = wxString::FromUTF8( git_repository_path( newRepo ) ) + wxS( "objects" )
2111 + wxFileName::GetPathSeparator() + wxS( "pack" );
2112 git_repository_free( newRepo );
2113 newRepo = nullptr;
2114
2115 // The rewritten commits go into the current repo, where their trees and blobs already live, so the
2116 // trimmed history can be packed straight into the new repo without copying objects one by one
2117 git_packbuilder* pb = nullptr;
2118
2119 if( git_packbuilder_new( &pb, repo ) != 0 )
2120 return false;
2121
2122 // Replay kept commits chronologically (oldest first) to preserve order.
2123 std::reverse( keep.begin(), keep.end() );
2124 git_commit* parent = nullptr;
2125 struct MAP_ENTRY { git_oid orig; git_oid neu; };
2126 std::vector<MAP_ENTRY> commitMap;
2127 bool rewriteOk = true;
2128
2129 if( aReporter )
2130 {
2131 aReporter->AdvancePhase( _( "Trimming local history..." ) );
2132 aReporter->SetCurrentProgress( 0 );
2133 }
2134
2135 for( size_t idx = 0; idx < keep.size() && rewriteOk; ++idx )
2136 {
2137 if( aReporter )
2138 {
2139 aReporter->SetCurrentProgress( (double) idx / keep.size() );
2140 aReporter->KeepRefreshing();
2141 }
2142
2143 const git_oid& co = keep[idx];
2144 git_commit* orig = nullptr;
2145
2146 if( git_commit_lookup( &orig, repo, &co ) != 0 )
2147 continue;
2148
2149 git_tree* tree = nullptr;
2150
2151 if( git_commit_tree( &tree, orig ) != 0 )
2152 {
2153 git_commit_free( orig );
2154 continue;
2155 }
2156
2157 // Recreate original author/committer signatures preserving timestamp.
2158 const git_signature* origAuthor = git_commit_author( orig );
2159 const git_signature* origCommitter = git_commit_committer( orig );
2160 git_signature* sigAuthor = nullptr;
2161 git_signature* sigCommitter = nullptr;
2162
2163 git_signature_new( &sigAuthor, origAuthor->name, origAuthor->email,
2164 origAuthor->when.time, origAuthor->when.offset );
2165 git_signature_new( &sigCommitter, origCommitter->name, origCommitter->email,
2166 origCommitter->when.time, origCommitter->when.offset );
2167
2168 const git_commit* parents[1];
2169 int parentCount = 0;
2170
2171 if( parent )
2172 {
2173 parents[0] = parent;
2174 parentCount = 1;
2175 }
2176
2177 git_oid newCommitOid;
2178
2179 if( git_commit_create( &newCommitOid, repo, nullptr, sigAuthor, sigCommitter, nullptr,
2180 git_commit_message( orig ), tree, parentCount, parentCount ? parents : nullptr )
2181 != 0 )
2182 {
2183 rewriteOk = false;
2184 }
2185 else
2186 {
2187 if( parent )
2188 git_commit_free( parent );
2189
2190 parent = nullptr;
2191 git_commit_lookup( &parent, repo, &newCommitOid );
2192 commitMap.emplace_back( co, newCommitOid );
2193 }
2194
2195 git_signature_free( sigAuthor );
2196 git_signature_free( sigCommitter );
2197 git_tree_free( tree );
2198 git_commit_free( orig );
2199 }
2200
2201 if( parent )
2202 git_commit_free( parent );
2203
2204 // libgit2 breaks delta ties and lays out the pack by insertion order, which it expects newest first
2205 for( auto it = commitMap.rbegin(); it != commitMap.rend() && rewriteOk; ++it )
2206 {
2207 if( git_packbuilder_insert_commit( pb, &it->neu ) != 0 )
2208 rewriteOk = false;
2209 }
2210
2211 if( !rewriteOk || commitMap.empty() )
2212 {
2213 git_packbuilder_free( pb );
2214 return false;
2215 }
2216
2217 if( aReporter )
2218 aReporter->AdvancePhase( _( "Compacting trimmed history..." ) );
2219
2220 bool packed = writePack( pb, newPackDir, aReporter );
2221 git_packbuilder_free( pb );
2222
2223 if( !packed || git_repository_open( &newRepo, trimPath.mb_str().data() ) != 0 )
2224 return false;
2225
2226 const git_oid& newHeadOid = commitMap.back().neu;
2227 git_reference* headRef = nullptr;
2228 bool headOk = false;
2229
2230 if( git_reference_lookup( &headRef, newRepo, "HEAD" ) == 0 )
2231 {
2232 const char* branch = git_reference_symbolic_target( headRef );
2233 git_reference* branchRef = nullptr;
2234
2235 if( branch && git_reference_create( &branchRef, newRepo, branch, &newHeadOid, 1, nullptr ) == 0 )
2236 {
2237 headOk = true;
2238 git_reference_free( branchRef );
2239 }
2240
2241 git_reference_free( headRef );
2242 }
2243
2244 if( !headOk )
2245 {
2246 git_repository_free( newRepo );
2247 return false;
2248 }
2249
2250 git_commit* newHead = nullptr;
2251
2252 if( git_commit_lookup( &newHead, newRepo, &newHeadOid ) == 0 )
2253 {
2254 git_tree* newHeadTree = nullptr;
2255 git_index* newIndex = nullptr;
2256
2257 if( git_commit_tree( &newHeadTree, newHead ) == 0 && git_repository_index( &newIndex, newRepo ) == 0 )
2258 {
2259 git_index_read_tree( newIndex, newHeadTree );
2260 git_index_write( newIndex );
2261 }
2262
2263 if( newIndex )
2264 git_index_free( newIndex );
2265
2266 if( newHeadTree )
2267 git_tree_free( newHeadTree );
2268
2269 git_commit_free( newHead );
2270 }
2271
2272 // Recreate preserved tags pointing to new commit OIDs where possible.
2273 for( const auto& tt : tagTargets )
2274 {
2275 // Find mapping
2276 const git_oid* newOid = nullptr;
2277
2278 for( const auto& m : commitMap )
2279 {
2280 if( memcmp( &m.orig, &tt.second, sizeof( git_oid ) ) == 0 )
2281 {
2282 newOid = &m.neu;
2283 break;
2284 }
2285 }
2286
2287 if( !newOid )
2288 continue; // commit trimmed away
2289
2290 git_object* obj = nullptr;
2291
2292 if( git_object_lookup( &obj, newRepo, newOid, GIT_OBJECT_COMMIT ) == 0 )
2293 {
2294 git_oid tag_oid; git_tag_create_lightweight( &tag_oid, newRepo, tt.first.mb_str().data(), obj, 0 );
2295 git_object_free( obj );
2296 }
2297 }
2298
2299 // Close repos before swapping directories to avoid file locking issues
2300 git_repository_free( newRepo );
2301
2302 // The swap replaces the whole directory, so carry over the user's ignore rules
2303 for( const wxString& name : { wxString( wxS( ".gitignore" ) ), wxString( wxS( "README.txt" ) ) } )
2304 {
2305 wxFileName src( aHistoryPath, name );
2306
2307 if( src.FileExists() && !wxCopyFile( src.GetFullPath(), wxFileName( trimPath, name ).GetFullPath(), true ) )
2308 return false;
2309 }
2310
2311 lock.ReleaseRepository();
2312
2313 // Replace old history dir with trimmed one
2314 wxString backupOld = aHistoryPath + wxS( "_old_" ) + KIID().AsString();
2315
2316 if( wxFileExists( backupOld ) || wxDirExists( backupOld ) )
2317 return false;
2318
2319 if( !wxRenameFile( aHistoryPath, backupOld, false ) )
2320 return false;
2321
2322 if( !wxRenameFile( trimPath, aHistoryPath, false ) )
2323 {
2324 if( !wxRenameFile( backupOld, aHistoryPath, false ) )
2325 wxLogError( _( "Could not restore local history '%s'. The previous history is preserved at '%s'." ),
2326 aHistoryPath, backupOld );
2327
2328 return false;
2329 }
2330
2331 if( !wxFileName::Rmdir( backupOld, wxPATH_RMDIR_RECURSIVE ) )
2332 wxLogTrace( traceAutoSave, wxS( "[history] Trimmed history installed; previous history retained at %s" ),
2333 backupOld );
2334
2335 return true;
2336}
2337
2338// Background compactions write their pack here first, one dir per process
2339static const wxString STAGE_DIR_PREFIX = wxS( "kicad-compact-" );
2340
2341
2342// A crash mid-compaction leaves its stage dir behind inside .git, where it counts against the limit
2343static void removeStaleStageDirs( const wxString& aGitDir )
2344{
2345 wxDir gitDir( aGitDir );
2346 wxString name;
2347 std::vector<wxString> stale;
2348 bool cont = gitDir.IsOpened()
2349 && gitDir.GetFirst( &name, STAGE_DIR_PREFIX + wxS( "*" ), wxDIR_DIRS );
2350 time_t expiry = wxDateTime::Now().GetTicks() - UNREACHABLE_LOOSE_EXPIRY_SECONDS;
2351
2352 while( cont )
2353 {
2354 if( wxFileModificationTime( aGitDir + name ) < expiry )
2355 stale.push_back( aGitDir + name );
2356
2357 cont = gitDir.GetNext( &name );
2358 }
2359
2360 for( const wxString& dir : stale )
2361 wxFileName::Rmdir( dir, wxPATH_RMDIR_RECURSIVE );
2362}
2363
2364
2365// Every ref with the commit it resolves to, HEAD included, as sorted "name oid" strings
2366static std::vector<std::string> refTargets( git_repository* aRepo )
2367{
2368 std::vector<std::string> targets;
2369 git_reference_iterator* iter = nullptr;
2370 git_reference* ref = nullptr;
2371 git_oid oid;
2372
2373 if( git_reference_name_to_id( &oid, aRepo, "HEAD" ) == 0 )
2374 targets.push_back( std::string( "HEAD " ) + git_oid_tostr_s( &oid ) );
2375
2376 if( git_reference_iterator_new( &iter, aRepo ) != 0 )
2377 return targets;
2378
2379 while( git_reference_next( &ref, iter ) == 0 )
2380 {
2381 git_reference* resolved = nullptr;
2382
2383 if( git_reference_resolve( &resolved, ref ) == 0 )
2384 {
2385 targets.push_back( std::string( git_reference_name( ref ) ) + " "
2386 + git_oid_tostr_s( git_reference_target( resolved ) ) );
2387 git_reference_free( resolved );
2388 }
2389
2390 git_reference_free( ref );
2391 }
2392
2393 git_reference_iterator_free( iter );
2394 std::sort( targets.begin(), targets.end() );
2395 return targets;
2396}
2397
2398
2399static size_t looseObjectBytes( const wxString& aObjectsPath )
2400{
2401 size_t total = 0;
2402 wxDir objDir( aObjectsPath );
2403 wxString fanout;
2404 bool cont = objDir.IsOpened() && objDir.GetFirst( &fanout, wxEmptyString, wxDIR_DIRS );
2405
2406 while( cont )
2407 {
2408 if( fanout.length() == 2 )
2409 total += dirSizeRecursive( aObjectsPath + wxFileName::GetPathSeparator() + fanout );
2410
2411 cont = objDir.GetNext( &fanout );
2412 }
2413
2414 return total;
2415}
2416
2417
2418void LOCAL_HISTORY::scheduleCompaction( const wxString& aProjectPath, size_t aLooseLimit )
2419{
2420 if( IsCompacting() )
2421 return;
2422
2423 m_cancelCompaction.store( false );
2424
2425 // A dedicated thread rather than the shared pool, which a pack write would tie up for seconds.
2426 // Packing runs unlocked so saves are never refused meanwhile; the lock covers only the install
2427 m_compactFuture = std::async( std::launch::async,
2428 [this, projectPath = aProjectPath, hist = historyPath( aProjectPath ), aLooseLimit]()
2429 {
2430 git_repository* repo = nullptr;
2431
2432 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
2433 return;
2434
2435 wxString sep = wxFileName::GetPathSeparator();
2436 wxString gitDir = wxString::FromUTF8( git_repository_path( repo ) );
2437 wxString objPath = gitDir + wxS( "objects" );
2438 wxString packDir = objPath + sep + wxS( "pack" );
2439 wxString stageDir = gitDir + STAGE_DIR_PREFIX + wxString::Format( wxS( "%lu" ), wxGetProcessId() );
2440
2441 if( looseObjectBytes( objPath ) < aLooseLimit )
2442 {
2443 git_repository_free( repo );
2444 return;
2445 }
2446
2447 removeStaleStageDirs( gitDir );
2448
2449 std::vector<wxString> priorPacks = listPackFiles( packDir );
2450 std::vector<std::string> priorRefs = refTargets( repo );
2451 time_t walkStart = wxDateTime::Now().GetTicks();
2452
2453 wxFileName::Rmdir( stageDir, wxPATH_RMDIR_RECURSIVE );
2454 wxMkdir( stageDir );
2455
2456 wxString stem = buildPack( repo, stageDir, nullptr, &m_cancelCompaction );
2457 git_repository_free( repo );
2458
2459 HISTORY_LOCK_MANAGER lock( projectPath, hist );
2460
2461 // Another KiCad's trim swaps in new packs, and a commit meanwhile may reuse an object only
2462 // a superseded pack holds, so install only into the repository exactly as the walk saw it
2463 bool unchanged = !stem.IsEmpty() && lock.IsLocked() && listPackFiles( packDir ) == priorPacks
2464 && refTargets( lock.GetRepository() ) == priorRefs;
2465
2466 if( unchanged )
2467 {
2468 lock.ReleaseRepository();
2469
2470 wxString staged = stageDir + sep + stem;
2471 wxString target = packDir + sep + stem;
2472
2473 // The index goes last since its presence is what makes a pack visible. Either file
2474 // may already be in place from an identical earlier pack or a half-finished install
2475 bool packReady = wxFileExists( target + wxS( ".pack" ) )
2476 || wxRenameFile( staged + wxS( ".pack" ), target + wxS( ".pack" ), false );
2477 bool installed = packReady
2478 && ( wxFileExists( target + wxS( ".idx" ) )
2479 || wxRenameFile( staged + wxS( ".idx" ), target + wxS( ".idx" ), false ) );
2480
2481 if( installed )
2482 {
2483 pruneLooseObjects( objPath, target + wxS( ".idx" ), walkStart );
2484
2485 // Windows refuses while another handle maps the pack; the next compaction retries
2486 for( const wxString& pack : supersededBy( priorPacks, stem ) )
2487 {
2488 if( !wxRemoveFile( pack ) )
2489 wxLogTrace( traceAutoSave, wxS( "[history] could not remove %s" ), pack );
2490 }
2491 }
2492 else
2493 {
2494 wxLogTrace( traceAutoSave, wxS( "[history] could not install %s" ), target );
2495 }
2496 }
2497
2498 wxFileName::Rmdir( stageDir, wxPATH_RMDIR_RECURSIVE );
2499 } );
2500}
2501
2502
2503void LOCAL_HISTORY::EnforceSizeLimitInBackground( const wxString& aProjectPath, size_t aMaxBytes )
2504{
2505 // Queue behind any running compaction rather than race it for the lock
2506 m_compactFuture = std::async( std::launch::async,
2507 [this, previous = std::move( m_compactFuture ), projectPath = aProjectPath,
2508 hist = historyPath( aProjectPath ), aMaxBytes]() mutable
2509 {
2510 if( previous.valid() )
2511 previous.wait();
2512
2513 // Quitting skips the trim rather than block exit on it; the next close enforces the limit
2514 if( !m_cancelCompaction.load() )
2515 enforceSizeLimit( projectPath, hist, aMaxBytes, nullptr );
2516 } );
2517}
2518
2519
2521{
2522 return m_compactFuture.valid()
2523 && m_compactFuture.wait_for( std::chrono::seconds( 0 ) ) != std::future_status::ready;
2524}
2525
2526
2527wxString LOCAL_HISTORY::GetHeadHash( const wxString& aProjectPath )
2528{
2529 wxString hist = historyPath( aProjectPath );
2530 git_repository* repo = nullptr;
2531
2532 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
2533 return wxEmptyString;
2534
2535 git_oid head_oid;
2536 if( git_reference_name_to_id( &head_oid, repo, "HEAD" ) != 0 )
2537 {
2538 git_repository_free( repo );
2539 return wxEmptyString;
2540 }
2541
2542 wxString hash = wxString::FromUTF8( git_oid_tostr_s( &head_oid ) );
2543 git_repository_free( repo );
2544 return hash;
2545}
2546
2547
2548// Helper functions for RestoreCommit
2549namespace
2550{
2551
2555bool checkForLockedFiles( const wxString& aProjectPath, std::vector<wxString>& aLockedFiles )
2556{
2557 // A symlinked folder can loop back or lead out of the project
2558 DIR_LOOP_GUARD guard( aProjectPath );
2559
2560 if( !guard.IsRooted() )
2561 return true;
2562
2563 std::function<void( const wxString& )> findLocks =
2564 [&]( const wxString& dirPath )
2565 {
2566 wxDir dir( dirPath );
2567 if( !dir.IsOpened() )
2568 return;
2569
2570 wxString filename;
2571 bool cont = dir.GetFirst( &filename );
2572
2573 while( cont )
2574 {
2575 wxFileName fullPath( dirPath, filename );
2576
2577 // Skip special directories
2578 if( filename == wxS(".history") || filename == wxS(".git") )
2579 {
2580 cont = dir.GetNext( &filename );
2581 continue;
2582 }
2583
2584 if( fullPath.DirExists() )
2585 {
2586 if( guard.ShouldDescend( fullPath.GetFullPath() ) )
2587 findLocks( fullPath.GetFullPath() );
2588 }
2589 else if( fullPath.FileExists()
2590 && filename.StartsWith( FILEEXT::LockFilePrefix )
2591 && filename.EndsWith( wxString( wxS( "." ) ) + FILEEXT::LockFileExtension ) )
2592 {
2593 // Reconstruct the original filename from the lock file name
2594 // Lock files are: ~<original>.<ext>.lck -> need to get <original>.<ext>
2595 wxString baseName = filename.Mid( FILEEXT::LockFilePrefix.length() );
2596 baseName = baseName.BeforeLast( '.' ); // Remove .lck
2597 wxFileName originalFile( dirPath, baseName );
2598
2599 // Inspect without taking the lock so we don't disturb another session
2600 LOCKFILE testLock = LOCKFILE::Inspect( originalFile.GetFullPath() );
2601
2602 if( !testLock.Valid() && !testLock.IsLockedByMe() )
2603 {
2604 aLockedFiles.push_back( fullPath.GetFullPath() );
2605 }
2606 }
2607
2608 cont = dir.GetNext( &filename );
2609 }
2610 };
2611
2612 findLocks( aProjectPath );
2613 return aLockedFiles.empty();
2614}
2615
2616
2620bool extractCommitToTemp( git_repository* aRepo, git_tree* aTree, const wxString& aTempPath )
2621{
2622 bool extractSuccess = true;
2623
2624 std::function<void( git_tree*, const wxString& )> extractTree =
2625 [&]( git_tree* t, const wxString& prefix )
2626 {
2627 if( !extractSuccess )
2628 return;
2629
2630 size_t cnt = git_tree_entrycount( t );
2631 for( size_t i = 0; i < cnt; ++i )
2632 {
2633 const git_tree_entry* entry = git_tree_entry_byindex( t, i );
2634 wxString name = wxString::FromUTF8( git_tree_entry_name( entry ) );
2635 wxString fullPath = prefix.IsEmpty() ? name : prefix + wxS("/") + name;
2636
2637 if( git_tree_entry_type( entry ) == GIT_OBJECT_TREE )
2638 {
2639 wxFileName dirPath( aTempPath + wxFileName::GetPathSeparator() + fullPath, wxEmptyString );
2640
2641 if( !wxFileName::Mkdir( dirPath.GetPath(), 0777, wxPATH_MKDIR_FULL ) )
2642 {
2643 wxLogTrace( traceAutoSave,
2644 wxS( "[history] extractCommitToTemp: Failed to create directory '%s'" ),
2645 dirPath.GetPath() );
2646 extractSuccess = false;
2647 return;
2648 }
2649
2650 git_tree* sub = nullptr;
2651
2652 if( git_tree_lookup( &sub, aRepo, git_tree_entry_id( entry ) ) == 0 )
2653 {
2654 extractTree( sub, fullPath );
2655 git_tree_free( sub );
2656 }
2657 }
2658 else if( git_tree_entry_type( entry ) == GIT_OBJECT_BLOB )
2659 {
2660 git_blob* blob = nullptr;
2661
2662 if( git_blob_lookup( &blob, aRepo, git_tree_entry_id( entry ) ) == 0 )
2663 {
2664 wxFileName dst( aTempPath + wxFileName::GetPathSeparator() + fullPath );
2665
2666 wxFileName dstDir( dst );
2667 dstDir.SetFullName( wxEmptyString );
2668 wxFileName::Mkdir( dstDir.GetPath(), 0777, wxPATH_MKDIR_FULL );
2669
2670 wxFFile f( dst.GetFullPath(), wxT( "wb" ) );
2671
2672 if( f.IsOpened() )
2673 {
2674 f.Write( git_blob_rawcontent( blob ), git_blob_rawsize( blob ) );
2675 f.Close();
2676 }
2677 else
2678 {
2679 wxLogTrace( traceAutoSave,
2680 wxS( "[history] extractCommitToTemp: Failed to write '%s'" ),
2681 dst.GetFullPath() );
2682 extractSuccess = false;
2683 git_blob_free( blob );
2684 return;
2685 }
2686
2687 git_blob_free( blob );
2688 }
2689 }
2690 }
2691 };
2692
2693 extractTree( aTree, wxEmptyString );
2694 return extractSuccess;
2695}
2696
2697
2704void collectRelativeFiles( const wxString& aRoot, const wxString& aDir, std::vector<wxString>& aOut )
2705{
2706 wxDir dir( aDir );
2707
2708 if( !dir.IsOpened() )
2709 return;
2710
2711 wxString name;
2712
2713 for( bool cont = dir.GetFirst( &name ); cont; cont = dir.GetNext( &name ) )
2714 {
2715 wxString full = aDir + wxFILE_SEP_PATH + name;
2716
2717 if( wxDirExists( full ) )
2718 {
2719 collectRelativeFiles( aRoot, full, aOut );
2720 }
2721 else if( wxFileExists( full ) )
2722 {
2723 wxString rel = full.Mid( aRoot.length() + 1 );
2724 rel.Replace( wxS( "\\" ), wxS( "/" ) );
2725 aOut.push_back( rel );
2726 }
2727 }
2728}
2729
2730
2739bool overlaySnapshotFiles( const wxString& aTempRestorePath, const wxString& aProjectPath, const wxString& aBackupPath )
2740{
2741 std::vector<wxString> relPaths;
2742 collectRelativeFiles( aTempRestorePath, aTempRestorePath, relPaths );
2743
2744 for( const wxString& rel : relPaths )
2745 {
2746 wxFileName src( aTempRestorePath + wxFILE_SEP_PATH + rel );
2747 wxFileName dst( aProjectPath + wxFILE_SEP_PATH + rel );
2748
2749 if( dst.FileExists() )
2750 {
2751 wxFileName bak( aBackupPath + wxFILE_SEP_PATH + rel );
2752
2753 if( !wxFileName::Mkdir( bak.GetPath(), 0777, wxPATH_MKDIR_FULL )
2754 || !wxCopyFile( dst.GetFullPath(), bak.GetFullPath(), true ) )
2755 {
2756 return false;
2757 }
2758 }
2759
2760 if( !wxFileName::Mkdir( dst.GetPath(), 0777, wxPATH_MKDIR_FULL )
2761 || !wxCopyFile( src.GetFullPath(), dst.GetFullPath(), true ) )
2762 {
2763 return false;
2764 }
2765 }
2766
2767 return true;
2768}
2769
2770
2771} // namespace
2772
2773
2774bool LOCAL_HISTORY::RestoreCommit( const wxString& aProjectPath, const wxString& aHash, wxWindow* aParent,
2775 bool aConfirm )
2776{
2777 // STEP 1: Verify no files are open by checking for LOCKFILEs
2778 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Checking for open files in %s" ),
2779 aProjectPath );
2780
2781 std::vector<wxString> lockedFiles;
2782 if( !checkForLockedFiles( aProjectPath, lockedFiles ) )
2783 {
2784 wxString lockList;
2785 for( const auto& f : lockedFiles )
2786 lockList += wxS("\n - ") + f;
2787
2788 wxLogTrace( traceAutoSave,
2789 wxS( "[history] RestoreCommit: Cannot restore - files are open:%s" ),
2790 lockList );
2791
2792 // Show user-visible warning dialog
2793 if( aParent )
2794 {
2795 wxString msg = _( "Cannot restore - the following files are open by another user:" );
2796 msg += lockList;
2797 wxMessageBox( msg, _( "Restore Failed" ), wxOK | wxICON_WARNING, aParent );
2798 }
2799 return false;
2800 }
2801
2802 // STEP 2: Acquire history lock and verify target commit
2803 HISTORY_LOCK_MANAGER lock( aProjectPath );
2804
2805 if( !lock.IsLocked() )
2806 {
2807 wxLogTrace( traceAutoSave,
2808 wxS( "[history] RestoreCommit: Failed to acquire lock for %s" ),
2809 aProjectPath );
2810 return false;
2811 }
2812
2813 git_repository* repo = lock.GetRepository();
2814 if( !repo )
2815 return false;
2816
2817 // Verify the target commit exists
2818 git_oid oid;
2819 if( git_oid_fromstr( &oid, aHash.mb_str().data() ) != 0 )
2820 {
2821 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Invalid hash %s" ), aHash );
2822 return false;
2823 }
2824
2825 git_commit* commit = nullptr;
2826 if( git_commit_lookup( &commit, repo, &oid ) != 0 )
2827 {
2828 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Commit not found %s" ), aHash );
2829 return false;
2830 }
2831
2832 git_tree* tree = nullptr;
2833 git_commit_tree( &tree, commit );
2834
2835 // Confirm before overwriting working files. The recovery prompt already asked, so it passes
2836 // aConfirm = false. Nothing is changed yet, so cancel just returns.
2837 if( aConfirm && aParent )
2838 {
2839 wxDateTime when( (time_t) git_commit_time( commit ) );
2840
2841 KICAD_MESSAGE_DIALOG dlg( aParent,
2842 wxString::Format( _( "Restore the project to the version from %s?" ),
2843 when.Format( wxS( "%Y-%m-%d %H:%M:%S" ) ) ),
2844 _( "Restore Version" ), wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION );
2845
2846 dlg.SetYesNoLabels( _( "Restore" ), _( "Cancel" ) );
2847 dlg.SetExtendedMessage( _( "Your current files are backed up first so you can undo the "
2848 "restore. Files that are not part of this version are left "
2849 "untouched." ) );
2850
2851 if( dlg.ShowModal() != wxID_YES )
2852 {
2853 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: User cancelled at confirm" ) );
2854 git_tree_free( tree );
2855 git_commit_free( commit );
2856 return false;
2857 }
2858 }
2859
2860 // Create pre-restore backup snapshot using the existing lock
2861 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Creating pre-restore backup" ) );
2862
2863 std::vector<wxString> backupFiles;
2864 collectProjectFiles( aProjectPath, backupFiles );
2865
2866 if( !backupFiles.empty() )
2867 {
2868 wxString hist = historyPath( aProjectPath );
2869 SNAPSHOT_COMMIT_RESULT backupResult = commitSnapshotWithLock( repo, lock.GetIndex(), hist, aProjectPath,
2870 backupFiles, wxS( "Pre-restore backup" ) );
2871
2872 if( backupResult == SNAPSHOT_COMMIT_RESULT::Error )
2873 {
2874 wxLogTrace( traceAutoSave,
2875 wxS( "[history] RestoreCommit: Failed to create pre-restore backup" ) );
2876 git_tree_free( tree );
2877 git_commit_free( commit );
2878 return false;
2879 }
2880
2881 if( backupResult == SNAPSHOT_COMMIT_RESULT::NoChanges )
2882 {
2883 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Current state already matches HEAD; "
2884 "continuing without a new backup commit" ) );
2885 }
2886 }
2887
2888 // STEP 3: Extract commit to temporary location
2889 wxString tempRestorePath = aProjectPath + wxS("_restore_temp");
2890
2891 if( wxDirExists( tempRestorePath ) )
2892 wxFileName::Rmdir( tempRestorePath, wxPATH_RMDIR_RECURSIVE );
2893
2894 if( !wxFileName::Mkdir( tempRestorePath, 0777, wxPATH_MKDIR_FULL ) )
2895 {
2896 wxLogTrace( traceAutoSave,
2897 wxS( "[history] RestoreCommit: Failed to create temp directory %s" ),
2898 tempRestorePath );
2899 git_tree_free( tree );
2900 git_commit_free( commit );
2901 return false;
2902 }
2903
2904 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Extracting to temp location %s" ),
2905 tempRestorePath );
2906
2907 if( !extractCommitToTemp( repo, tree, tempRestorePath ) )
2908 {
2909 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Extraction failed, cleaning up" ) );
2910 wxFileName::Rmdir( tempRestorePath, wxPATH_RMDIR_RECURSIVE );
2911 git_tree_free( tree );
2912 git_commit_free( commit );
2913 return false;
2914 }
2915
2916 // STEP 4: Overlay the snapshot onto the working copy. Restore never removes files that are
2917 // absent from the snapshot, so restoring a partial per-editor commit (for example the HEAD
2918 // autosave from a board-only session) cannot delete the schematic, project file, outputs, or
2919 // libraries. Overwritten files are archived to backupPath for manual recovery, and the
2920 // pre-restore commit created above is the full undo point.
2921 wxString backupPath =
2922 aProjectPath + wxS( "_restore_backup_" )
2923 + wxDateTime::UNow().Format( wxS( "%Y-%m-%dT%H-%M-%S-%l" ) );
2924
2925 if( !overlaySnapshotFiles( tempRestorePath, aProjectPath, backupPath ) )
2926 {
2927 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Overlay failed, rolling back from backup" ) );
2928
2929 // Put back whatever we already overwrote, then drop the partial backups.
2930 if( wxDirExists( backupPath ) )
2931 {
2932 wxString discard = aProjectPath + wxS( "_restore_discard" );
2933 overlaySnapshotFiles( backupPath, aProjectPath, discard );
2934 wxFileName::Rmdir( discard, wxPATH_RMDIR_RECURSIVE );
2935 wxFileName::Rmdir( backupPath, wxPATH_RMDIR_RECURSIVE );
2936 }
2937
2938 wxFileName::Rmdir( tempRestorePath, wxPATH_RMDIR_RECURSIVE );
2939 git_tree_free( tree );
2940 git_commit_free( commit );
2941 return false;
2942 }
2943
2944 // The backup directory is retained so the user can recover any displaced file.
2945 wxLogTrace( traceAutoSave,
2946 wxS( "[history] RestoreCommit: Restore successful, backup retained at %s" ),
2947 backupPath );
2948 wxFileName::Rmdir( tempRestorePath, wxPATH_RMDIR_RECURSIVE );
2949
2950 // Commit the full post-overlay project so HEAD and the saved baseline match the disk.
2951 std::vector<wxString> resultFiles;
2952 collectProjectFiles( aProjectPath, resultFiles );
2953 commitSnapshotWithLock( repo, lock.GetIndex(), historyPath( aProjectPath ), aProjectPath, resultFiles,
2954 wxString::Format( wxS( "Restored from %s" ), aHash ) );
2955
2956 // Anchor the saved baseline so reopening does not re-prompt.
2957 tagSaveAtHead( repo, wxS( "project" ) );
2958
2959 git_tree_free( tree );
2960 git_commit_free( commit );
2961
2962 wxLogTrace( traceAutoSave, wxS( "[history] RestoreCommit: Complete" ) );
2963 return true;
2964}
2965
2966void LOCAL_HISTORY::ShowRestoreDialog( const wxString& aProjectPath, wxWindow* aParent )
2967{
2968 if( !HistoryExists( aProjectPath ) )
2969 return;
2970
2971 std::vector<LOCAL_HISTORY_SNAPSHOT_INFO> snapshots = LoadSnapshots( aProjectPath );
2972
2973 if( snapshots.empty() )
2974 return;
2975
2976 DIALOG_RESTORE_LOCAL_HISTORY dlg( aParent, snapshots );
2977
2978 if( dlg.ShowModal() == wxID_OK )
2979 {
2980 wxString selectedHash = dlg.GetSelectedHash();
2981
2982 if( !selectedHash.IsEmpty() )
2983 RestoreCommit( aProjectPath, selectedHash, aParent );
2984 }
2985}
2986
2987std::vector<LOCAL_HISTORY_SNAPSHOT_INFO> LOCAL_HISTORY::LoadSnapshots( const wxString& aProjectPath )
2988{
2989 std::vector<LOCAL_HISTORY_SNAPSHOT_INFO> snapshots;
2990
2991 wxString hist = historyPath( aProjectPath );
2992 git_repository* repo = nullptr;
2993
2994 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
2995 return snapshots;
2996
2997 git_revwalk* walk = nullptr;
2998 if( git_revwalk_new( &walk, repo ) != 0 )
2999 {
3000 git_repository_free( repo );
3001 return snapshots;
3002 }
3003
3004 git_revwalk_sorting( walk, GIT_SORT_TIME );
3005 git_revwalk_push_head( walk );
3006
3007 git_oid oid;
3008
3009 while( git_revwalk_next( &oid, walk ) == 0 )
3010 {
3011 git_commit* commit = nullptr;
3012
3013 if( git_commit_lookup( &commit, repo, &oid ) != 0 )
3014 continue;
3015
3017 info.hash = wxString::FromUTF8( git_oid_tostr_s( &oid ) );
3018 info.date = wxDateTime( static_cast<time_t>( git_commit_time( commit ) ) );
3019 info.message = wxString::FromUTF8( git_commit_message( commit ) );
3020
3021 wxString firstLine = info.message.BeforeFirst( '\n' );
3022
3023 long parsedCount = 0;
3024 wxString remainder;
3025 firstLine.BeforeFirst( ':', &remainder );
3026 remainder.Trim( true ).Trim( false );
3027
3028 if( remainder.EndsWith( wxS( "files changed" ) ) )
3029 {
3030 wxString countText = remainder.BeforeFirst( ' ' );
3031
3032 if( countText.ToLong( &parsedCount ) )
3033 info.filesChanged = static_cast<int>( parsedCount );
3034 }
3035
3036 info.summary = firstLine.BeforeFirst( ':' );
3037
3038 wxString rest;
3039 info.message.BeforeFirst( '\n', &rest );
3040 wxArrayString lines = wxSplit( rest, '\n', '\0' );
3041
3042 for( const wxString& line : lines )
3043 {
3044 if( !line.IsEmpty() )
3045 info.changedFiles.Add( line );
3046 }
3047
3048 snapshots.push_back( std::move( info ) );
3049 git_commit_free( commit );
3050 }
3051
3052 git_revwalk_free( walk );
3053 git_repository_free( repo );
3054 return snapshots;
3055}
3056
3057
3058std::vector<LOCAL_HISTORY_SNAPSHOT_INFO> LOCAL_HISTORY::GetSnapshots( const wxString& aProjectPath )
3059{
3060 return LoadSnapshots( aProjectPath );
3061}
3062
3063
3064wxString LOCAL_HISTORY::TreeFingerprint( const wxString& aProjectPath, const wxString& aHash,
3065 const wxString& aExtension )
3066{
3067 wxString hist = historyPath( aProjectPath );
3068 git_repository* repo = nullptr;
3069
3070 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
3071 return wxEmptyString;
3072
3073 git_oid oid;
3074 git_commit* commit = nullptr;
3075 git_tree* tree = nullptr;
3076
3077 if( git_oid_fromstr( &oid, aHash.mb_str().data() ) != 0 || git_commit_lookup( &commit, repo, &oid ) != 0 )
3078 {
3079 git_repository_free( repo );
3080 return wxEmptyString;
3081 }
3082
3083 if( git_commit_tree( &tree, commit ) != 0 )
3084 {
3085 git_commit_free( commit );
3086 git_repository_free( repo );
3087 return wxEmptyString;
3088 }
3089
3090 struct WALK_CTX
3091 {
3092 wxString ext;
3093 std::vector<wxString> entries;
3094 } ctx{ aExtension, {} };
3095
3096 auto collect = []( const char* aRoot, const git_tree_entry* aEntry, void* aPayload ) -> int
3097 {
3098 WALK_CTX* c = static_cast<WALK_CTX*>( aPayload );
3099
3100 if( git_tree_entry_type( aEntry ) != GIT_OBJECT_BLOB )
3101 return 0;
3102
3103 wxString name = wxString::FromUTF8( git_tree_entry_name( aEntry ) );
3104
3105 if( !name.EndsWith( c->ext ) )
3106 return 0;
3107
3108 wxString path = wxString::FromUTF8( aRoot ) + name;
3109 c->entries.push_back( path + wxS( ":" )
3110 + wxString::FromUTF8( git_oid_tostr_s( git_tree_entry_id( aEntry ) ) ) );
3111 return 0;
3112 };
3113
3114 git_tree_walk( tree, GIT_TREEWALK_PRE, collect, &ctx );
3115
3116 git_tree_free( tree );
3117 git_commit_free( commit );
3118 git_repository_free( repo );
3119
3120 std::sort( ctx.entries.begin(), ctx.entries.end() );
3121
3122 wxString fingerprint;
3123
3124 for( const wxString& entry : ctx.entries )
3125 fingerprint << entry << wxS( "|" );
3126
3127 return fingerprint;
3128}
3129
3130
3131bool LOCAL_HISTORY::ExtractAllFilesAtCommit( const wxString& aProjectPath, const wxString& aHash,
3132 const wxString& aDestDir, const std::vector<wxString>& aExtensions )
3133{
3134 wxString hist = historyPath( aProjectPath );
3135 git_repository* repo = nullptr;
3136
3137 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
3138 return false;
3139
3140 git_oid oid;
3141 git_commit* commit = nullptr;
3142 git_tree* tree = nullptr;
3143
3144 if( git_oid_fromstr( &oid, aHash.mb_str().data() ) != 0 || git_commit_lookup( &commit, repo, &oid ) != 0 )
3145 {
3146 git_repository_free( repo );
3147 return false;
3148 }
3149
3150 if( git_commit_tree( &tree, commit ) != 0 )
3151 {
3152 git_commit_free( commit );
3153 git_repository_free( repo );
3154 return false;
3155 }
3156
3157 struct WALK_CTX
3158 {
3159 git_repository* repo;
3160 wxString destDir;
3161 const std::vector<wxString>* extensions;
3162 bool ok;
3163 } ctx{ repo, aDestDir, &aExtensions, true };
3164
3165 // Non-capturing so it converts to the libgit2 C callback; state goes via payload.
3166 auto writeEntry = []( const char* aRoot, const git_tree_entry* aEntry, void* aPayload ) -> int
3167 {
3168 WALK_CTX* c = static_cast<WALK_CTX*>( aPayload );
3169
3170 if( git_tree_entry_type( aEntry ) != GIT_OBJECT_BLOB )
3171 return 0;
3172
3173 wxString name = wxString::FromUTF8( git_tree_entry_name( aEntry ) );
3174
3175 if( !c->extensions->empty() )
3176 {
3177 bool match = false;
3178
3179 for( const wxString& ext : *c->extensions )
3180 {
3181 if( name.EndsWith( ext ) )
3182 {
3183 match = true;
3184 break;
3185 }
3186 }
3187
3188 if( !match )
3189 return 0;
3190 }
3191
3192 wxString rel = wxString::FromUTF8( aRoot ) + name;
3193 wxFileName outFn( c->destDir + wxS( "/" ) + rel );
3194
3195 if( !wxFileName::Mkdir( outFn.GetPath(), wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
3196 {
3197 c->ok = false;
3198 return 0;
3199 }
3200
3201 git_blob* blob = nullptr;
3202
3203 if( git_blob_lookup( &blob, c->repo, git_tree_entry_id( aEntry ) ) == 0 )
3204 {
3205 const void* data = git_blob_rawcontent( blob );
3206 const size_t size = static_cast<size_t>( git_blob_rawsize( blob ) );
3207 wxFFile out( outFn.GetFullPath(), wxS( "wb" ) );
3208
3209 if( !( data && out.IsOpened() && out.Write( data, size ) == size ) )
3210 c->ok = false;
3211
3212 git_blob_free( blob );
3213 }
3214 else
3215 {
3216 c->ok = false;
3217 }
3218
3219 return 0;
3220 };
3221
3222 git_tree_walk( tree, GIT_TREEWALK_PRE, writeEntry, &ctx );
3223
3224 git_tree_free( tree );
3225 git_commit_free( commit );
3226 git_repository_free( repo );
3227 return ctx.ok;
3228}
int index
const char * name
bool AutosaveUsesLocalHistory() const
The backup format is the single switch that selects the autosave mechanism: the incremental format re...
AUTO_BACKUP m_Backup
int ShowModal() override
bool ShouldDescend(const wxString &aDir)
bool IsRooted() const
Definition gestfich.h:267
Hybrid locking mechanism for local history git repositories.
git_repository * GetRepository()
Get the git repository handle (only valid if IsLocked() returns true).
void ReleaseRepository()
Release git repository and index handles early, but keep the file lock.
wxString GetLockError() const
Get error message describing why lock could not be acquired.
git_index * GetIndex()
Get the git index handle (only valid if IsLocked() returns true).
git_repository * ReopenRepository()
Re-open the git repository and index after ReleaseRepository().
bool IsLocked() const
Check if locks were successfully acquired.
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
std::vector< LOCAL_HISTORY_SNAPSHOT_INFO > LoadSnapshots(const wxString &aProjectPath)
void EnforceSizeLimitInBackground(const wxString &aProjectPath, size_t aMaxBytes)
Run EnforceSizeLimit without a reporter on a background thread, after any running compaction.
bool EnforceSizeLimit(const wxString &aProjectPath, size_t aMaxBytes, PROGRESS_REPORTER *aReporter=nullptr)
Enforce total size limit by rebuilding trimmed history keeping newest commits whose cumulative unique...
bool TagSave(const wxString &aProjectPath, const wxString &aFileType)
Tag a manual save in the local history repository.
static std::vector< std::pair< wxString, wxString > > CollectAutosaveFilePairs(const wxString &aAutosaveRoot, const wxString &aProjectPath, BACKUP_LOCATION aLocation)
Enumerate every (autosave, source) pair found under aAutosaveRoot for the project at aProjectPath,...
bool RunRegisteredSaversAndCommit(const wxString &aProjectPath, const wxString &aTitle, const wxString &aTagFileType=wxEmptyString)
Run all registered savers and, if any staged changes differ from HEAD, create a commit.
std::vector< std::pair< wxString, wxString > > FindStaleAutosaveFiles(const wxString &aProjectPath, const std::vector< wxString > &aExtensions) const
Enumerate autosave files newer than their corresponding source files for the project at aProjectPath,...
wxString GetHeadHash(const wxString &aProjectPath)
Return the current head commit hash.
std::future< void > m_compactFuture
void RegisterProjectSaver(PROJECT *aProject)
Register aProject's own files (project, rules and library tables) for history snapshots.
SNAPSHOT_COMMIT_RESULT commitInBackground(const wxString &aProjectPath, const wxString &aTitle, const std::vector< HISTORY_FILE_DATA > &aFileData, bool aIsManualSave)
Execute file writes and git commit on a background thread.
void ShowRestoreDialog(const wxString &aProjectPath, wxWindow *aParent)
Show a dialog allowing the user to choose a snapshot to restore.
std::map< const void *, SAVER_ENTRY > m_savers
bool HeadNewerThanLastSave(const wxString &aProjectPath)
Return true if the autosave data is newer than the last manual save.
std::set< wxString > m_pendingFiles
bool CommitDuplicateOfLastSave(const wxString &aProjectPath, const wxString &aFileType, const wxString &aMessage)
Create a new commit duplicating the tree pointed to by Last_Save_<fileType> and move the Last_Save_<f...
void WaitForPendingSave()
Block until any pending background save completes.
bool RestoreCommit(const wxString &aProjectPath, const wxString &aHash, wxWindow *aParent=nullptr, bool aConfirm=true)
Restore the project files to the state recorded by the given commit hash.
void scheduleCompaction(const wxString &aProjectPath, size_t aLooseLimit)
Start packing loose history objects on a background thread once they exceed aLooseLimit bytes,...
bool IsCompacting() const
True while a background compaction started by autosave is still running.
bool Init(const wxString &aProjectPath)
Initialize the local history repository for the given project path.
void ClearAllSavers()
Clear all registered savers.
bool CommitSnapshot(const std::vector< wxString > &aFiles, const wxString &aTitle)
Commit the given files to the local history repository.
std::atomic< bool > m_saveInProgress
void NoteFileChange(const wxString &aFile)
Record that a file has been modified and should be included in the next snapshot.
bool enforceSizeLimit(const wxString &aProjectPath, const wxString &aHistoryPath, size_t aMaxBytes, PROGRESS_REPORTER *aReporter)
EnforceSizeLimit with the history directory already resolved, so it can run off the UI thread.
bool CommitPending()
Commit any pending modified files to the history repository.
bool HistoryExists(const wxString &aProjectPath)
Return true if history exists for the project.
bool RunRegisteredSaversAsAutosaveFiles(const wxString &aProjectPath)
Run all registered savers and write their output to autosave files instead of committing to the local...
bool CommitFullProjectSnapshot(const wxString &aProjectPath, const wxString &aTitle)
Commit a snapshot of the entire project directory (excluding the .history directory and ignored trans...
std::vector< LOCAL_HISTORY_SNAPSHOT_INFO > GetSnapshots(const wxString &aProjectPath)
Snapshots (commits) for the project, newest first.
wxString TreeFingerprint(const wxString &aProjectPath, const wxString &aHash, const wxString &aExtension)
Fingerprint of all files ending in aExtension recorded by commit aHash (sorted path:blob pairs).
bool ExtractAllFilesAtCommit(const wxString &aProjectPath, const wxString &aHash, const wxString &aDestDir, const std::vector< wxString > &aExtensions={})
Write files recorded at aHash into aDestDir, recreating the project's relative folder structure.
std::atomic< bool > m_cancelCompaction
std::future< bool > m_pendingFuture
void RegisterSaver(const void *aSaverObject, const std::function< void(const wxString &, std::vector< HISTORY_FILE_DATA > &)> &aSaver, const std::weak_ptr< void > &aLifetime={})
Register a saver callback invoked during autosave history commits.
void UnregisterSaver(const void *aSaverObject)
Unregister a previously registered saver callback.
void pruneExpiredSavers()
Drop tracked savers whose owning document has been freed, before any saver runs.
void RemoveAutosaveFiles(const wxString &aProjectPath) const
Remove every autosave file under the project at aProjectPath regardless of which source it shadowed.
Advisory lock over a file, taken by writing a sibling lock file and holding an exclusive lock on it f...
Definition lockfile.h:54
bool Valid() const
Definition lockfile.h:224
bool IsLockedByMe()
Definition lockfile.h:200
static LOCKFILE Inspect(const wxString &aFilename)
Look at a lock without taking it: nothing is created, nothing is claimed and nothing is removed on re...
Definition lockfile.h:113
static bool EnsurePathExists(const wxString &aPath, bool aPathToFile=false)
Attempts to create a given path if it does not exist.
Definition paths.cpp:470
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:576
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
A progress reporter interface for use in multi-threaded environments.
virtual bool KeepRefreshing(bool aWait=false)=0
Update the UI (if any).
virtual void Report(const wxString &aMessage)=0
Display aMessage in the progress bar dialog.
virtual void AdvancePhase()=0
Use the next available virtual zone of the dialog progress bar.
virtual void SetCurrentProgress(double aProgress)=0
Set the progress value to aProgress (0..1).
Container for project specific data.
Definition project.h:63
std::weak_ptr< void > GetHistoryLifetimeToken() const
Liveness token handed to LOCAL_HISTORY::RegisterSaver so a shared autosave timer skips this project's...
Definition project.h:333
void SaveToHistory(const wxString &aProjectPath, std::vector< HISTORY_FILE_DATA > &aFileData)
Produce HISTORY_FILE_DATA entries for project files (.kicad_pro and .kicad_prl).
Definition project.cpp:561
COMMON_SETTINGS * GetCommonSettings() const
Retrieve the common settings shared by all applications.
wxString GetAutosaveRootForProject(const PROJECT *aProject=nullptr) const
Resolve the autosave-files root for a project.
PROJECT * GetProjectForPath(const wxString &aProjectPath) const
Return the active project iff its path matches aProjectPath, else nullptr.
wxString GetLocalHistoryDirForPath(const wxString &aProjectPath) const
Resolve the local-history directory for a project given by its on-disk path.
BACKUP_LOCATION
@ PROJECT_DIR
Inside the project directory (default)
This file is part of the common library.
#define KICAD_MESSAGE_DIALOG
Definition confirm.h:48
#define _(s)
static const std::string LockFileExtension
static const std::string ProjectFileExtension
static const std::string LockFilePrefix
const wxChar *const traceAutoSave
Flag to enable auto save feature debug tracing.
static wxString historyPath(const wxString &aProjectPath)
static bool readFileContent(const wxString &aPath, std::string &aContent)
static wxString historyPath(const wxString &aProjectPath)
static bool isRestoreProtectedEntry(const wxString &aName)
static const wxString STAGE_DIR_PREFIX
static std::vector< std::pair< wxString, wxString > > findAutosaveFilePairs(const wxString &aProjectPath)
static void removeStaleStageDirs(const wxString &aGitDir)
static const wxString AUTOSAVE_PREFIX
static bool commitSnapshotForProject(const wxString &aProjectPath, const std::vector< wxString > &aFiles, const wxString &aTitle)
static size_t dirSizeRecursive(const wxString &path)
static bool isKiCadProjectFile(const wxFileName &aFile)
static wxString buildPack(git_repository *aRepo, const wxString &aPackDir, PROGRESS_REPORTER *aReporter, const std::atomic< bool > *aCancel)
static wxString sourceForAutosaveFile(const wxString &aAutosavePath, const wxString &aProjectPath, const wxString &aAutosaveRoot, BACKUP_LOCATION aLocation)
static std::vector< wxString > supersededBy(const std::vector< wxString > &aPriorPacks, const wxString &aNewStem)
static bool tagSaveAtHead(git_repository *repo, const wxString &aFileType)
static bool writePack(git_packbuilder *aPb, const wxString &aPackDir, PROGRESS_REPORTER *aReporter, const std::atomic< bool > *aCancel=nullptr)
static wxString resolveAutosaveDestination(const wxString &aAutosaveRoot, const wxString &aRelativePath, BACKUP_LOCATION aLocation)
static SNAPSHOT_COMMIT_RESULT commitSnapshotWithLock(git_repository *repo, git_index *index, const wxString &aHistoryPath, const wxString &aProjectPath, const std::vector< wxString > &aFiles, const wxString &aTitle)
static bool localHistoryEnabled()
static bool filesContentEqual(const wxString &aPathA, const wxString &aPathB)
static void pruneLooseObjects(const wxString &aObjectsPath, const wxString &aPackIndex, time_t aWalkStart)
static const size_t UNLIMITED_HISTORY_LOOSE_BYTES
static void removeLegacyWorkingCopies(git_repository *aRepo, const wxString &aHistoryRoot)
static size_t looseObjectBytes(const wxString &aObjectsPath)
static const time_t UNREACHABLE_LOOSE_EXPIRY_SECONDS
static std::vector< wxString > listPackFiles(const wxString &aPackDir)
static bool compactRepository(git_repository *aRepo, PROGRESS_REPORTER *aReporter, std::vector< wxString > *aSupersededPacks)
static bool isProjectDirectory(const wxString &aProjectPath)
static void collectProjectFiles(const wxString &aProjectPath, std::vector< wxString > &aFiles)
static std::vector< std::string > refTargets(git_repository *aRepo)
static wxString joinHistoryDestination(const wxString &aHistoryRoot, const wxString &aRelativePath)
SNAPSHOT_COMMIT_RESULT
void Prettify(std::string &aSource, FORMAT_MODE aMode)
Pretty-prints s-expression text according to KiCad format rules.
bool AtomicWriteFile(const wxString &aTargetPath, const void *aData, size_t aSize, wxString *aError=nullptr)
Writes aData to aTargetPath via a sibling temp file, fsyncs the data and directory,...
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
static const std::vector< std::string > extensions
Definition plugin.cpp:63
static std::vector< uint8_t > copyBytes(const void *aData, size_t aBytes)
#define PROJECT_BACKUPS_DIR_SUFFIX
Project settings path will be <projectname> + this.
unsigned long long limit_total_size
Maximum total size of backups (bytes), 0 for unlimited.
BACKUP_LOCATION location
Where backups, history, and autosave files live.
Data produced by a registered saver on the UI thread, consumed by either the background local-history...
std::function< void(const wxString &, std::vector< HISTORY_FILE_DATA > &)> saver
bool tracked
std::weak_ptr< void > lifetime
std::string path
IbisParser parser & reporter
VECTOR2I location
wxString result
Test unit parsing edge cases and error handling.
int delta
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
wxLogTrace helper definitions.
Definition of file extensions used in Kicad.