26#include <wx/filename.h>
44 wxString* aTrustCommand )
62 return backend->
CreateBranch( aRepo, aBranchName, wxEmptyString );
67 bool aRemoveGitDir, wxString* aErrors )
74 return backend->
RemoveVCS( aRepo, aProjectPath, aRemoveGitDir, aErrors );
84 const auto read = [&]() -> ENVIRONMENT::VCS_VALUE
88 if( git_reference_name_to_id( &oid, aRepo,
"HEAD" ) != 0 )
91 char hash[GIT_OID_HEXSZ + 1];
92 git_oid_tostr( hash,
sizeof( hash ), &oid );
95 auto* environment = ENVIRONMENT::Current();
96 const char*
path = git_repository_path( aRepo );
97 const auto value = environment &&
path
98 ? environment->VcsValue( { ENVIRONMENT::VCS_QUERY::HEAD, wxString::FromUTF8(
path ),
"", 0,
false }, read )
102 if( value.text.empty() || git_oid_fromstr( &oid, value.text.c_str() ) != 0 )
111 const auto read = [&]
116 if( git_oid_is_zero( &oid ) )
117 return wxString(
"no hash" );
119 char hash[GIT_OID_HEXSZ + 1];
120 git_oid_tostr( hash,
sizeof( hash ), &oid );
121 return wxString::FromUTF8( hash );
124 const wxString hash = environment ? environment->GitHash( aProjectFile, read ) : read();
125 return aShort ? hash.Left( 8 ) : hash;
137 char resolved[PATH_MAX];
139 if( aPath.IsEmpty() || realpath( aPath.mb_str(), resolved ) ==
nullptr )
142 wxString out = wxString::FromUTF8( resolved );
144 if( !out.EndsWith( wxFileName::GetPathSeparator() ) && wxFileName::DirExists( out ) )
145 out += wxFileName::GetPathSeparator();
153 const wxString& aCanonicalWorkDir )
156 return aCanonicalWorkDir;
158 if( aUserProjectPath.IsEmpty() || aCanonicalWorkDir.IsEmpty() )
159 return aCanonicalWorkDir;
161 char resolvedPath[PATH_MAX];
163 if( realpath( aUserProjectPath.mb_str(), resolvedPath ) ==
nullptr )
164 return aCanonicalWorkDir;
166 wxString canonicalUserPath = wxString::FromUTF8( resolvedPath );
168 if( !canonicalUserPath.EndsWith( wxFileName::GetPathSeparator() ) )
169 canonicalUserPath += wxFileName::GetPathSeparator();
171 wxString canonicalWorkDirNorm = aCanonicalWorkDir;
173 if( !canonicalWorkDirNorm.EndsWith( wxFileName::GetPathSeparator() ) )
174 canonicalWorkDirNorm += wxFileName::GetPathSeparator();
180 if( canonicalUserPath == canonicalWorkDirNorm )
182 return aUserProjectPath.EndsWith( wxFileName::GetPathSeparator() )
184 : aUserProjectPath + wxFileName::GetPathSeparator();
191 userFn.AssignDir( aUserProjectPath );
193 wxFileName canonicalUserFn;
194 canonicalUserFn.AssignDir( canonicalUserPath );
196 wxFileName canonicalWorkDirFn;
197 canonicalWorkDirFn.AssignDir( canonicalWorkDirNorm );
199 while( canonicalUserFn.GetFullPath() != canonicalWorkDirFn.GetFullPath() )
201 if( canonicalUserFn.GetDirCount() == 0 || userFn.GetDirCount() == 0 )
202 return aCanonicalWorkDir;
204 canonicalUserFn.RemoveLastDir();
205 userFn.RemoveLastDir();
211 if(
canonicalDir( userFn.GetPathWithSep() ) != canonicalWorkDirNorm )
212 return aCanonicalWorkDir;
214 return userFn.GetPathWithSep();
219static bool pathIsUnder(
const wxString& aAbsPath,
const wxString& aProjectPath )
221 wxString absPath = aAbsPath;
222 wxString projectPath = aProjectPath;
225 absPath.Replace( wxT(
"\\" ), wxT(
"/" ) );
226 projectPath.Replace( wxT(
"\\" ), wxT(
"/" ) );
229 if( !projectPath.EndsWith( wxT(
"/" ) ) )
230 projectPath += wxT(
"/" );
233 return absPath.Lower().StartsWith( projectPath.Lower() );
235 return absPath.StartsWith( projectPath );
242 if( aProjectPath.IsEmpty() )
254static std::optional<wxString>
prefixUnder(
const wxString& aWorkDir,
const wxString& aProjectPath )
256 wxString workDir = aWorkDir;
257 wxString projectPath = aProjectPath;
259 workDir.Replace( wxS(
"\\" ), wxS(
"/" ) );
260 projectPath.Replace( wxS(
"\\" ), wxS(
"/" ) );
262 if( !workDir.EndsWith( wxS(
"/" ) ) )
263 workDir += wxS(
"/" );
265 if( !projectPath.EndsWith( wxS(
"/" ) ) )
266 projectPath += wxS(
"/" );
270 if( !projectPath.Lower().StartsWith( workDir.Lower() ) )
273 if( !projectPath.StartsWith( workDir ) )
277 return projectPath.Mid( workDir.length() );
283 if( aWorkDir.IsEmpty() || aProjectPath.IsEmpty() )
286 std::optional<wxString> prefix =
prefixUnder( aWorkDir, aProjectPath );
298 if( !aRepo || aPath.IsEmpty() )
301 const char* value =
nullptr;
303#if LIBGIT2_VER_MAJOR > 1 || ( LIBGIT2_VER_MAJOR == 1 && LIBGIT2_VER_MINOR >= 3 )
305 git_attr_options opts = {};
306 opts.version = GIT_ATTR_OPTIONS_VERSION;
307 opts.flags = GIT_ATTR_CHECK_INDEX_THEN_FILE;
312 opts.flags |= GIT_ATTR_CHECK_INCLUDE_COMMIT;
313 git_oid_cpy( &opts.attr_commit_id, aCommit );
316 if( git_attr_get_ext( &value, aRepo, &opts, aPath.utf8_string().c_str(),
"filter" ) != GIT_OK )
321 if( git_attr_get( &value, aRepo, GIT_ATTR_CHECK_INDEX_THEN_FILE, aPath.utf8_string().c_str(),
"filter" ) != GIT_OK )
328 return git_attr_value( value ) == GIT_ATTR_VALUE_STRING && strcmp( value,
"lfs" ) == 0;
340 const git_oid* commit =
nullptr;
344 int lfsWalkEntry(
const char* aRoot,
const git_tree_entry* aEntry,
void* aPayload )
346 LFS_WALK* walk =
static_cast<LFS_WALK*
>( aPayload );
347 std::string
path = std::string( aRoot ) + git_tree_entry_name( aEntry );
349 if( git_tree_entry_type( aEntry ) == GIT_OBJECT_TREE )
351 std::string dir =
path +
"/";
354 if( walk->prefix.compare( 0, dir.length(), dir ) != 0
355 && dir.compare( 0, walk->prefix.length(), walk->prefix ) != 0 )
363 if( git_tree_entry_type( aEntry ) != GIT_OBJECT_BLOB )
366 if(
path.compare( 0, walk->prefix.length(), walk->prefix ) != 0 )
371 walk->example = wxString::FromUTF8(
path.c_str() );
383 if( !aCommon || !aCommon->
GetRepo() )
384 return wxEmptyString;
388 return _(
"Could not work out which folder this project occupies in the repository, "
389 "so the operation was cancelled." );
395 return wxEmptyString;
397 return wxString::Format(
_(
"This project keeps '%s' in Git LFS, which KiCad cannot read or "
398 "write. Use git on the command line for this repository." ),
414 git_oid_cpy( &commitOid, aCommit );
415 else if( git_reference_name_to_id( &commitOid, repo,
"HEAD" ) != GIT_OK )
418 git_commit* commit =
nullptr;
420 if( git_commit_lookup( &commit, repo, &commitOid ) != GIT_OK )
424 git_tree* tree =
nullptr;
426 if( git_commit_tree( &tree, commit ) != GIT_OK )
430 LFS_WALK walk{ repo, prefix->utf8_string(), wxEmptyString, aCommit };
432 git_tree_walk( tree, GIT_TREEWALK_PRE, lfsWalkEntry, &walk );
435 *aExample = walk.example;
437 return !walk.example.IsEmpty();
443 static const std::vector<wxString> patterns = {
446 wxS(
"_autosave-*" ),
447 wxS(
"fp-info-cache" ),
449 wxS(
"*.[lL][cC][kK]" ),
454 wxS(
"*.[kK][iI][cC][aA][dD]_[pP][rR][lL]" ),
458 wxS(
"*.mine.[0-9]" ),
459 wxS(
"*.mine.[0-9][0-9]" ),
461 wxS(
"*.theirs.[0-9]" ),
462 wxS(
"*.theirs.[0-9][0-9]" ),
472 using PATHSPEC_PTR = std::unique_ptr<git_pathspec,
decltype( &git_pathspec_free )>;
475 PATHSPEC_PTR transientPathspec(
bool aDirectory )
477 std::vector<std::string> patterns;
481 if( pattern.EndsWith( wxS(
"/" ) ) )
486 pattern.RemoveLast();
489 patterns.push_back( pattern.utf8_string() );
492 std::vector<char*> paths;
494 for( std::string& pattern : patterns )
495 paths.push_back( pattern.data() );
497 git_strarray pathArray = { paths.data(), paths.size() };
498 git_pathspec* spec =
nullptr;
500 if( git_pathspec_new( &spec, &pathArray ) != GIT_OK )
501 return PATHSPEC_PTR(
nullptr, git_pathspec_free );
503 return PATHSPEC_PTR( spec, git_pathspec_free );
511 static const PATHSPEC_PTR filePatterns = transientPathspec(
false );
512 static const PATHSPEC_PTR directoryPatterns = transientPathspec(
true );
514 if( filePatterns && git_pathspec_matches_path( filePatterns.get(), 0, aFile.GetFullName().utf8_str() ) )
517 for(
const wxString& dir : aFile.GetDirs() )
519 if( directoryPatterns && git_pathspec_matches_path( directoryPatterns.get(), 0, dir.utf8_str() ) )
534 aCommon->SetShuttingDown(
true );
545 aCommon->SetRepo(
nullptr );
550 std::unique_lock<std::mutex> gitLock = aCommon->TryLockAction();
552 if( gitLock.owns_lock() )
554 aCommon->SetRepo(
nullptr );
555 git_repository_free( repo );
562 auto cleanup = [repo, old = std::move( aCommon )]()
mutable
564 std::unique_lock<std::mutex> g = old->LockAction();
565 old->SetRepo(
nullptr );
566 git_repository_free( repo );
581 const wxString& aDestPath )
583 if( !aRepo || aRef.IsEmpty() || aPath.IsEmpty() )
591 git_tree_entry* entry =
nullptr;
593 if( git_tree_entry_bypath( &entry, treePtr.get(), aPath.ToUTF8().data() ) != 0 )
598 if( git_tree_entry_type( entry ) != GIT_OBJECT_BLOB )
601 git_object* blobObj =
nullptr;
603 if( git_tree_entry_to_object( &blobObj, aRepo, entry ) != 0 )
607 git_blob* blob =
reinterpret_cast<git_blob*
>( blobObj );
613 if( !out.Create( aDestPath,
true, wxS_IRUSR | wxS_IWUSR ) )
616 const void* raw = git_blob_rawcontent( blob );
617 git_off_t size = git_blob_rawsize( blob );
619 return out.Write( raw,
static_cast<size_t>( size ) ) ==
static_cast<size_t>( size );
625 if( !aRepo || aRef.IsEmpty() || aDestDir.IsEmpty() )
634 if( !wxFileName::Mkdir( aDestDir, 0700, wxPATH_MKDIR_FULL ) )
637 std::string destUtf8 = aDestDir.utf8_string();
638 git_checkout_options opts;
639 git_checkout_options_init( &opts, GIT_CHECKOUT_OPTIONS_VERSION );
643 opts.checkout_strategy = GIT_CHECKOUT_FORCE | GIT_CHECKOUT_RECREATE_MISSING | GIT_CHECKOUT_DONT_UPDATE_INDEX;
644 opts.target_directory = destUtf8.c_str();
646 return git_checkout_tree( aRepo,
reinterpret_cast<git_object*
>( treePtr.get() ), &opts ) == GIT_OK;
virtual int CreateBranch(git_repository *aRepo, const wxString &aBranchName, const wxString &aFrom)=0
KIGIT_ORPHAN_REGISTRY & OrphanRegistry()
Return the process-wide orphan thread registry owned by this backend.
virtual git_repository * GetRepositoryForFile(const char *aFilename, wxString *aError, wxString *aTrustCommand)=0
aError receives why git refused to open the repository, and aTrustCommand the command that trusts it ...
virtual bool RemoveVCS(git_repository *&aRepo, const wxString &aProjectPath, bool aRemoveGitDir, wxString *aErrors)=0
static bool WriteBlobToFile(git_repository *aRepo, const wxString &aRef, const wxString &aPath, const wxString &aDestPath)
Write a file as it exists at a git ref to a path on disk, so a committed version can be diffed.
static bool PathUsesGitLfs(git_repository *aRepo, const wxString &aPath, const git_oid *aCommit=nullptr)
Whether git routes aPath through the Git LFS filter.
static git_oid GetCapturedHeadOid(git_repository *aRepo)
Return HEAD for commit-based text queries.
static wxString GetCurrentHash(const wxString &aProjectFile, bool aShort)
Return the current HEAD commit hash for the repository containing aProjectFile.
static git_repository * GetRepositoryForFile(const char *aFilename, wxString *aError=nullptr, wxString *aTrustCommand=nullptr)
Discover and open the repository that contains the given file.
static bool IsTransientGitFile(const wxFileName &aFile)
Match a project-relative path against the shared transient patterns.
static const std::vector< wxString > & TransientGitIgnorePatterns()
Shared patterns for new .gitignore files and the untracked-file filter.
static void SafeFreeRepository(std::shared_ptr< KIGIT_COMMON > aCommon, const std::string &aLabel)
Free the session's repository handle without pulling it out from under a running operation.
static wxString ComputeSymlinkPreservingWorkDir(const wxString &aUserProjectPath, const wxString &aCanonicalWorkDir)
Compute a working directory path that preserves symlinks from the user's project path.
static bool WriteTreeToDir(git_repository *aRepo, const wxString &aRef, const wxString &aDestDir)
Check out a whole tree into a directory, leaving the repository's working copy and index alone.
static bool ProjectUsesGitLfs(const KIGIT_COMMON &aCommon, wxString *aExample=nullptr, const git_oid *aCommit=nullptr)
Whether any committed file in the project's folder goes through Git LFS.
static bool IsWithinProjectPath(const wxString &aAbsPath, const wxString &aProjectPath)
Test whether an absolute file path lives inside the current project directory.
static bool RemoveVCS(git_repository *&aRepo, const wxString &aProjectPath=wxEmptyString, bool aRemoveGitDir=false, wxString *aErrors=nullptr)
Remove version control from a directory by freeing the repository and optionally removing the ....
static wxString LfsRefusal(KIGIT_COMMON *aCommon)
Return a refusal message for LFS files or an unknown project folder, otherwise empty.
static int CreateBranch(git_repository *aRepo, const wxString &aBranchName)
Create a new branch based on HEAD.
static std::optional< wxString > ProjectPrefix(const wxString &aWorkDir, const wxString &aProjectPath)
The project's folder inside the repository, ending in a slash.
The project's git session.
std::optional< wxString > GetProjectPrefix() const
Project folder relative to the repository, with a trailing slash.
git_repository * GetRepo() const
static wxString GetLastGitError()
libgit2's last message, without credentials from any URL it quotes, so it is safe to show or trace.
bool Register(const std::string &aLabel, F &&aWork)
Spawn a tracked orphan thread running aWork.
A text evaluation frame with one frozen clock and memoized external queries.
static ENVIRONMENT * Current()
GIT_BACKEND * GetGitBackend()
const wxChar *const traceGit
Flag to enable Git debugging output.
std::unique_ptr< git_tree, decltype([](git_tree *aTree) { git_tree_free(aTree); })> GitTreePtr
A unique pointer for git_tree objects with automatic cleanup.
static bool pathIsUnder(const wxString &aAbsPath, const wxString &aProjectPath)
wxString BranchNameError(const wxString &aName)
Empty when aName is a branch name git would accept, otherwise why it would not, in the words to show ...
std::unique_ptr< git_repository, decltype([](git_repository *aRepo) { git_repository_free(aRepo); })> GitRepositoryPtr
A unique pointer for git_repository objects with automatic cleanup.
git_tree * ResolveRefToTree(git_repository *aRepo, const wxString &aRef)
Resolve a string ref (branch name, short OID, full OID, tag) to its tree.
std::unique_ptr< git_commit, decltype([](git_commit *aCommit) { git_commit_free(aCommit); })> GitCommitPtr
A unique pointer for git_commit objects with automatic cleanup.
static wxString canonicalDir(const wxString &aPath)
std::unique_ptr< git_tree_entry, decltype([](git_tree_entry *aEntry) { git_tree_entry_free(aEntry); })> GitTreeEntryPtr
A unique pointer for git_tree_entry objects with automatic cleanup.
static std::optional< wxString > prefixUnder(const wxString &aWorkDir, const wxString &aProjectPath)
std::unique_ptr< git_object, decltype([](git_object *aObject) { git_object_free(aObject); })> GitObjectPtr
A unique pointer for git_object objects with automatic cleanup.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
wxLogTrace helper definitions.