KiCad PCB EDA Suite
Loading...
Searching...
No Matches
text_eval_vcs.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 modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * 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
23#include <git/git_backend.h>
26#include <string_utils.h>
27#include <wx/filename.h>
28#include <wx/string.h>
29#include <wx/arrstr.h> // REQUIRED for wxString vector export on MSVC
30#include <algorithm>
31#include <map>
32
34{
35// Per-thread override that anchors repo-scoped queries to a specific path (for example the
36// loaded project directory). When empty, repo discovery falls back to the process cwd.
37namespace
38{
39 // Static destructors such as ~SETTINGS_MANAGER run after the main thread's thread_local objects are
40 // destroyed. A bool has no destructor, so it stays readable and tells them the context is gone.
41 thread_local bool tl_contextGone = false;
42
43 struct CONTEXT
44 {
45 ~CONTEXT() { tl_contextGone = true; }
46
47 wxString path;
48 bool isFile = false;
49 };
50
51 thread_local CONTEXT tl_context;
52
53 void setContext( const wxString& aPath, bool aIsFile )
54 {
55 if( tl_contextGone )
56 return;
57
58 tl_context.path = aPath;
59 tl_context.isFile = aIsFile;
60 }
61}
62
63
64void SetContextPath( const wxString& aPath )
65{
66 setContext( aPath, !aPath.IsEmpty() && wxFileName( aPath ).FileExists() );
67}
68
69
71{
72 if( tl_contextGone || tl_context.path.IsEmpty() )
73 return wxString( wxT( "." ) );
74
75 return tl_context.path;
76}
77
78
80{
81 return !tl_contextGone && tl_context.isFile;
82}
83
84
86 m_previous( tl_contextGone ? wxString() : tl_context.path ),
88{
89 SetContextPath( aPath );
90}
91
92
97
98
99// Private implementation details
100namespace
101{
102 wxString ResolveEffectivePath( const std::string& aPath )
103 {
104 if( aPath.empty() || aPath == "." )
105 return GetContextPath();
106
107 wxFileName path( wxString::FromUTF8( aPath ) );
108
109 if( path.IsRelative() )
110 {
111 wxFileName context( GetContextPath() );
112 context.MakeAbsolute();
113 path.MakeAbsolute( GetContextIsFile() ? context.GetPath() : context.GetFullPath() );
114 }
115
116 return path.GetFullPath();
117 }
118
119
120 using VCS_QUERY = TEXT_EVAL::ENVIRONMENT::VCS_QUERY;
121 using VCS_VALUE = TEXT_EVAL::ENVIRONMENT::VCS_VALUE;
122
123 VCS_VALUE Capture( VCS_QUERY aQuery, const std::string& aPath, const std::string& aArgument,
124 int aOptions, const std::function<VCS_VALUE()>& aRead )
125 {
126 if( TEXT_EVAL::ENVIRONMENT* environment = TEXT_EVAL::ENVIRONMENT::Current() )
127 {
128 wxFileName path = wxFileName::DirName( ResolveEffectivePath( aPath ) );
129 path.MakeAbsolute();
130 const bool contextFile = GetContextIsFile() && ( aPath.empty() || aPath == "." );
131 return environment->VcsValue( { aQuery,
132 path.GetPath( (int) wxPATH_GET_VOLUME ),
133 aArgument,
134 aOptions,
135 contextFile },
136 aRead );
137 }
138
139 return aRead();
140 }
141
142
143 git_repository* OpenRepo( const std::string& aPath )
144 {
145 if( !GetGitBackend() )
146 return nullptr;
147
148 wxFileName effective( ResolveEffectivePath( aPath ) );
149
150 if( ( !aPath.empty() && aPath != "." ) || GetContextIsFile() )
151 {
152 effective.MakeAbsolute();
153 return KIGIT::PROJECT_GIT_UTILS::GetRepositoryForFile( TO_UTF8( effective.GetPath() ) );
154 }
155
156 return KIGIT::PROJECT_GIT_UTILS::GetRepositoryForFile( TO_UTF8( effective.GetFullPath() ) );
157 }
158
159 void CloseRepo( git_repository* aRepo )
160 {
161 if( aRepo )
162 git_repository_free( aRepo );
163 }
164
165 git_oid MakeZeroOid()
166 {
167 git_oid oid;
168 git_oid_fromstrn( &oid, "0000000000000000000000000000000000000000", 40 );
169 return oid;
170 }
171
172 git_oid GetFileCommit( git_repository* aRepo, const std::string& aPath )
173 {
174 if( !aRepo )
175 return MakeZeroOid();
176
177 const git_oid head_oid = KIGIT::PROJECT_GIT_UTILS::GetCapturedHeadOid( aRepo );
178
179 if( git_oid_is_zero( &head_oid ) )
180 return MakeZeroOid();
181
182 // For repo-level query (empty or "."), just return HEAD
183 if( aPath.empty() || aPath == "." )
184 return head_oid;
185
186 const char* workdir = git_repository_workdir( aRepo );
187
188 if( !workdir )
189 return MakeZeroOid();
190
191 wxFileName file( ResolveEffectivePath( aPath ) );
192
194 file.GetPath(), wxString::FromUTF8( workdir ) );
195
196 if( !file.MakeRelativeTo( base ) )
197 return MakeZeroOid();
198
199 const std::string treePath = file.GetFullPath( wxPATH_UNIX ).ToStdString( wxConvUTF8 );
200
201 if( treePath.empty() || treePath == "." || treePath == ".." || treePath.starts_with( "../" ) )
202 return MakeZeroOid();
203
204 // For file-specific query, walk history to find last commit that touched this file
205 git_revwalk* walker = nullptr;
206
207 if( git_revwalk_new( &walker, aRepo ) != 0 )
208 return MakeZeroOid();
209
210 git_revwalk_sorting( walker, GIT_SORT_TIME );
211
212 if( git_revwalk_push( walker, &head_oid ) != 0 )
213 {
214 git_revwalk_free( walker );
215 return MakeZeroOid();
216 }
217
218 // Walk through commits to find when the file was last modified
219 git_oid result = MakeZeroOid();
220 git_oid commit_oid;
221 git_oid prev_blob_oid = MakeZeroOid();
222 bool first_commit = true;
223
224 while( git_revwalk_next( &commit_oid, walker ) == 0 )
225 {
226 git_commit* commit = nullptr;
227
228 if( git_commit_lookup( &commit, aRepo, &commit_oid ) != 0 )
229 continue;
230
231 // Get the tree for this commit
232 git_tree* tree = nullptr;
233
234 if( git_commit_tree( &tree, commit ) == 0 )
235 {
236 // Try to find the file in this tree
237 git_tree_entry* entry = nullptr;
238
239 if( git_tree_entry_bypath( &entry, tree, treePath.c_str() ) == 0 )
240 {
241 const git_oid* blob_oid = git_tree_entry_id( entry );
242
243 if( first_commit )
244 {
245 // First time we see this file, remember its blob ID
246 git_oid_cpy( &prev_blob_oid, blob_oid );
247 git_oid_cpy( &result, &commit_oid );
248 first_commit = false;
249 }
250 else if( git_oid_cmp( blob_oid, &prev_blob_oid ) != 0 )
251 {
252 // File content changed - previous commit is where it changed
253 git_tree_entry_free( entry );
254 git_tree_free( tree );
255 git_commit_free( commit );
256 break;
257 }
258 else
259 {
260 // File unchanged, keep looking
261 git_oid_cpy( &result, &commit_oid );
262 }
263
264 git_tree_entry_free( entry );
265 }
266 else if( !first_commit )
267 {
268 // File doesn't exist in this commit, but existed before
269 // So the previous commit is where it was added/last modified
270 git_tree_free( tree );
271 git_commit_free( commit );
272 break;
273 }
274
275 git_tree_free( tree );
276 }
277
278 git_commit_free( commit );
279 }
280
281 git_revwalk_free( walker );
282 return result;
283 }
284
285 struct DESCRIBE_INFO
286 {
287 std::string tag;
288 int distance;
289 };
290
291 DESCRIBE_INFO ReadDescribeInfo( const std::string& aMatch, bool aAnyTags )
292 {
293 git_repository* repo = OpenRepo( "." );
294
295 if( !repo )
296 return { std::string(), 0 };
297
298 const git_oid head_oid = KIGIT::PROJECT_GIT_UTILS::GetCapturedHeadOid( repo );
299
300 if( git_oid_is_zero( &head_oid ) )
301 {
302 CloseRepo( repo );
303 return { std::string(), 0 };
304 }
305
306 git_strarray tag_names;
307
308 if( git_tag_list_match( &tag_names, aMatch.empty() ? "*" : aMatch.c_str(), repo ) != 0 )
309 {
310 CloseRepo( repo );
311 return { std::string(), 0 };
312 }
313
314 // Build map of commit OID -> tag name upfront
315 std::map<git_oid, std::string, decltype(
316 [](const git_oid& a, const git_oid& b)
317 {
318 return git_oid_cmp(&a, &b) < 0;
319 } )> commit_to_tag;
320
321 for( size_t i = 0; i < tag_names.count; ++i )
322 {
323 git_object* tag_obj = nullptr;
324
325 if( git_revparse_single( &tag_obj, repo, tag_names.strings[i] ) == 0 )
326 {
327 git_object_t type = git_object_type( tag_obj );
328
329 if( type == GIT_OBJECT_TAG )
330 {
331 git_object* target = nullptr;
332
333 if( git_tag_peel( &target, (git_tag*) tag_obj ) == 0 )
334 {
335 commit_to_tag[*git_object_id( target )] = tag_names.strings[i];
336 git_object_free( target );
337 }
338 }
339 else if( aAnyTags && type == GIT_OBJECT_COMMIT )
340 {
341 commit_to_tag[*git_object_id( tag_obj )] = tag_names.strings[i];
342 }
343
344 git_object_free( tag_obj );
345 }
346 }
347
348 git_strarray_dispose( &tag_names );
349
350 git_revwalk* walker = nullptr;
351
352 if( git_revwalk_new( &walker, repo ) != 0 )
353 {
354 CloseRepo( repo );
355 return { std::string(), 0 };
356 }
357
358 git_revwalk_sorting( walker, GIT_SORT_TOPOLOGICAL | GIT_SORT_TIME );
359
360 if( git_revwalk_push( walker, &head_oid ) != 0 )
361 {
362 git_revwalk_free( walker );
363 CloseRepo( repo );
364 return { std::string(), 0 };
365 }
366
367 DESCRIBE_INFO result{ std::string(), 0 };
368 int distance = 0;
369 git_oid commit_oid;
370
371 while( git_revwalk_next( &commit_oid, walker ) == 0 )
372 {
373 auto it = commit_to_tag.find( commit_oid );
374
375 if( it != commit_to_tag.end() )
376 {
377 result.tag = it->second;
378 result.distance = distance;
379 break;
380 }
381
382 distance++;
383 }
384
385 git_revwalk_free( walker );
386 CloseRepo( repo );
387 return result;
388 }
389
390 DESCRIBE_INFO GetDescribeInfo( const std::string& aMatch, bool aAnyTags )
391 {
392 const VCS_VALUE value = Capture( VCS_QUERY::DESCRIPTION, ".", aMatch, aAnyTags,
393 [&]() -> VCS_VALUE
394 {
395 const DESCRIBE_INFO description = ReadDescribeInfo( aMatch, aAnyTags );
396 return { description.tag, description.distance };
397 } );
398 return { value.text, static_cast<int>( value.number ) };
399 }
400
401 std::string ReadCommitSignatureField( const std::string& aPath, bool aUseCommitter, bool aGetEmail )
402 {
403 git_repository* repo = OpenRepo( aPath );
404
405 if( !repo )
406 return std::string();
407
408 git_oid oid = GetFileCommit( repo, aPath );
409
410 if( git_oid_is_zero( &oid ) )
411 {
412 CloseRepo( repo );
413 return std::string();
414 }
415
416 git_commit* commit = nullptr;
417 std::string result;
418
419 if( git_commit_lookup( &commit, repo, &oid ) == 0 )
420 {
421 const git_signature* sig = aUseCommitter ? git_commit_committer( commit ) : git_commit_author( commit );
422
423 if( sig )
424 {
425 const char* field = aGetEmail ? sig->email : sig->name;
426
427 if( field )
428 result = field;
429 }
430
431 git_commit_free( commit );
432 }
433
434 CloseRepo( repo );
435 return result;
436 }
437
438 std::string GetCommitSignatureField( const std::string& aPath, bool aUseCommitter, bool aGetEmail )
439 {
440 return Capture( VCS_QUERY::SIGNATURE, aPath, aPath, ( aUseCommitter ? 2 : 0 ) | ( aGetEmail ? 1 : 0 ),
441 [&]() -> VCS_VALUE
442 {
443 return { ReadCommitSignatureField( aPath, aUseCommitter, aGetEmail ) };
444 } ).text;
445 }
446
447} // anonymous namespace
448
449
450static std::string ReadCommitHash( const std::string& aPath )
451{
452 git_repository* repo = OpenRepo( aPath );
453
454 if( !repo )
455 return std::string();
456
457 git_oid oid = GetFileCommit( repo, aPath );
458
459 if( git_oid_is_zero( &oid ) )
460 {
461 CloseRepo( repo );
462 return std::string();
463 }
464
465 char hash[GIT_OID_HEXSZ + 1];
466 git_oid_tostr( hash, sizeof( hash ), &oid );
467
468 CloseRepo( repo );
469 return hash;
470}
471
472
473std::string GetCommitHash( const std::string& aPath, int aLength )
474{
475 const VCS_VALUE value = Capture( VCS_QUERY::HASH, aPath, aPath, 0,
476 [&]() -> VCS_VALUE
477 {
478 return { ReadCommitHash( aPath ) };
479 } );
480 return value.text.substr( 0, std::clamp( aLength, 4, GIT_OID_HEXSZ ) );
481}
482
483
484std::string GetNearestTag( const std::string& aMatch, bool aAnyTags )
485{
486 return GetDescribeInfo( aMatch, aAnyTags ).tag;
487}
488
489
490int GetDistanceFromTag( const std::string& aMatch, bool aAnyTags )
491{
492 return GetDescribeInfo( aMatch, aAnyTags ).distance;
493}
494
495
496static bool ReadIsDirty( bool aIncludeUntracked )
497{
498 git_repository* repo = OpenRepo( "." );
499
500 if( !repo )
501 return false;
502
503 git_status_list* status = nullptr;
504 git_status_options statusOpts;
505 git_status_options_init( &statusOpts, GIT_STATUS_OPTIONS_VERSION );
506
507 statusOpts.show = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
508 statusOpts.flags = aIncludeUntracked ? GIT_STATUS_OPT_INCLUDE_UNTRACKED : GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
509
510 bool isDirty = false;
511
512 if( git_status_list_new( &status, repo, &statusOpts ) == 0 )
513 {
514 isDirty = git_status_list_entrycount( status ) > 0;
515 git_status_list_free( status );
516 }
517
518 CloseRepo( repo );
519 return isDirty;
520}
521
522
523bool IsDirty( bool aIncludeUntracked )
524{
525 return Capture( VCS_QUERY::DIRTY, ".", "", aIncludeUntracked,
526 [&]() -> VCS_VALUE
527 {
528 return { {}, ReadIsDirty( aIncludeUntracked ) };
529 } ).number != 0;
530}
531
532
533std::string GetAuthor( const std::string& aPath )
534{
535 return GetCommitSignatureField( aPath, false, false );
536}
537
538
539std::string GetAuthorEmail( const std::string& aPath )
540{
541 return GetCommitSignatureField( aPath, false, true );
542}
543
544
545std::string GetCommitter( const std::string& aPath )
546{
547 return GetCommitSignatureField( aPath, true, false );
548}
549
550
551std::string GetCommitterEmail( const std::string& aPath )
552{
553 return GetCommitSignatureField( aPath, true, true );
554}
555
556
557static std::string ReadBranch()
558{
559 git_repository* repo = OpenRepo( "." );
560
561 if( !repo )
562 return std::string();
563
564 KIGIT_COMMON common( repo );
565 wxString branchName = common.GetCurrentBranchName();
566
567 CloseRepo( repo );
568 return branchName.ToStdString();
569}
570
571
572std::string GetBranch()
573{
574 return Capture( VCS_QUERY::BRANCH, ".", "", 0,
575 []() -> VCS_VALUE
576 {
577 return { ReadBranch() };
578 } ).text;
579}
580
581
582static int64_t ReadCommitTimestamp( const std::string& aPath )
583{
584 git_repository* repo = OpenRepo( aPath );
585
586 if( !repo )
587 return 0;
588
589 git_oid oid = GetFileCommit( repo, aPath );
590
591 if( git_oid_is_zero( &oid ) )
592 {
593 CloseRepo( repo );
594 return 0;
595 }
596
597 git_commit* commit = nullptr;
598 int64_t timestamp = 0;
599
600 if( git_commit_lookup( &commit, repo, &oid ) == 0 )
601 {
602 timestamp = static_cast<int64_t>( git_commit_time( commit ) );
603 git_commit_free( commit );
604 }
605
606 CloseRepo( repo );
607 return timestamp;
608}
609
610
611int64_t GetCommitTimestamp( const std::string& aPath )
612{
613 return Capture( VCS_QUERY::TIMESTAMP, aPath, aPath, 0,
614 [&]() -> VCS_VALUE
615 {
616 return { {}, ReadCommitTimestamp( aPath ) };
617 } ).number;
618}
619
620
621std::string GetCommitDate( const std::string& aPath )
622{
623 int64_t timestamp = GetCommitTimestamp( aPath );
624 return timestamp > 0 ? std::to_string( timestamp ) : std::string();
625}
626
627
629{
630 const auto read =
631 [&]() -> VCS_VALUE
632 {
633 const auto& [query, path, argument, options, contextFile] = aKey;
634
635 if( query == VCS_QUERY::HEAD )
636 {
637 if( !GetGitBackend() )
638 return {};
639
640 git_repository* raw = nullptr;
641
642 // Discovery could select the main repository instead of this linked worktree's HEAD.
643 if( git_repository_open( &raw, path.ToUTF8().data() ) != 0 )
644 return {};
645
646 KIGIT::GitRepositoryPtr repo( raw );
647 git_oid oid{};
648
649 if( git_reference_name_to_id( &oid, repo.get(), "HEAD" ) != 0 )
650 return {};
651
652 char hash[GIT_OID_HEXSZ + 1];
653 git_oid_tostr( hash, sizeof( hash ), &oid );
654 return { hash };
655 }
656
657 const bool fileQuery = ( query == VCS_QUERY::HASH
658 || query == VCS_QUERY::SIGNATURE
659 || query == VCS_QUERY::TIMESTAMP )
660 && !argument.empty()
661 && argument != ".";
662 const CONTEXT_PATH_SCOPE context( fileQuery || contextFile ? wxFileName( path ).GetPath() : path );
663 const std::string file = fileQuery ? path.ToStdString( wxConvUTF8 ) : std::string();
664
665 switch( query )
666 {
667 case VCS_QUERY::HASH:
668 return { ReadCommitHash( file ) };
669
670 case VCS_QUERY::DESCRIPTION:
671 {
672 const DESCRIBE_INFO description = ReadDescribeInfo( argument, options != 0 );
673 return { description.tag, description.distance };
674 }
675
676 case VCS_QUERY::SIGNATURE:
677 return { ReadCommitSignatureField( file, ( options & 2 ) != 0, ( options & 1 ) != 0 ) };
678
679 case VCS_QUERY::BRANCH:
680 return { ReadBranch() };
681
682 case VCS_QUERY::DIRTY:
683 return { {}, ReadIsDirty( options != 0 ) };
684
685 case VCS_QUERY::TIMESTAMP:
686 return { {}, ReadCommitTimestamp( file ) };
687
688 case VCS_QUERY::HEAD:
689 break;
690 }
691
692 return {};
693 };
694
696 return environment->VcsValue( aKey, read );
697
698 return read();
699}
700
701} // namespace TEXT_EVAL_VCS
wxString GetCommitHash()
Get the commit hash as a string.
static git_oid GetCapturedHeadOid(git_repository *aRepo)
Return HEAD for commit-based text queries.
static git_repository * GetRepositoryForFile(const char *aFilename, wxString *aError=nullptr, wxString *aTrustCommand=nullptr)
Discover and open the repository that contains the given file.
static wxString ComputeSymlinkPreservingWorkDir(const wxString &aUserProjectPath, const wxString &aCanonicalWorkDir)
Compute a working directory path that preserves symlinks from the user's project path.
The project's git session.
wxString GetCurrentBranchName() const
A text evaluation frame with one frozen clock and memoized external queries.
static ENVIRONMENT * Current()
std::tuple< VCS_QUERY, wxString, std::string, int, bool > VCS_KEY
Query, absolute path (Git directory for HEAD), selector or pattern, options, and whether the context ...
RAII helper that sets the VCS context path on construction and restores the previous value on destruc...
CONTEXT_PATH_SCOPE(const wxString &aPath)
GIT_BACKEND * GetGitBackend()
std::unique_ptr< git_repository, decltype([](git_repository *aRepo) { git_repository_free(aRepo); })> GitRepositoryPtr
A unique pointer for git_repository objects with automatic cleanup.
VCS (Version Control System) utility functions for text evaluation.
std::string GetAuthor(const std::string &aPath)
Get the author name of the HEAD commit.
bool IsDirty(bool aIncludeUntracked)
Check if the repository has uncommitted changes.
wxString GetContextPath()
Return the current context path for repo-scoped VCS queries.
bool GetContextIsFile()
File/directory classification captured when the current context was activated.
static std::string ReadBranch()
static int64_t ReadCommitTimestamp(const std::string &aPath)
TEXT_EVAL::ENVIRONMENT::VCS_VALUE ReadSource(const TEXT_EVAL::ENVIRONMENT::VCS_KEY &aKey)
Re-read an owned query descriptor using any active frame memo.
static std::string ReadCommitHash(const std::string &aPath)
std::string GetCommitterEmail(const std::string &aPath)
Get the committer email of the HEAD commit.
std::string GetCommitDate(const std::string &aPath)
Get the commit date of the HEAD commit as a timestamp string.
std::string GetAuthorEmail(const std::string &aPath)
Get the author email of the HEAD commit.
void SetContextPath(const wxString &aPath)
Set the filesystem path used for repository discovery and relative file queries.
std::string GetCommitter(const std::string &aPath)
Get the committer name of the HEAD commit.
std::string GetBranch()
Get the current branch name.
std::string GetNearestTag(const std::string &aMatch, bool aAnyTags)
Get the nearest tag/label from HEAD.
static bool ReadIsDirty(bool aIncludeUntracked)
int64_t GetCommitTimestamp(const std::string &aPath)
Get the commit timestamp (Unix time) of the HEAD commit.
int GetDistanceFromTag(const std::string &aMatch, bool aAnyTags)
Get the number of commits since the nearest matching tag.
static float distance(const SFVEC2UI &a, const SFVEC2UI &b)
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
std::string path
wxString result
Test unit parsing edge cases and error handling.