40#include <git2/sys/odb_backend.h>
42#include <wx/filename.h>
46#include <wx/datetime.h>
74 const wxString& aRelativePath )
76 wxFileName fn( aRelativePath );
79 return fn.GetFullPath();
84 wxArrayString dirs = fn.GetDirs();
87 dst.AssignDir( aHistoryRoot );
89 for(
const wxString& d : dirs )
92 dst.SetFullName( fn.GetFullName() );
93 return dst.GetFullPath();
106 std::ifstream file( aPath.fn_str(), std::ios::binary );
111 aContent.assign( std::istreambuf_iterator<char>( file ), std::istreambuf_iterator<char>() );
121 wxDir histDir( aHistoryRoot );
123 bool hasCopies =
false;
124 bool cont = histDir.IsOpened()
125 && histDir.GetFirst( &
name, wxEmptyString, wxDIR_FILES | wxDIR_DIRS | wxDIR_HIDDEN );
128 while( cont && !hasCopies )
130 hasCopies =
name != wxS(
".git" ) &&
name != wxS(
".gitignore" ) &&
name != wxS(
"README.txt" );
131 cont = histDir.GetNext( &
name );
138 git_commit* head =
nullptr;
139 git_tree* tree =
nullptr;
141 if( git_reference_name_to_id( &headOid, aRepo,
"HEAD" ) != 0 || git_commit_lookup( &head, aRepo, &headOid ) != 0 )
144 if( git_commit_tree( &tree, head ) == 0 )
149 std::vector<wxString> dirs;
150 } state{ aHistoryRoot, {} };
153 tree, GIT_TREEWALK_POST,
154 [](
const char* aDir,
const git_tree_entry* aEntry,
void* aPayload ) ->
int
156 auto* walkState =
static_cast<WALK_STATE*
>( aPayload );
157 wxString rel = wxString::FromUTF8( aDir ) + wxString::FromUTF8( git_tree_entry_name( aEntry ) );
159 if( rel.Contains( wxS(
".." ) ) )
164 if( git_tree_entry_type( aEntry ) == GIT_OBJECT_TREE )
165 walkState->dirs.push_back(
path );
166 else if( wxFileExists(
path ) )
167 wxRemoveFile(
path );
175 wxLogNull suppressRmdirErrors;
177 for(
const wxString& dir : state.dirs )
179 if( wxDirExists( dir ) )
183 git_tree_free( tree );
186 git_commit_free( head );
193 wxFFile fileA( aPathA, wxS(
"rb" ) );
194 wxFFile fileB( aPathB, wxS(
"rb" ) );
196 if( !fileA.IsOpened() || !fileB.IsOpened() )
199 wxFileOffset lenA = fileA.Length();
200 wxFileOffset lenB = fileB.Length();
202 if( lenA < 0 || lenB < 0 || lenA != lenB )
205 constexpr size_t chunkSize = 64 * 1024;
206 std::vector<char> bufA( chunkSize );
207 std::vector<char> bufB( chunkSize );
209 while( !fileA.Eof() )
211 size_t readA = fileA.Read( bufA.data(), chunkSize );
212 size_t readB = fileB.Read( bufB.data(), chunkSize );
217 if( readA > 0 && std::memcmp( bufA.data(), bufB.data(), readA ) != 0 )
220 if( fileA.Error() || fileB.Error() )
234 const wxString& aRelativePath,
237 wxFileName rel( aRelativePath );
239 dst.AssignDir( aAutosaveRoot );
241 for(
const wxString& d : rel.GetDirs() )
247 dst.SetFullName( rel.GetFullName() );
249 return dst.GetFullPath();
257 const wxString& aProjectPath,
258 const wxString& aAutosaveRoot,
261 wxFileName autosave( aAutosavePath );
265 wxString
name = autosave.GetFullName();
268 return wxEmptyString;
271 return autosave.GetFullPath();
274 if( !aAutosavePath.StartsWith( aAutosaveRoot ) )
275 return wxEmptyString;
277 wxString rel = aAutosavePath.Mid( aAutosaveRoot.length() );
278 wxFileName projFn( aProjectPath, wxEmptyString );
280 return projFn.GetPathWithSep() + rel;
285 const wxString& aTitle );
306 if( aProjectPath.IsEmpty() || !wxDirExists( aProjectPath ) )
309 wxDir dir( aProjectPath );
312 return dir.IsOpened()
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" )
348 wxFileName fn( aFile );
358 const void* aSaverObject,
359 const std::function<
void(
const wxString&, std::vector<HISTORY_FILE_DATA>& )>& aSaver,
360 const std::weak_ptr<void>& aLifetime )
364 wxLogTrace(
traceAutoSave, wxS(
"[history] Saver %p already registered, skipping" ), aSaverObject );
369 entry.
saver = aSaver;
374 entry.
tracked = aLifetime.lock() !=
nullptr;
376 m_savers[aSaverObject] = std::move( entry );
377 wxLogTrace(
traceAutoSave, wxS(
"[history] Registered saver %p (total=%zu)" ), aSaverObject,
m_savers.size() );
384 [aProject](
const wxString& aProjectPath, std::vector<HISTORY_FILE_DATA>& aFileData )
387 if(
Pgm().GetCommonSettings()->AutosaveUsesLocalHistory() )
396 std::vector<const void*> expired;
400 for(
const auto& [saverObject, entry] :
m_savers )
402 if( entry.tracked && entry.lifetime.expired() )
403 expired.push_back( saverObject );
406 for(
const void* obj : expired )
415 auto it =
m_savers.find( aSaverObject );
420 wxLogTrace(
traceAutoSave, wxS(
"[history] Unregistered saver %p (total=%zu)" ),
430 wxLogTrace(
traceAutoSave, wxS(
"[history] Cleared all savers" ) );
435 const wxString& aTagFileType )
439 wxLogTrace(
traceAutoSave, wxS(
"Local history disabled, returning" ) );
446 Init( aProjectPath );
449 wxS(
"[history] RunRegisteredSaversAndCommit start project='%s' title='%s' savers=%zu tag='%s'" ),
450 aProjectPath, aTitle,
m_savers.size(), aTagFileType );
454 wxLogTrace(
traceAutoSave, wxS(
"[history] no savers registered; skipping") );
459 if( !aTagFileType.IsEmpty() )
465 wxLogTrace(
traceAutoSave, wxS(
"[history] previous save still in progress; skipping cycle" ) );
472 std::vector<HISTORY_FILE_DATA> fileData;
474 for(
const auto& [saverObject, entry] :
m_savers )
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() );
485 fileData.erase( std::remove_if( fileData.begin(), fileData.end(),
488 if( entry.relativePath.IsEmpty() || wxFileName( entry.relativePath ).IsAbsolute() )
490 wxLogTrace( traceAutoSave, wxS(
"[history] filtered out entry with invalid path: '%s'" ),
491 entry.relativePath );
498 if( fileData.empty() )
500 wxLogTrace(
traceAutoSave, wxS(
"[history] saver set produced no entries; skipping" ) );
505 m_saveInProgress.store(
true, std::memory_order_release );
508 [
this, projectPath = aProjectPath, title = aTitle, tagFileType = aTagFileType,
509 data = std::move( fileData )]()
mutable ->
bool
512 !tagFileType.IsEmpty() );
516 TagSave( projectPath, tagFileType );
518 m_saveInProgress.store(
false, std::memory_order_release );
523 if( !aTagFileType.IsEmpty() )
525 WaitForPendingSave();
540 if( !
Pgm().GetCommonSettings()->m_Backup.enabled )
545 wxLogTrace(
traceAutoSave, wxS(
"[autosave] no savers registered; skipping" ) );
555 wxLogTrace(
traceAutoSave, wxS(
"[autosave] cannot create autosave root '%s'" ), autosaveRoot );
561 std::vector<HISTORY_FILE_DATA> fileData;
563 for(
const auto& [saverObject, entry] :
m_savers )
564 entry.saver( aProjectPath, fileData );
566 bool anyWritten =
false;
570 if( entry.removed || entry.relativePath.IsEmpty() || wxFileName( entry.relativePath ).IsAbsolute() )
574 wxFileName dstFn( dst );
578 wxLogTrace(
traceAutoSave, wxS(
"[autosave] cannot create dir '%s'" ), dstFn.GetPath() );
584 if( !entry.content.empty() )
586 buf = std::move( entry.content );
591 else if( !entry.sourcePath.IsEmpty() )
593 wxFFile src( entry.sourcePath, wxS(
"rb" ) );
595 if( !src.IsOpened() )
598 wxFileOffset len = src.Length();
603 buf.resize(
static_cast<size_t>( len ) );
605 if( len > 0 && src.Read( buf.data(), buf.size() ) != buf.size() )
621 wxLogTrace(
traceAutoSave, wxS(
"[autosave] wrote %zu bytes to '%s'" ), buf.size(), dst );
625 wxLogTrace(
traceAutoSave, wxS(
"[autosave] write failed for '%s': %s" ), dst, err );
638std::vector<std::pair<wxString, wxString>>
642 std::vector<std::pair<wxString, wxString>> results;
644 if( !wxDirExists( aAutosaveRoot ) )
652 std::function<void(
const wxString& )> walk =
653 [&](
const wxString& aDir )
661 bool cont = d.GetFirst( &
name );
665 wxFileName fn( aDir,
name );
666 wxString fullPath = fn.GetFullPath();
668 if( wxDirExists( fullPath ) )
671 && (
name == wxS(
".history" ) ||
name.EndsWith( wxS(
"-backups" ) ) ) )
673 cont = d.GetNext( &
name );
687 results.emplace_back( fullPath, src );
690 cont = d.GetNext( &
name );
694 walk( aAutosaveRoot );
699static std::vector<std::pair<wxString, wxString>>
710std::vector<std::pair<wxString, wxString>>
713 std::vector<std::pair<wxString, wxString>> results;
715 if( aExtensions.empty() )
720 wxFileName srcFn( pair.second );
723 for(
const wxString& ext : aExtensions )
725 if( srcFn.GetExt().IsSameAs( ext,
false ) )
737 if( srcFn.FileExists() )
738 srcTime = srcFn.GetModificationTime();
740 wxDateTime autosaveTime = wxFileName( pair.first ).GetModificationTime();
744 bool stale = !srcTime.IsValid()
745 || ( autosaveTime.IsLaterThan( srcTime )
749 results.emplace_back( std::move( pair ) );
763 if( wxFileExists( autosavePath ) )
764 wxRemoveFile( autosavePath );
770 const std::vector<wxString>& aSourcePaths )
const
772 if( aSourcePaths.empty() )
775 std::vector<wxFileName> targets;
776 targets.reserve( aSourcePaths.size() );
778 for(
const wxString& src : aSourcePaths )
781 targets.emplace_back( src );
784 if( targets.empty() )
789 wxFileName srcFn( srcPath );
792 for(
const wxFileName& target : targets )
794 if( srcFn.SameAs( target ) )
801 if( match && wxFileExists( autosavePath ) )
802 wxRemoveFile( autosavePath );
808 const std::vector<HISTORY_FILE_DATA>& aFileData,
811 wxLogTrace(
traceAutoSave, wxS(
"[history] background: writing %zu entries for '%s'" ),
812 aFileData.size(), aProjectPath );
818 wxLogTrace(
traceAutoSave, wxS(
"[history] background: cannot create history root '%s'" ), hist );
824 wxString relativePath;
826 bool removed =
false;
829 std::vector<STAGED_FILE> staged;
833 STAGED_FILE file{ entry.relativePath, std::string(), entry.removed };
837 staged.push_back( std::move( file ) );
841 if( !entry.content.empty() )
843 file.content = entry.content;
848 else if( entry.sourcePath.IsEmpty() )
855 wxLogTrace(
traceAutoSave, wxS(
"[history] background: cannot read '%s'" ), entry.sourcePath );
859 staged.push_back( std::move( file ) );
877 for(
const STAGED_FILE& file : staged )
879 wxString rel = file.relativePath;
880 rel.Replace( wxS(
"\\" ), wxS(
"/" ) );
882 std::string
path = rel.utf8_string();
887 if( git_index_remove_bypath(
index,
path.c_str() ) != 0 )
889 wxLogTrace(
traceAutoSave, wxS(
"[history] background: failed to unstage '%s'" ), rel );
890 git_index_read(
index,
true );
897 git_index_entry indexEntry = {};
898 indexEntry.mode = GIT_FILEMODE_BLOB;
899 indexEntry.path =
path.c_str();
901 if( git_index_add_from_buffer(
index, &indexEntry, file.content.data(), file.content.size() ) != 0 )
904 wxLogTrace(
traceAutoSave, wxS(
"[history] background: failed to stage '%s'" ), rel );
905 git_index_read(
index,
true );
912 git_commit* head_commit =
nullptr;
913 git_tree* head_tree =
nullptr;
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 );
919 git_tree* rawIndexTree =
nullptr;
920 git_oid index_tree_oid;
922 if( git_index_write_tree( &index_tree_oid,
index ) != 0 )
925 git_tree_free( head_tree );
928 git_commit_free( head_commit );
930 wxLogTrace(
traceAutoSave, wxS(
"[history] background: failed to write index tree" ) );
934 git_tree_lookup( &rawIndexTree, repo, &index_tree_oid );
935 std::unique_ptr<git_tree,
decltype( &git_tree_free )> indexTree( rawIndexTree, &git_tree_free );
937 bool hasChanges =
true;
941 git_diff* diff =
nullptr;
943 if( git_diff_tree_to_tree( &diff, repo, head_tree, indexTree.get(),
nullptr ) == 0 )
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 );
955 bool stagedMatchesDisk =
true;
957 for(
const STAGED_FILE& file : staged )
959 wxFileName diskPath( file.relativePath );
960 std::string diskContent;
962 diskPath.MakeAbsolute( aProjectPath );
964 const bool matchesDisk = file.removed ? !diskPath.FileExists()
966 && diskContent == file.content;
970 stagedMatchesDisk =
false;
975 if( stagedMatchesDisk && !aIsManualSave )
977 wxLogTrace(
traceAutoSave, wxS(
"[history] background: first commit; staged matches disk -- skipping" ) );
983 git_tree_free( head_tree );
986 git_commit_free( head_commit );
990 wxLogTrace(
traceAutoSave, wxS(
"[history] background: no changes detected; no commit") );
994 if( !aTitle.IsEmpty() && aTitle != wxS(
"Autosave" ) )
996 git_oid head_oid_amend;
998 if( git_reference_name_to_id( &head_oid_amend, repo,
"HEAD" ) == 0 )
1000 git_commit* head_commit_amend =
nullptr;
1002 if( git_commit_lookup( &head_commit_amend, repo, &head_oid_amend ) == 0 )
1004 wxString existingMsg = wxString::FromUTF8( git_commit_message( head_commit_amend ) );
1005 existingMsg.Trim(
true ).Trim(
false );
1007 if( existingMsg != aTitle )
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 );
1014 wxLogTrace(
traceAutoSave, wxS(
"[history] background: amended HEAD message '%s' -> '%s'" ),
1015 existingMsg, aTitle );
1017 wxLogTrace(
traceAutoSave, wxS(
"[history] background: amend failed rc=%d" ), amend_rc );
1020 git_commit_free( head_commit_amend );
1028 git_signature* rawSig =
nullptr;
1030 std::unique_ptr<git_signature,
decltype( &git_signature_free )> sig( rawSig, &git_signature_free );
1032 git_commit* parent =
nullptr;
1036 if( git_reference_name_to_id( &parent_id, repo,
"HEAD" ) == 0 )
1038 if( git_commit_lookup( &parent, repo, &parent_id ) == 0 )
1042 wxString msg = aTitle.IsEmpty() ? wxString(
"Autosave" ) : aTitle;
1044 const git_commit* constParent = parent;
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 );
1052 wxLogTrace(
traceAutoSave, wxS(
"[history] background: commit created %s (%s entries=%zu)" ),
1053 wxString::FromUTF8( git_oid_tostr_s( &commit_id ) ), msg, aFileData.size() );
1057 wxLogTrace(
traceAutoSave, wxS(
"[history] background: commit failed rc=%d" ), rc );
1061 git_commit_free( parent );
1063 git_index_write(
index );
1072 wxLogTrace(
traceAutoSave, wxS(
"[history] waiting for pending background save" ) );
1096 if( !wxDirExists( hist ) )
1098 wxLogNull suppressSysErrorPopups;
1109 if( git_repository_open( &rawRepo, hist.mb_str().data() ) != 0 )
1111 if( git_repository_init( &rawRepo, hist.mb_str().data(), 0 ) != 0 )
1114 wxFileName ignoreFile( hist, wxS(
".gitignore" ) );
1115 if( !ignoreFile.FileExists() )
1117 wxFFile f( ignoreFile.GetFullPath(), wxT(
"w" ) );
1120 f.Write( wxS(
"# KiCad local history exclusions. Edit to add your own rules.\n"
1127 wxFileName readmeFile( hist, wxS(
"README.txt" ) );
1129 if( !readmeFile.FileExists() )
1131 wxFFile f( readmeFile.GetFullPath(), wxT(
"w" ) );
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" ) );
1151 git_repository_free( rawRepo );
1161 const wxString& aHistoryPath,
const wxString& aProjectPath,
1162 const std::vector<wxString>& aFiles,
const wxString& aTitle )
1164 std::vector<std::string> filesArrStr;
1166 for(
const wxString& file : aFiles )
1168 wxFileName src( file );
1171 if( src.GetFullPath().StartsWith( aProjectPath + wxFILE_SEP_PATH ) )
1172 relPath = src.GetFullPath().Mid( aProjectPath.length() + 1 );
1174 relPath = src.GetFullName();
1176 relPath.Replace(
"\\",
"/" );
1177 std::string relPathStr = relPath.ToStdString();
1179 unsigned int status = 0;
1180 int rc = git_status_file( &status, repo, relPathStr.data() );
1182 if( rc == 0 && status != 0 )
1184 wxLogTrace(
traceAutoSave, wxS(
"File %s status %d " ), relPath, status );
1185 filesArrStr.emplace_back( relPathStr );
1189 wxLogTrace(
traceAutoSave, wxS(
"File %s status error %d " ), relPath, rc );
1190 filesArrStr.emplace_back( relPathStr );
1194 std::vector<char*> cStrings( filesArrStr.size() );
1196 for(
size_t i = 0; i < filesArrStr.size(); i++ )
1197 cStrings[i] = filesArrStr[i].data();
1199 git_strarray filesArrGit;
1200 filesArrGit.count = filesArrStr.size();
1201 filesArrGit.strings = cStrings.data();
1203 if( filesArrStr.size() == 0 )
1209 int rc = git_index_add_all(
index, &filesArrGit, GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH | GIT_INDEX_ADD_FORCE, NULL,
1211 wxLogTrace(
traceAutoSave, wxS(
"Adding %zu files, rc %d" ), filesArrStr.size(), rc );
1217 if( git_index_write_tree( &tree_id,
index ) != 0 )
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 );
1224 git_signature* rawSig =
nullptr;
1226 std::unique_ptr<git_signature,
decltype( &git_signature_free )> sig( rawSig,
1227 &git_signature_free );
1229 git_commit* rawParent =
nullptr;
1233 if( git_reference_name_to_id( &parent_id, repo,
"HEAD" ) == 0 )
1235 git_commit_lookup( &rawParent, repo, &parent_id );
1239 std::unique_ptr<git_commit,
decltype( &git_commit_free )> parent( rawParent,
1242 git_tree* rawParentTree =
nullptr;
1245 git_commit_tree( &rawParentTree, parent.get() );
1247 std::unique_ptr<git_tree,
decltype( &git_tree_free )> parentTree( rawParentTree, &git_tree_free );
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 );
1253 size_t numChangedFiles = git_diff_num_deltas( diff.get() );
1255 if( numChangedFiles == 0 )
1257 wxLogTrace(
traceAutoSave, wxS(
"No actual changes in tree, skipping commit" ) );
1263 if( !aTitle.IsEmpty() )
1264 msg << aTitle << wxS(
": " );
1266 msg << numChangedFiles << wxS(
" files changed" );
1268 for(
size_t i = 0; i < numChangedFiles; ++i )
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,
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 );
1280 msg << wxS(
"\n" ) << wxString::FromUTF8(
delta->new_file.path )
1281 << wxS(
" " ) << adds << wxS(
"/" ) << dels << wxS(
"/" ) << updated;
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 )
1294 git_index_write(
index );
1303 const wxString& aTitle )
1311 wxLogTrace(
traceAutoSave, wxS(
"[history] commitSnapshotForProject failed to acquire lock: %s" ),
1328 wxString proj = wxFileName( aFiles[0] ).GetPath();
1342 wxString
name = aFile.GetFullName();
1344 if(
name == wxS(
"sym-lib-table" ) ||
name == wxS(
"fp-lib-table" ) )
1347 return aFile.GetExt().StartsWith( wxS(
"kicad_" ) );
1356 wxDir dir( aProjectPath );
1358 if( !dir.IsOpened() )
1369 std::function<void(
const wxString&,
bool )> collect =
1370 [&](
const wxString&
path,
bool topLevel )
1375 wxS(
"[history] collectProjectFiles: Skipping nested project at %s" ),
1386 bool cont = d.GetFirst( &
name );
1392 cont = d.GetNext( &
name );
1397 wxString fullPath = fn.GetFullPath();
1399 if( wxFileName::DirExists( fullPath ) )
1402 collect( fullPath,
false );
1404 else if( fn.FileExists() && fn.GetFullName() != wxS(
"fp-info-cache" ) &&
isKiCadProjectFile( fn ) )
1406 aFiles.push_back( fn.GetFullPath() );
1409 cont = d.GetNext( &
name );
1413 collect( aProjectPath,
true );
1422 std::vector<wxString> files;
1428 Init( aProjectPath );
1434 return wxDirExists(
historyPath( aProjectPath ) );
1446 if( git_reference_name_to_id( &head, repo,
"HEAD" ) != 0 )
1451 git_reference* ref =
nullptr;
1454 tagName.Printf( wxS(
"Save_%s_%d" ), aFileType, i++ );
1455 }
while( git_reference_lookup( &ref, repo, ( wxS(
"refs/tags/" ) + tagName ).mb_str().data() ) == 0 );
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 );
1464 lastName.Printf( wxS(
"Last_Save_%s" ), aFileType );
1465 if( git_reference_lookup( &ref, repo, ( wxS(
"refs/tags/" ) + lastName ).mb_str().data() ) == 0 )
1467 git_reference_delete( ref );
1468 git_reference_free( ref );
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 );
1493 wxLogTrace(
traceAutoSave, wxS(
"[history] TagSave: Failed to acquire lock for %s" ), aProjectPath );
1505 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
1509 if( git_reference_name_to_id( &head_oid, repo,
"HEAD" ) != 0 )
1511 git_repository_free( repo );
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 );
1520 git_tag_list_match( &tags,
"Last_Save_*", repo );
1521 git_time_t save_time = 0;
1523 for(
size_t i = 0; i < tags.count; ++i )
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 )
1530 const git_oid* oid = git_reference_target( ref );
1531 git_commit* c =
nullptr;
1532 if( git_commit_lookup( &c, repo, oid ) == 0 )
1534 git_time_t t = git_commit_time( c );
1537 git_commit_free( c );
1539 git_reference_free( ref );
1543 git_strarray_free( &tags );
1544 git_commit_free( head_commit );
1545 git_repository_free( repo );
1549 if( save_time == 0 )
1552 return head_time > save_time;
1556 const wxString& aMessage )
1568 wxLogTrace(
traceAutoSave, wxS(
"[history] CommitDuplicateOfLastSave: Failed to acquire lock for %s" ), aProjectPath );
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 )
1581 std::unique_ptr<git_reference,
decltype( &git_reference_free )> lastRefPtr( lastRef, &git_reference_free );
1583 const git_oid* lastOid = git_reference_target( lastRef );
1584 git_commit* lastCommit =
nullptr;
1585 if( git_commit_lookup( &lastCommit, repo, lastOid ) != 0 )
1587 std::unique_ptr<git_commit,
decltype( &git_commit_free )> lastCommitPtr( lastCommit, &git_commit_free );
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 );
1595 git_commit* headCommit =
nullptr;
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 )
1601 parentArray[0] = headCommit;
1605 git_signature* sigRaw =
nullptr;
1607 std::unique_ptr<git_signature,
decltype( &git_signature_free )> sig( sigRaw, &git_signature_free );
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 );
1618 git_reference* existing =
nullptr;
1619 if( git_reference_lookup( &existing, repo, ( wxS(
"refs/tags/") + lastName ).mb_str().data() ) == 0 )
1621 git_reference_delete( existing );
1622 git_reference_free( existing );
1624 git_object* newCommitObj =
nullptr;
1625 if( git_object_lookup( &newCommitObj, repo, &newCommitOid, GIT_OBJECT_COMMIT ) == 0 )
1627 git_tag_create_lightweight( &newCommitOid, repo, lastName.mb_str().data(), newCommitObj, 0 );
1628 git_object_free( newCommitObj );
1637 if( !dir.IsOpened() )
1640 bool cont = dir.GetFirst( &
name );
1644 wxString fullPath = fn.GetFullPath();
1646 if( wxFileName::DirExists( fullPath ) )
1648 else if( fn.FileExists() )
1649 total += (size_t) fn.GetSize().GetValue();
1650 cont = dir.GetNext( &
name );
1657 std::vector<wxString> packs;
1658 wxDir packDir( aPackDir );
1660 if( !packDir.IsOpened() )
1664 bool cont = packDir.GetFirst( &
name, wxEmptyString, wxDIR_FILES );
1668 if(
name.EndsWith( wxS(
".pack" ) ) ||
name.EndsWith( wxS(
".idx" ) ) )
1669 packs.push_back( aPackDir + wxFileName::GetPathSeparator() +
name );
1671 cont = packDir.GetNext( &
name );
1674 std::sort( packs.begin(), packs.end() );
1680 const std::atomic<bool>* aCancel =
nullptr )
1682 struct PROGRESS_STATE
1685 const std::atomic<bool>*
cancel;
1686 } state{ aReporter, aCancel };
1690 if( aReporter || aCancel )
1692 git_packbuilder_set_callbacks(
1694 [](
int aStage, uint32_t aCurrent, uint32_t aTotal,
void* aPayload )
1696 auto* progress =
static_cast<PROGRESS_STATE*
>( aPayload );
1698 if( progress->reporter )
1701 progress->reporter->SetCurrentProgress( (
double) aCurrent / aTotal );
1703 progress->reporter->KeepRefreshing();
1706 return progress->cancel && progress->cancel->load() ? -1 : 0;
1711 std::string packDir = aPackDir.utf8_string();
1713 return git_packbuilder_write( aPb, aPackDir.IsEmpty() ?
nullptr : packDir.c_str(), 0,
nullptr,
nullptr ) == 0;
1724static void pruneLooseObjects(
const wxString& aObjectsPath,
const wxString& aPackIndex, time_t aWalkStart )
1726 git_odb* packOdb =
nullptr;
1727 git_odb_backend* backend =
nullptr;
1729 if( git_odb_new( &packOdb ) != 0 )
1732 if( git_odb_backend_one_pack( &backend, aPackIndex.utf8_string().c_str() ) != 0 )
1734 git_odb_free( packOdb );
1738 if( git_odb_add_backend( packOdb, backend, 1 ) != 0 )
1740 backend->free( backend );
1741 git_odb_free( packOdb );
1745 wxLogNull suppressRmdirErrors;
1746 wxDir objDir( aObjectsPath );
1748 bool contDir = objDir.IsOpened() && objDir.GetFirst( &fanout, wxEmptyString, wxDIR_DIRS );
1752 wxString fanoutPath = aObjectsPath + wxFileName::GetPathSeparator() + fanout;
1753 wxDir looseDir( fanoutPath );
1755 bool contFile = fanout.length() == 2 && looseDir.IsOpened()
1756 && looseDir.GetFirst( &rest, wxEmptyString, wxDIR_FILES );
1761 wxString loosePath = fanoutPath + wxFileName::GetPathSeparator() + rest;
1763 if( git_oid_fromstr( &oid, ( fanout + rest ).utf8_string().c_str() ) == 0
1764 && ( git_odb_exists( packOdb, &oid )
1767 wxRemoveFile( loosePath );
1770 contFile = looseDir.GetNext( &rest );
1773 if( fanout.length() == 2 && !wxDir( fanoutPath ).HasFiles() )
1774 wxRmdir( fanoutPath );
1776 contDir = objDir.GetNext( &fanout );
1779 git_odb_free( packOdb );
1786 const std::atomic<bool>* aCancel )
1788 git_packbuilder* pb =
nullptr;
1789 git_revwalk* walk =
nullptr;
1791 if( git_packbuilder_new( &pb, aRepo ) != 0 )
1792 return wxEmptyString;
1794 if( git_revwalk_new( &walk, aRepo ) != 0 )
1796 git_packbuilder_free( pb );
1797 return wxEmptyString;
1801 bool ok = git_revwalk_push_glob( walk,
"refs/*" ) == 0 && git_revwalk_push_head( walk ) == 0;
1805 while( ok && ( rc = git_revwalk_next( &oid, walk ) ) == 0 )
1806 ok = git_packbuilder_insert_commit( pb, &oid ) == 0;
1808 git_revwalk_free( walk );
1813 if( ok && rc == GIT_ITEROVER &&
writePack( pb, aPackDir, aReporter, aCancel ) )
1815#if ( LIBGIT2_VER_MAJOR > 1 ) || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 4 )
1816 const char* newPackName = git_packbuilder_name( pb );
1818 char hex[GIT_OID_HEXSZ + 1];
1819 hex[GIT_OID_HEXSZ] =
'\0';
1820 git_oid_fmt( hex, git_packbuilder_hash( pb ) );
1822 const char* newPackName = strlen( hex ) > 0 ? hex :
nullptr;
1826 stem = wxS(
"pack-" ) + wxString::FromUTF8( newPackName );
1829 git_packbuilder_free( pb );
1835static std::vector<wxString>
supersededBy(
const std::vector<wxString>& aPriorPacks,
const wxString& aNewStem )
1837 std::vector<wxString> superseded;
1839 for(
const wxString& pack : aPriorPacks )
1841 if( wxFileName( pack ).GetName() != aNewStem )
1842 superseded.push_back( pack );
1852 std::vector<wxString>* aSupersededPacks )
1854 wxString sep = wxFileName::GetPathSeparator();
1855 wxString objPath = wxString::FromUTF8( git_repository_path( aRepo ) ) + wxS(
"objects" );
1856 wxString packDir = objPath + sep + wxS(
"pack" );
1858 std::vector<wxString> priorPacks =
listPackFiles( packDir );
1859 time_t walkStart = wxDateTime::Now().GetTicks();
1860 wxString stem =
buildPack( aRepo, wxEmptyString, aReporter,
nullptr );
1862 if( stem.IsEmpty() )
1880 if( aMaxBytes == 0 )
1883 if( !wxDirExists( aHistoryPath ) )
1888 if( current <= aMaxBytes )
1895 wxLogTrace(
traceAutoSave, wxS(
"[history] EnforceSizeLimit: Failed to acquire lock for %s" ), aProjectPath );
1907 if( current <= aMaxBytes )
1911 aReporter->
Report(
_(
"Compacting local history..." ) );
1914 std::vector<wxString> supersededPacks;
1920 for(
const wxString& pack : supersededPacks )
1922 if( !wxRemoveFile( pack ) )
1923 wxLogTrace(
traceAutoSave, wxS(
"[history] could not remove %s" ), pack );
1929 const size_t target = aMaxBytes / 4 * 3;
1931 if( current <= target )
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;
1947 while( git_revwalk_next( &oid, walk ) == 0 )
1948 commits.push_back( oid );
1950 git_revwalk_free( walk );
1952 if( commits.empty() )
1956 std::set<git_oid, bool ( * )(
const git_oid&,
const git_oid& )> seenBlobs(
1957 [](
const git_oid& a,
const git_oid& b )
1959 return memcmp( &a, &b,
sizeof( git_oid ) ) < 0;
1963 wxString gitDir = wxString::FromUTF8( git_repository_path( repo ) );
1965 size_t copyBytes = current > gitBytes ? current - gitBytes : 0;
1968 size_t keptBytes = 0;
1969 std::vector<git_oid> keep;
1971 git_odb* odb =
nullptr;
1972 git_repository_odb( &odb, repo );
1974 std::function<size_t( git_tree* )> accountTree =
1975 [&]( git_tree* tree )
1978 size_t cnt = git_tree_entrycount( tree );
1980 for(
size_t i = 0; i < cnt; ++i )
1982 const git_tree_entry* entry = git_tree_entry_byindex( tree, i );
1984 if( git_tree_entry_type( entry ) == GIT_OBJECT_BLOB )
1986 const git_oid* bid = git_tree_entry_id( entry );
1988 if( seenBlobs.find( *bid ) == seenBlobs.end() )
1991 git_object_t type = GIT_OBJECT_ANY;
1993 if( odb && git_odb_read_header( &len, &type, odb, bid ) == 0 )
1996 seenBlobs.insert( *bid );
1999 else if( git_tree_entry_type( entry ) == GIT_OBJECT_TREE )
2001 git_tree* sub =
nullptr;
2003 if( git_tree_lookup( &sub, repo, git_tree_entry_id( entry ) ) == 0 )
2005 added += accountTree( sub );
2006 git_tree_free( sub );
2014 for(
const git_oid& cOid : commits )
2016 git_commit* c =
nullptr;
2018 if( git_commit_lookup( &c, repo, &cOid ) != 0 )
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 );
2027 if( keep.empty() || keptBytes + add <= budget )
2029 keep.push_back( cOid );
2037 keep.push_back( commits.front() );
2040 git_odb_free( odb );
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 )
2048 return memcmp( &a, &b,
sizeof( git_oid ) ) < 0;
2050 git_strarray tagList;
2052 if( git_tag_list( &tagList, repo ) == 0 )
2054 for(
size_t i = 0; i < tagList.count; ++i )
2056 wxString
name = wxString::FromUTF8( tagList.strings[i] );
2057 if(
name.StartsWith( wxS(
"Save_") ) ||
name.StartsWith( wxS(
"Last_Save_") ) )
2059 git_reference* tref =
nullptr;
2061 if( git_reference_lookup( &tref, repo, ( wxS(
"refs/tags/" ) +
name ).mb_str().data() ) == 0 )
2063 const git_oid* toid = git_reference_target( tref );
2067 tagTargets.emplace_back(
name, *toid );
2068 taggedCommits.insert( *toid );
2072 for(
const auto& k : keep )
2074 if( memcmp( &k, toid,
sizeof( git_oid ) ) == 0 )
2084 keep.push_back( *toid );
2085 wxLogTrace(
traceAutoSave, wxS(
"[history] EnforceSizeLimit: Preserving tagged commit %s" ),
2090 git_reference_free( tref );
2094 git_strarray_free( &tagList );
2098 wxFileName trimFn( aHistoryPath + wxS(
"_trim"), wxEmptyString );
2099 wxString trimPath = trimFn.GetPath();
2101 if( wxDirExists( trimPath ) )
2102 wxFileName::Rmdir( trimPath, wxPATH_RMDIR_RECURSIVE );
2104 wxMkdir( trimPath );
2107 if( git_repository_init( &newRepo, trimPath.mb_str().data(), 0 ) != 0 )
2110 wxString newPackDir = wxString::FromUTF8( git_repository_path( newRepo ) ) + wxS(
"objects" )
2111 + wxFileName::GetPathSeparator() + wxS(
"pack" );
2112 git_repository_free( newRepo );
2117 git_packbuilder* pb =
nullptr;
2119 if( git_packbuilder_new( &pb, repo ) != 0 )
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;
2131 aReporter->
AdvancePhase(
_(
"Trimming local history..." ) );
2135 for(
size_t idx = 0; idx < keep.size() && rewriteOk; ++idx )
2143 const git_oid& co = keep[idx];
2144 git_commit* orig =
nullptr;
2146 if( git_commit_lookup( &orig, repo, &co ) != 0 )
2149 git_tree* tree =
nullptr;
2151 if( git_commit_tree( &tree, orig ) != 0 )
2153 git_commit_free( orig );
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;
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 );
2168 const git_commit* parents[1];
2169 int parentCount = 0;
2173 parents[0] = parent;
2177 git_oid newCommitOid;
2179 if( git_commit_create( &newCommitOid, repo,
nullptr, sigAuthor, sigCommitter,
nullptr,
2180 git_commit_message( orig ), tree, parentCount, parentCount ? parents :
nullptr )
2188 git_commit_free( parent );
2191 git_commit_lookup( &parent, repo, &newCommitOid );
2192 commitMap.emplace_back( co, newCommitOid );
2195 git_signature_free( sigAuthor );
2196 git_signature_free( sigCommitter );
2197 git_tree_free( tree );
2198 git_commit_free( orig );
2202 git_commit_free( parent );
2205 for(
auto it = commitMap.rbegin(); it != commitMap.rend() && rewriteOk; ++it )
2207 if( git_packbuilder_insert_commit( pb, &it->neu ) != 0 )
2211 if( !rewriteOk || commitMap.empty() )
2213 git_packbuilder_free( pb );
2218 aReporter->
AdvancePhase(
_(
"Compacting trimmed history..." ) );
2220 bool packed =
writePack( pb, newPackDir, aReporter );
2221 git_packbuilder_free( pb );
2223 if( !packed || git_repository_open( &newRepo, trimPath.mb_str().data() ) != 0 )
2226 const git_oid& newHeadOid = commitMap.back().neu;
2227 git_reference* headRef =
nullptr;
2228 bool headOk =
false;
2230 if( git_reference_lookup( &headRef, newRepo,
"HEAD" ) == 0 )
2232 const char* branch = git_reference_symbolic_target( headRef );
2233 git_reference* branchRef =
nullptr;
2235 if( branch && git_reference_create( &branchRef, newRepo, branch, &newHeadOid, 1,
nullptr ) == 0 )
2238 git_reference_free( branchRef );
2241 git_reference_free( headRef );
2246 git_repository_free( newRepo );
2250 git_commit* newHead =
nullptr;
2252 if( git_commit_lookup( &newHead, newRepo, &newHeadOid ) == 0 )
2254 git_tree* newHeadTree =
nullptr;
2255 git_index* newIndex =
nullptr;
2257 if( git_commit_tree( &newHeadTree, newHead ) == 0 && git_repository_index( &newIndex, newRepo ) == 0 )
2259 git_index_read_tree( newIndex, newHeadTree );
2260 git_index_write( newIndex );
2264 git_index_free( newIndex );
2267 git_tree_free( newHeadTree );
2269 git_commit_free( newHead );
2273 for(
const auto& tt : tagTargets )
2276 const git_oid* newOid =
nullptr;
2278 for(
const auto& m : commitMap )
2280 if( memcmp( &m.orig, &tt.second,
sizeof( git_oid ) ) == 0 )
2290 git_object* obj =
nullptr;
2292 if( git_object_lookup( &obj, newRepo, newOid, GIT_OBJECT_COMMIT ) == 0 )
2294 git_oid tag_oid; git_tag_create_lightweight( &tag_oid, newRepo, tt.first.mb_str().data(), obj, 0 );
2295 git_object_free( obj );
2300 git_repository_free( newRepo );
2303 for(
const wxString&
name : { wxString( wxS(
".gitignore" ) ), wxString( wxS(
"README.txt" ) ) } )
2305 wxFileName src( aHistoryPath,
name );
2307 if( src.FileExists() && !wxCopyFile( src.GetFullPath(), wxFileName( trimPath,
name ).GetFullPath(),
true ) )
2314 wxString backupOld = aHistoryPath + wxS(
"_old_" ) +
KIID().
AsString();
2316 if( wxFileExists( backupOld ) || wxDirExists( backupOld ) )
2319 if( !wxRenameFile( aHistoryPath, backupOld,
false ) )
2322 if( !wxRenameFile( trimPath, aHistoryPath,
false ) )
2324 if( !wxRenameFile( backupOld, aHistoryPath,
false ) )
2325 wxLogError(
_(
"Could not restore local history '%s'. The previous history is preserved at '%s'." ),
2326 aHistoryPath, backupOld );
2331 if( !wxFileName::Rmdir( backupOld, wxPATH_RMDIR_RECURSIVE ) )
2332 wxLogTrace(
traceAutoSave, wxS(
"[history] Trimmed history installed; previous history retained at %s" ),
2345 wxDir gitDir( aGitDir );
2347 std::vector<wxString> stale;
2348 bool cont = gitDir.IsOpened()
2354 if( wxFileModificationTime( aGitDir +
name ) < expiry )
2355 stale.push_back( aGitDir +
name );
2357 cont = gitDir.GetNext( &
name );
2360 for(
const wxString& dir : stale )
2361 wxFileName::Rmdir( dir, wxPATH_RMDIR_RECURSIVE );
2368 std::vector<std::string> targets;
2369 git_reference_iterator* iter =
nullptr;
2370 git_reference* ref =
nullptr;
2373 if( git_reference_name_to_id( &oid, aRepo,
"HEAD" ) == 0 )
2374 targets.push_back( std::string(
"HEAD " ) + git_oid_tostr_s( &oid ) );
2376 if( git_reference_iterator_new( &iter, aRepo ) != 0 )
2379 while( git_reference_next( &ref, iter ) == 0 )
2381 git_reference* resolved =
nullptr;
2383 if( git_reference_resolve( &resolved, ref ) == 0 )
2385 targets.push_back( std::string( git_reference_name( ref ) ) +
" "
2386 + git_oid_tostr_s( git_reference_target( resolved ) ) );
2387 git_reference_free( resolved );
2390 git_reference_free( ref );
2393 git_reference_iterator_free( iter );
2394 std::sort( targets.begin(), targets.end() );
2402 wxDir objDir( aObjectsPath );
2404 bool cont = objDir.IsOpened() && objDir.GetFirst( &fanout, wxEmptyString, wxDIR_DIRS );
2408 if( fanout.length() == 2 )
2409 total +=
dirSizeRecursive( aObjectsPath + wxFileName::GetPathSeparator() + fanout );
2411 cont = objDir.GetNext( &fanout );
2428 [
this, projectPath = aProjectPath, hist =
historyPath( aProjectPath ), aLooseLimit]()
2432 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
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() );
2443 git_repository_free( repo );
2449 std::vector<wxString> priorPacks =
listPackFiles( packDir );
2450 std::vector<std::string> priorRefs =
refTargets( repo );
2451 time_t walkStart = wxDateTime::Now().GetTicks();
2453 wxFileName::Rmdir( stageDir, wxPATH_RMDIR_RECURSIVE );
2454 wxMkdir( stageDir );
2457 git_repository_free( repo );
2470 wxString staged = stageDir + sep + stem;
2471 wxString target = packDir + sep + stem;
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 ) );
2486 for(
const wxString& pack :
supersededBy( priorPacks, stem ) )
2488 if( !wxRemoveFile( pack ) )
2489 wxLogTrace(
traceAutoSave, wxS(
"[history] could not remove %s" ), pack );
2494 wxLogTrace(
traceAutoSave, wxS(
"[history] could not install %s" ), target );
2498 wxFileName::Rmdir( stageDir, wxPATH_RMDIR_RECURSIVE );
2507 [
this, previous = std::move(
m_compactFuture ), projectPath = aProjectPath,
2508 hist =
historyPath( aProjectPath ), aMaxBytes]()
mutable
2510 if( previous.valid() )
2523 &&
m_compactFuture.wait_for( std::chrono::seconds( 0 ) ) != std::future_status::ready;
2532 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
2533 return wxEmptyString;
2536 if( git_reference_name_to_id( &head_oid, repo,
"HEAD" ) != 0 )
2538 git_repository_free( repo );
2539 return wxEmptyString;
2542 wxString hash = wxString::FromUTF8( git_oid_tostr_s( &head_oid ) );
2543 git_repository_free( repo );
2555bool checkForLockedFiles(
const wxString& aProjectPath, std::vector<wxString>& aLockedFiles )
2560 if( !guard.IsRooted() )
2563 std::function<void(
const wxString& )> findLocks =
2564 [&](
const wxString& dirPath )
2566 wxDir dir( dirPath );
2567 if( !dir.IsOpened() )
2571 bool cont = dir.GetFirst( &filename );
2575 wxFileName fullPath( dirPath, filename );
2578 if( filename == wxS(
".history") || filename == wxS(
".git") )
2580 cont = dir.GetNext( &filename );
2584 if( fullPath.DirExists() )
2586 if( guard.ShouldDescend( fullPath.GetFullPath() ) )
2587 findLocks( fullPath.GetFullPath() );
2589 else if( fullPath.FileExists()
2596 baseName = baseName.BeforeLast(
'.' );
2597 wxFileName originalFile( dirPath, baseName );
2604 aLockedFiles.push_back( fullPath.GetFullPath() );
2608 cont = dir.GetNext( &filename );
2612 findLocks( aProjectPath );
2613 return aLockedFiles.empty();
2620bool extractCommitToTemp(
git_repository* aRepo, git_tree* aTree,
const wxString& aTempPath )
2622 bool extractSuccess =
true;
2624 std::function<void( git_tree*,
const wxString& )> extractTree =
2625 [&]( git_tree* t,
const wxString& prefix )
2627 if( !extractSuccess )
2630 size_t cnt = git_tree_entrycount( t );
2631 for(
size_t i = 0; i < cnt; ++i )
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;
2637 if( git_tree_entry_type( entry ) == GIT_OBJECT_TREE )
2639 wxFileName dirPath( aTempPath + wxFileName::GetPathSeparator() + fullPath, wxEmptyString );
2641 if( !wxFileName::Mkdir( dirPath.GetPath(), 0777, wxPATH_MKDIR_FULL ) )
2644 wxS(
"[history] extractCommitToTemp: Failed to create directory '%s'" ),
2645 dirPath.GetPath() );
2646 extractSuccess =
false;
2650 git_tree* sub =
nullptr;
2652 if( git_tree_lookup( &sub, aRepo, git_tree_entry_id( entry ) ) == 0 )
2654 extractTree( sub, fullPath );
2655 git_tree_free( sub );
2658 else if( git_tree_entry_type( entry ) == GIT_OBJECT_BLOB )
2660 git_blob* blob =
nullptr;
2662 if( git_blob_lookup( &blob, aRepo, git_tree_entry_id( entry ) ) == 0 )
2664 wxFileName dst( aTempPath + wxFileName::GetPathSeparator() + fullPath );
2666 wxFileName dstDir( dst );
2667 dstDir.SetFullName( wxEmptyString );
2668 wxFileName::Mkdir( dstDir.GetPath(), 0777, wxPATH_MKDIR_FULL );
2670 wxFFile f( dst.GetFullPath(), wxT(
"wb" ) );
2674 f.Write( git_blob_rawcontent( blob ), git_blob_rawsize( blob ) );
2680 wxS(
"[history] extractCommitToTemp: Failed to write '%s'" ),
2681 dst.GetFullPath() );
2682 extractSuccess =
false;
2683 git_blob_free( blob );
2687 git_blob_free( blob );
2693 extractTree( aTree, wxEmptyString );
2694 return extractSuccess;
2704void collectRelativeFiles(
const wxString& aRoot,
const wxString& aDir, std::vector<wxString>& aOut )
2708 if( !dir.IsOpened() )
2713 for(
bool cont = dir.GetFirst( &
name ); cont; cont = dir.GetNext( &
name ) )
2715 wxString full = aDir + wxFILE_SEP_PATH +
name;
2717 if( wxDirExists( full ) )
2719 collectRelativeFiles( aRoot, full, aOut );
2721 else if( wxFileExists( full ) )
2723 wxString rel = full.Mid( aRoot.length() + 1 );
2724 rel.Replace( wxS(
"\\" ), wxS(
"/" ) );
2725 aOut.push_back( rel );
2739bool overlaySnapshotFiles(
const wxString& aTempRestorePath,
const wxString& aProjectPath,
const wxString& aBackupPath )
2741 std::vector<wxString> relPaths;
2742 collectRelativeFiles( aTempRestorePath, aTempRestorePath, relPaths );
2744 for(
const wxString& rel : relPaths )
2746 wxFileName src( aTempRestorePath + wxFILE_SEP_PATH + rel );
2747 wxFileName dst( aProjectPath + wxFILE_SEP_PATH + rel );
2749 if( dst.FileExists() )
2751 wxFileName bak( aBackupPath + wxFILE_SEP_PATH + rel );
2753 if( !wxFileName::Mkdir( bak.GetPath(), 0777, wxPATH_MKDIR_FULL )
2754 || !wxCopyFile( dst.GetFullPath(), bak.GetFullPath(),
true ) )
2760 if( !wxFileName::Mkdir( dst.GetPath(), 0777, wxPATH_MKDIR_FULL )
2761 || !wxCopyFile( src.GetFullPath(), dst.GetFullPath(),
true ) )
2778 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: Checking for open files in %s" ),
2781 std::vector<wxString> lockedFiles;
2782 if( !checkForLockedFiles( aProjectPath, lockedFiles ) )
2785 for(
const auto& f : lockedFiles )
2786 lockList += wxS(
"\n - ") + f;
2789 wxS(
"[history] RestoreCommit: Cannot restore - files are open:%s" ),
2795 wxString msg =
_(
"Cannot restore - the following files are open by another user:" );
2797 wxMessageBox( msg,
_(
"Restore Failed" ), wxOK | wxICON_WARNING, aParent );
2808 wxS(
"[history] RestoreCommit: Failed to acquire lock for %s" ),
2819 if( git_oid_fromstr( &oid, aHash.mb_str().data() ) != 0 )
2821 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: Invalid hash %s" ), aHash );
2825 git_commit* commit =
nullptr;
2826 if( git_commit_lookup( &commit, repo, &oid ) != 0 )
2828 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: Commit not found %s" ), aHash );
2832 git_tree* tree =
nullptr;
2833 git_commit_tree( &tree, commit );
2837 if( aConfirm && aParent )
2839 wxDateTime when( (time_t) git_commit_time( commit ) );
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 );
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 "
2851 if( dlg.ShowModal() != wxID_YES )
2853 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: User cancelled at confirm" ) );
2854 git_tree_free( tree );
2855 git_commit_free( commit );
2861 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: Creating pre-restore backup" ) );
2863 std::vector<wxString> backupFiles;
2866 if( !backupFiles.empty() )
2870 backupFiles, wxS(
"Pre-restore backup" ) );
2875 wxS(
"[history] RestoreCommit: Failed to create pre-restore backup" ) );
2876 git_tree_free( tree );
2877 git_commit_free( commit );
2883 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: Current state already matches HEAD; "
2884 "continuing without a new backup commit" ) );
2889 wxString tempRestorePath = aProjectPath + wxS(
"_restore_temp");
2891 if( wxDirExists( tempRestorePath ) )
2892 wxFileName::Rmdir( tempRestorePath, wxPATH_RMDIR_RECURSIVE );
2894 if( !wxFileName::Mkdir( tempRestorePath, 0777, wxPATH_MKDIR_FULL ) )
2897 wxS(
"[history] RestoreCommit: Failed to create temp directory %s" ),
2899 git_tree_free( tree );
2900 git_commit_free( commit );
2904 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: Extracting to temp location %s" ),
2907 if( !extractCommitToTemp( repo, tree, tempRestorePath ) )
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 );
2921 wxString backupPath =
2922 aProjectPath + wxS(
"_restore_backup_" )
2923 + wxDateTime::UNow().Format( wxS(
"%Y-%m-%dT%H-%M-%S-%l" ) );
2925 if( !overlaySnapshotFiles( tempRestorePath, aProjectPath, backupPath ) )
2927 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: Overlay failed, rolling back from backup" ) );
2930 if( wxDirExists( backupPath ) )
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 );
2938 wxFileName::Rmdir( tempRestorePath, wxPATH_RMDIR_RECURSIVE );
2939 git_tree_free( tree );
2940 git_commit_free( commit );
2946 wxS(
"[history] RestoreCommit: Restore successful, backup retained at %s" ),
2948 wxFileName::Rmdir( tempRestorePath, wxPATH_RMDIR_RECURSIVE );
2951 std::vector<wxString> resultFiles;
2954 wxString::Format( wxS(
"Restored from %s" ), aHash ) );
2959 git_tree_free( tree );
2960 git_commit_free( commit );
2962 wxLogTrace(
traceAutoSave, wxS(
"[history] RestoreCommit: Complete" ) );
2971 std::vector<LOCAL_HISTORY_SNAPSHOT_INFO> snapshots =
LoadSnapshots( aProjectPath );
2973 if( snapshots.empty() )
2982 if( !selectedHash.IsEmpty() )
2989 std::vector<LOCAL_HISTORY_SNAPSHOT_INFO> snapshots;
2994 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
2997 git_revwalk* walk =
nullptr;
2998 if( git_revwalk_new( &walk, repo ) != 0 )
3000 git_repository_free( repo );
3004 git_revwalk_sorting( walk, GIT_SORT_TIME );
3005 git_revwalk_push_head( walk );
3009 while( git_revwalk_next( &oid, walk ) == 0 )
3011 git_commit* commit =
nullptr;
3013 if( git_commit_lookup( &commit, repo, &oid ) != 0 )
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 ) );
3021 wxString firstLine =
info.message.BeforeFirst(
'\n' );
3023 long parsedCount = 0;
3025 firstLine.BeforeFirst(
':', &remainder );
3026 remainder.Trim(
true ).Trim(
false );
3028 if( remainder.EndsWith( wxS(
"files changed" ) ) )
3030 wxString countText = remainder.BeforeFirst(
' ' );
3032 if( countText.ToLong( &parsedCount ) )
3033 info.filesChanged =
static_cast<int>( parsedCount );
3036 info.summary = firstLine.BeforeFirst(
':' );
3039 info.message.BeforeFirst(
'\n', &rest );
3040 wxArrayString lines = wxSplit( rest,
'\n',
'\0' );
3042 for(
const wxString& line : lines )
3044 if( !line.IsEmpty() )
3045 info.changedFiles.Add( line );
3048 snapshots.push_back( std::move(
info ) );
3049 git_commit_free( commit );
3052 git_revwalk_free( walk );
3053 git_repository_free( repo );
3065 const wxString& aExtension )
3070 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
3071 return wxEmptyString;
3074 git_commit* commit =
nullptr;
3075 git_tree* tree =
nullptr;
3077 if( git_oid_fromstr( &oid, aHash.mb_str().data() ) != 0 || git_commit_lookup( &commit, repo, &oid ) != 0 )
3079 git_repository_free( repo );
3080 return wxEmptyString;
3083 if( git_commit_tree( &tree, commit ) != 0 )
3085 git_commit_free( commit );
3086 git_repository_free( repo );
3087 return wxEmptyString;
3093 std::vector<wxString> entries;
3094 } ctx{ aExtension, {} };
3096 auto collect = [](
const char* aRoot,
const git_tree_entry* aEntry,
void* aPayload ) ->
int
3098 WALK_CTX* c =
static_cast<WALK_CTX*
>( aPayload );
3100 if( git_tree_entry_type( aEntry ) != GIT_OBJECT_BLOB )
3103 wxString
name = wxString::FromUTF8( git_tree_entry_name( aEntry ) );
3105 if( !
name.EndsWith( c->ext ) )
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 ) ) ) );
3114 git_tree_walk( tree, GIT_TREEWALK_PRE, collect, &ctx );
3116 git_tree_free( tree );
3117 git_commit_free( commit );
3118 git_repository_free( repo );
3120 std::sort( ctx.entries.begin(), ctx.entries.end() );
3122 wxString fingerprint;
3124 for(
const wxString& entry : ctx.entries )
3125 fingerprint << entry << wxS(
"|" );
3132 const wxString& aDestDir,
const std::vector<wxString>& aExtensions )
3137 if( git_repository_open( &repo, hist.mb_str().data() ) != 0 )
3141 git_commit* commit =
nullptr;
3142 git_tree* tree =
nullptr;
3144 if( git_oid_fromstr( &oid, aHash.mb_str().data() ) != 0 || git_commit_lookup( &commit, repo, &oid ) != 0 )
3146 git_repository_free( repo );
3150 if( git_commit_tree( &tree, commit ) != 0 )
3152 git_commit_free( commit );
3153 git_repository_free( repo );
3163 } ctx{ repo, aDestDir, &aExtensions,
true };
3166 auto writeEntry = [](
const char* aRoot,
const git_tree_entry* aEntry,
void* aPayload ) ->
int
3168 WALK_CTX* c =
static_cast<WALK_CTX*
>( aPayload );
3170 if( git_tree_entry_type( aEntry ) != GIT_OBJECT_BLOB )
3173 wxString
name = wxString::FromUTF8( git_tree_entry_name( aEntry ) );
3175 if( !c->extensions->empty() )
3179 for(
const wxString& ext : *c->extensions )
3181 if(
name.EndsWith( ext ) )
3192 wxString rel = wxString::FromUTF8( aRoot ) +
name;
3193 wxFileName outFn( c->destDir + wxS(
"/" ) + rel );
3195 if( !wxFileName::Mkdir( outFn.GetPath(), wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
3201 git_blob* blob =
nullptr;
3203 if( git_blob_lookup( &blob, c->repo, git_tree_entry_id( aEntry ) ) == 0 )
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" ) );
3209 if( !( data && out.IsOpened() && out.Write( data, size ) == size ) )
3212 git_blob_free( blob );
3222 git_tree_walk( tree, GIT_TREEWALK_PRE, writeEntry, &ctx );
3224 git_tree_free( tree );
3225 git_commit_free( commit );
3226 git_repository_free( repo );
bool AutosaveUsesLocalHistory() const
The backup format is the single switch that selects the autosave mechanism: the incremental format re...
wxString GetSelectedHash() const
bool ShouldDescend(const wxString &aDir)
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.
wxString AsString() const
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...
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...
static bool EnsurePathExists(const wxString &aPath, bool aPathToFile=false)
Attempts to create a given path if it does not exist.
virtual COMMON_SETTINGS * GetCommonSettings() const
virtual SETTINGS_MANAGER & GetSettingsManager() const
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.
std::weak_ptr< void > GetHistoryLifetimeToken() const
Liveness token handed to LOCAL_HISTORY::RegisterSaver so a shared autosave timer skips this project's...
void SaveToHistory(const wxString &aProjectPath, std::vector< HISTORY_FILE_DATA > &aFileData)
Produce HISTORY_FILE_DATA entries for project files (.kicad_pro and .kicad_prl).
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.
@ PROJECT_DIR
Inside the project directory (default)
This file is part of the common library.
#define KICAD_MESSAGE_DIALOG
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)
PGM_BASE & Pgm()
The global program "get" accessor.
static const std::vector< std::string > extensions
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
std::weak_ptr< void > lifetime
IbisParser parser & reporter
wxString result
Test unit parsing edge cases and error handling.
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
wxLogTrace helper definitions.
Definition of file extensions used in Kicad.