KiCad PCB EDA Suite
Loading...
Searching...
No Matches
git_init_handler.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.TXT for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 3
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include "git_init_handler.h"
21#include "git_backend.h"
24#include <git/kigit_ignore.h>
26#include <paths.h>
27#include <trace_helpers.h>
28
29#include <git2.h>
30
31#include <set>
32#include <string>
33
34#include <wx/ffile.h>
35#include <wx/filename.h>
36#include <wx/log.h>
37#include <wx/tokenzr.h>
38
39
40// Seed a new .gitignore with the same generated paths the change list hides.
41// An existing file belongs to the team and is left alone.
42static void ensureProjectGitignore( const wxString& aProjectPath )
43{
44 const wxFileName ignoreFile = KIGIT::ProjectIgnoreFile( aProjectPath );
45
46 if( ignoreFile.FileExists() )
47 return;
48
49 wxString error;
50
52 wxS( "KiCad-generated files and directories." ), error );
53}
54
55
56// Add .gitattributes entries that route KiCad design files through our merge
57// drivers. The drivers themselves are registered with libgit2 at kiface init
58// (KIGIT_PCB_MERGE::Apply etc.); the attribute file tells git which paths to
59// route to which driver.
60//
61// Append-only: existing user entries are preserved. If a path glob is already
62// present with any merge=... value, we leave it alone — never overwrite a
63// user's choice.
64static void ensureProjectGitattributes( const wxString& aProjectPath )
65{
66 static const std::pair<wxString, wxString> kicadEntries[] = {
67 { wxS( "*.kicad_pcb" ), wxS( "merge=kicad-pcb" ) },
68 { wxS( "*.kicad_sch" ), wxS( "merge=kicad-sch" ) },
69 { wxS( "*.kicad_sym" ), wxS( "merge=kicad-sym-lib" ) },
70 { wxS( "*.kicad_mod" ), wxS( "merge=kicad-fp" ) },
71 };
72
73 wxFileName attrFile( aProjectPath, wxS( ".gitattributes" ) );
74
75 // Map glob -> existing merge driver, if any.
76 std::set<wxString> existingPatterns;
77 bool fileExists = attrFile.FileExists();
78 bool hasTrailingNewline = true;
79
80 if( fileExists )
81 {
82 wxFFile in( attrFile.GetFullPath(), wxT( "r" ) );
83 wxString contents;
84
85 if( !in.IsOpened() || !in.ReadAll( &contents ) )
86 return;
87
88 hasTrailingNewline = contents.empty() || contents.EndsWith( wxS( "\n" ) );
89
90 wxStringTokenizer tok( contents, wxS( "\n" ) );
91
92 while( tok.HasMoreTokens() )
93 {
94 wxString line = tok.GetNextToken();
95 line.Trim().Trim( false );
96
97 if( line.empty() || line.StartsWith( wxS( "#" ) ) )
98 continue;
99
100 // First whitespace-delimited token is the pattern.
101 wxString pattern = line.BeforeFirst( ' ' );
102 pattern = pattern.BeforeFirst( '\t' );
103
104 if( !pattern.empty() )
105 existingPatterns.insert( pattern );
106 }
107 }
108
109 wxString missing;
110
111 for( const auto& [glob, attr] : kicadEntries )
112 {
113 if( existingPatterns.find( glob ) == existingPatterns.end() )
114 missing += glob + wxS( " " ) + attr + wxS( "\n" );
115 }
116
117 if( missing.empty() )
118 return;
119
120 wxFFile out( attrFile.GetFullPath(), wxT( "a" ) );
121
122 if( !out.IsOpened() )
123 return;
124
125 if( !fileExists )
126 out.Write( wxS( "# KiCad design files use custom merge drivers.\n" ) );
127 else if( !hasTrailingNewline )
128 out.Write( wxS( "\n" ) );
129
130 out.Write( missing );
131}
132
133
134// Resolve the absolute path to the kicad-cli binary alongside the running
135// process. Used as the driver / mergetool command so the per-repo git config
136// doesn't depend on PATH (which differs under installers, portable builds,
137// and per-user PATH overrides).
138static wxString resolveKicadCliPath()
139{
140 return PATHS::ResolveSiblingExecutable( wxT( "kicad-cli" ) );
141}
142
143
144// Set a string config key, but only if not already present so the user's
145// custom config is never stomped. Returns true if anything was written.
146static bool setConfigIfMissing( git_config* aConfig, const char* aKey, const wxString& aValue )
147{
148 git_config_entry* entry = nullptr;
149 int result = git_config_get_entry( &entry, aConfig, aKey );
150 KIGIT::GitConfigEntryPtr entryPtr( entry );
151
152 if( result == 0 && entry )
153 {
154 wxLogTrace( traceGit, "Config key '%s' already set; leaving alone", aKey );
155 return false;
156 }
157
158 std::string val( aValue.ToUTF8() );
159
160 if( git_config_set_string( aConfig, aKey, val.c_str() ) != 0 )
161 {
162 wxLogTrace( traceGit, "git_config_set_string('%s') failed: %s",
164 return false;
165 }
166
167 return true;
168}
169
170
171// Configure the merge drivers and mergetool entries pointing at kicad-cli so
172// command-line `git merge` / `git mergetool` invocations route KiCad design
173// files through us. Append-only at the config level too: any existing
174// merge.kicad-* or mergetool.kicad config entry is preserved. `merge.tool`
175// is only set to "kicad" when the user hasn't already picked a tool.
176static void ensureMergeDriverConfig( const wxString& aProjectPath )
177{
178 const wxString cliPath = resolveKicadCliPath();
179
180 if( cliPath.IsEmpty() )
181 {
182 wxLogTrace( traceGit,
183 "kicad-cli not found next to running binary; skipping merge driver "
184 "config (libgit2 in-process driver still works)." );
185 return;
186 }
187
188 git_repository* repo = nullptr;
189
190 if( git_repository_open( &repo, aProjectPath.ToUTF8() ) != 0 )
191 {
192 wxLogTrace( traceGit, "git_repository_open failed: %s",
194 return;
195 }
196
197 KIGIT::GitRepositoryPtr repoPtr( repo );
198
199 git_config* config = nullptr;
200
201 if( git_repository_config( &config, repo ) != 0 )
202 {
203 wxLogTrace( traceGit, "git_repository_config failed: %s",
205 return;
206 }
207
208 KIGIT::GitConfigPtr configPtr( config );
209
210 // Per-format merge driver entries. Command-line `git merge` invokes the
211 // configured driver command for paths tagged `merge=kicad-*` in
212 // .gitattributes; the hidden `kicad-cli git-mergedriver` hook performs a
213 // structural 3-way merge (NOT a text merge), writing the merged file and
214 // returning 0 when clean. On unresolved conflicts it returns non-zero, so
215 // git leaves the path unmerged and the user resolves it interactively with
216 // `git mergetool` (configured below). The document kind is passed via
217 // --kind because git hands the driver extension-less temp paths.
218 // (KiCad's own in-app git integration uses the IN-PROCESS libgit2 driver
219 // registered via git_merge_driver_register instead of these commands.)
220 struct DRIVER_ENTRY
221 {
222 const char* nameKey;
223 const char* driverKey;
224 const char* humanName;
225 const char* cliCommand;
226 };
227
228 static const DRIVER_ENTRY drivers[] = {
229 { "merge.kicad-pcb.name", "merge.kicad-pcb.driver", "KiCad PCB merge driver",
230 "git-mergedriver --kind pcb \"%O\" \"%A\" \"%B\" --output \"%A\"" },
231 { "merge.kicad-sch.name", "merge.kicad-sch.driver", "KiCad schematic merge driver",
232 "git-mergedriver --kind sch \"%O\" \"%A\" \"%B\" --output \"%A\"" },
233 { "merge.kicad-sym-lib.name", "merge.kicad-sym-lib.driver",
234 "KiCad symbol library merge driver",
235 "git-mergedriver --kind sym \"%O\" \"%A\" \"%B\" --output \"%A\"" },
236 { "merge.kicad-fp.name", "merge.kicad-fp.driver", "KiCad footprint merge driver",
237 "git-mergedriver --kind fp \"%O\" \"%A\" \"%B\" --output \"%A\"" }
238 };
239
240 for( const DRIVER_ENTRY& d : drivers )
241 {
242 setConfigIfMissing( config, d.nameKey, wxString::FromUTF8( d.humanName ) );
243
244 wxString cmd = wxT( "\"" ) + cliPath + wxT( "\" " ) + wxString::FromUTF8( d.cliCommand );
245 setConfigIfMissing( config, d.driverKey, cmd );
246 }
247
248 // `git mergetool --tool=kicad` entry. Variables expanded by git:
249 // $BASE, $LOCAL, $REMOTE — ancestor / ours / theirs scratch files
250 // $MERGED — path the merged blob is written back to
251 wxString mergetoolCmd = wxT( "\"" ) + cliPath + wxT( "\" mergetool "
252 "\"$BASE\" \"$LOCAL\" \"$REMOTE\" "
253 "--output \"$MERGED\"" );
254 setConfigIfMissing( config, "mergetool.kicad.cmd", mergetoolCmd );
255 setConfigIfMissing( config, "mergetool.kicad.trustExitCode", wxT( "true" ) );
256
257 // merge.tool — only opt in when the user hasn't already picked a tool,
258 // so existing meld/kdiff3/etc. setups stay untouched.
259 setConfigIfMissing( config, "merge.tool", wxT( "kicad" ) );
260}
261
262
265
266
269
270
271bool GIT_INIT_HANDLER::IsRepository( const wxString& aPath )
272{
273 return GetGitBackend()->IsRepository( this, aPath );
274}
275
276
278{
280
283
284 return result;
285}
286
287
288void ApplyKicadGitConventions( const wxString& aProjectPath )
289{
290 ensureProjectGitignore( aProjectPath );
291 ensureProjectGitattributes( aProjectPath );
292 ensureMergeDriverConfig( aProjectPath );
293}
294
295
297{
298 return GetGitBackend()->SetupRemote( this, aConfig );
299}
virtual InitResult InitializeRepository(GIT_INIT_HANDLER *aHandler, const wxString &aPath)=0
virtual bool IsRepository(GIT_INIT_HANDLER *aHandler, const wxString &aPath)=0
virtual bool SetupRemote(GIT_INIT_HANDLER *aHandler, const RemoteConfig &aConfig)=0
bool IsRepository(const wxString &aPath)
Check if a directory is already a git repository.
GIT_INIT_HANDLER(KIGIT_COMMON *aCommon)
InitResult InitializeRepository(const wxString &aPath)
Initialize a new git repository in the specified directory.
bool SetupRemote(const RemoteConfig &aConfig)
Set up a remote for the repository.
static const std::vector< wxString > & TransientGitIgnorePatterns()
Shared patterns for new .gitignore files and the untracked-file filter.
The project's git session.
static wxString GetLastGitError()
libgit2's last message, without credentials from any URL it quotes, so it is safe to show or trace.
KIGIT_REPO_MIXIN(KIGIT_COMMON *aCommon)
static wxString ResolveSiblingExecutable(const wxString &aBaseName)
Resolve a sibling executable alongside the running process.
Definition paths.cpp:714
GIT_BACKEND * GetGitBackend()
static void ensureProjectGitignore(const wxString &aProjectPath)
static wxString resolveKicadCliPath()
static void ensureProjectGitattributes(const wxString &aProjectPath)
void ApplyKicadGitConventions(const wxString &aProjectPath)
Apply KiCad's standard repo conventions to a project directory:
static void ensureMergeDriverConfig(const wxString &aProjectPath)
static bool setConfigIfMissing(git_config *aConfig, const char *aKey, const wxString &aValue)
InitResult
APIEXPORT void ApplyKicadGitConventions(const wxString &aProjectPath)
Apply KiCad's standard repo conventions to a project directory:
const wxChar *const traceGit
Flag to enable Git debugging output.
static CLI::MERGETOOL_COMMAND mergetoolCmd
std::unique_ptr< git_repository, decltype([](git_repository *aRepo) { git_repository_free(aRepo); })> GitRepositoryPtr
A unique pointer for git_repository objects with automatic cleanup.
APIEXPORT bool AddIgnoreRules(const wxFileName &aIgnoreFile, const std::vector< wxString > &aRules, const wxString &aHeader, wxString &aError)
Append rules to an ignore file, creating it with aHeader as a comment when it is not there.
APIEXPORT wxFileName ProjectIgnoreFile(const wxString &aProjectPath)
The ignore file that covers a project.
std::unique_ptr< git_config, decltype([](git_config *aConfig) { git_config_free(aConfig); })> GitConfigPtr
A unique pointer for git_config objects with automatic cleanup.
std::unique_ptr< git_config_entry, decltype([](git_config_entry *aEntry) { git_config_entry_free(aEntry); })> GitConfigEntryPtr
A unique pointer for git_config_entry objects with automatic cleanup.
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.