KiCad PCB EDA Suite
Loading...
Searching...
No Matches
kigit_ignore.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 "kigit_ignore.h"
21
22#include <core/kicad_algo.h>
25
26#include <optional>
27#include <string>
28
29#include <wx/ffile.h>
30#include <wx/file.h>
31#include <wx/tokenzr.h>
32#include <wx/translation.h>
33
34
35namespace
36{
37
38// Git reads these as patterns, so a name holding one has to be escaped.
39wxString escapePattern( const wxString& aText )
40{
41 wxString escaped;
42
43 for( const wxUniChar& ch : aText )
44 {
45 if( ch == '*' || ch == '?' || ch == '[' || ch == '\\' )
46 escaped += '\\';
47
48 escaped += ch;
49 }
50
51 return escaped;
52}
53
54
55bool readIgnoreFile( const wxFileName& aIgnoreFile, wxString& aContents )
56{
57 // Opening a file that is not there logs a system error, and having no rules yet is normal.
58 if( !aIgnoreFile.FileExists() )
59 return false;
60
61 wxFFile in( aIgnoreFile.GetFullPath(), wxT( "r" ) );
62
63 return in.IsOpened() && in.ReadAll( &aContents );
64}
65
66
67bool fileError( wxString& aError, const wxString& aMessage, const wxFileName& aFile )
68{
69 aError = wxString::Format( aMessage, aFile.GetFullPath() );
70 return false;
71}
72
73
74std::vector<wxString> splitIgnoreRules( const wxString& aContents )
75{
76 std::vector<wxString> rules;
77 wxStringTokenizer tokenizer( aContents, wxS( "\n" ) );
78
79 while( tokenizer.HasMoreTokens() )
80 {
81 wxString line = tokenizer.GetNextToken();
82 line.Trim().Trim( false );
83
84 if( !line.IsEmpty() && !line.StartsWith( wxS( "#" ) ) )
85 rules.push_back( line );
86 }
87
88 return rules;
89}
90
91} // namespace
92
93
94wxFileName KIGIT::ProjectIgnoreFile( const wxString& aProjectPath )
95{
96 return wxFileName( aProjectPath, wxS( ".gitignore" ) );
97}
98
99
100wxString KIGIT::PathIgnoreRule( const wxString& aProjectRelPath, bool aIsDirectory )
101{
102 if( aProjectRelPath.IsEmpty() )
103 return wxEmptyString;
104
105 // The leading slash anchors the rule here, so it cannot match the same name further down.
106 wxString rule = wxS( "/" ) + escapePattern( aProjectRelPath );
107
108 if( aIsDirectory )
109 rule += wxS( "/" );
110
111 return rule;
112}
113
114
115wxString KIGIT::ExtensionIgnoreRule( const wxString& aProjectRelPath )
116{
117 const wxString ext = wxFileName( aProjectRelPath, wxPATH_UNIX ).GetExt();
118
119 if( ext.IsEmpty() )
120 return wxEmptyString;
121
122 return wxS( "*." ) + escapePattern( ext );
123}
124
125
126std::vector<wxString> KIGIT::ReadIgnoreRules( const wxFileName& aIgnoreFile )
127{
128 wxString contents;
129
130 if( !readIgnoreFile( aIgnoreFile, contents ) )
131 return {};
132
133 return splitIgnoreRules( contents );
134}
135
136
137bool KIGIT::AddIgnoreRules( const wxFileName& aIgnoreFile, const std::vector<wxString>& aRules, const wxString& aHeader,
138 wxString& aError )
139{
140 const bool exists = aIgnoreFile.FileExists();
141 wxString contents;
142
143 if( exists && !readIgnoreFile( aIgnoreFile, contents ) )
144 return fileError( aError, _( "Could not read '%s'." ), aIgnoreFile );
145
146 std::vector<wxString> present = splitIgnoreRules( contents );
147 wxString missing;
148
149 for( const wxString& rule : aRules )
150 {
151 if( rule.IsEmpty() || alg::contains( present, rule ) )
152 continue;
153
154 // A rule listed twice in one call would otherwise be written twice.
155 present.push_back( rule );
156 missing += rule + wxS( "\n" );
157 }
158
159 if( missing.IsEmpty() )
160 return true;
161
162 if( !exists )
163 {
164 if( !aHeader.IsEmpty() )
165 missing.Prepend( wxS( "# " ) + aHeader + wxS( "\n" ) );
166 }
167 else if( !contents.IsEmpty() && !contents.EndsWith( wxS( "\n" ) ) )
168 {
169 // Otherwise the first new rule would land on the end of the user's last one.
170 missing.Prepend( wxS( "\n" ) );
171 }
172
173 wxFFile out( aIgnoreFile.GetFullPath(), wxT( "a" ) );
174
175 if( !out.IsOpened() || !out.Write( missing ) )
176 return fileError( aError, _( "Could not write to '%s'." ), aIgnoreFile );
177
178 return true;
179}
180
181
182bool KIGIT::RemoveIgnoreRules( const wxFileName& aIgnoreFile, const std::vector<wxString>& aRules, wxString& aError )
183{
184 wxString contents;
185
186 if( !aIgnoreFile.FileExists() )
187 return true;
188
189 if( !readIgnoreFile( aIgnoreFile, contents ) )
190 return fileError( aError, _( "Could not read '%s'." ), aIgnoreFile );
191
192 wxString kept;
193 bool removed = false;
194
195 wxStringTokenizer tokenizer( contents, wxS( "\n" ), wxTOKEN_RET_EMPTY );
196
197 while( tokenizer.HasMoreTokens() )
198 {
199 wxString line = tokenizer.GetNextToken();
200 wxString rule = line;
201 rule.Trim().Trim( false );
202
203 if( !rule.IsEmpty() && alg::contains( aRules, rule ) )
204 {
205 removed = true;
206 continue;
207 }
208
209 kept += line + wxS( "\n" );
210 }
211
212 if( !removed )
213 return true;
214
215 // A rewrite that failed partway would lose rules the user still wants.
216 wxTempFile out( aIgnoreFile.GetFullPath() );
217
218 if( !out.IsOpened() || !out.Write( kept ) || !out.Commit() )
219 return fileError( aError, _( "Could not write to '%s'." ), aIgnoreFile );
220
221 return true;
222}
223
224
225KIGIT::IGNORE_STATE KIGIT::IgnoreState( KIGIT_COMMON& aCommon, const wxString& aProjectRelPath, bool aIsDirectory )
226{
227 IGNORE_STATE state;
228 git_repository* repo = aCommon.GetRepo();
229 const std::optional<wxString> prefix = aCommon.GetProjectPrefix();
230
231 if( !repo || !prefix || aProjectRelPath.IsEmpty() )
232 return state;
233
234 const wxString repoRelative = *prefix + aProjectRelPath;
235 const std::string repoRelPath = repoRelative.utf8_string();
236 int ignored = 0;
237
238 // The trailing slash tells libgit2 this is a directory, so directory-only rules apply.
239 const std::string ignorePath = aIsDirectory ? repoRelPath + "/" : repoRelPath;
240
241 if( git_ignore_path_is_ignored( &ignored, repo, ignorePath.c_str() ) == GIT_OK )
242 state.ignored = ignored != 0;
243
244 git_index* index = nullptr;
245
246 if( git_repository_index( &index, repo ) != GIT_OK )
247 return state;
248
249 KIGIT::GitIndexPtr indexPtr( index );
250
251 if( aIsDirectory )
252 {
253 // A rule for the folder cannot untrack what is already inside it.
254 const std::string indexPrefix = repoRelPath + "/";
255 size_t position = 0;
256
257 state.tracked = git_index_find_prefix( &position, index, indexPrefix.c_str() ) == GIT_OK;
258 }
259 else
260 {
261 // A file a merge stopped on has no stage zero entry, but git tracks it just the same.
262 state.tracked = git_index_get_bypath( index, repoRelPath.c_str(), 0 ) != nullptr
263 || aCommon.IsPathConflicted( repoRelative );
264 }
265
266 return state;
267}
int index
The project's git session.
std::optional< wxString > GetProjectPrefix() const
Project folder relative to the repository, with a trailing slash.
git_repository * GetRepo() const
bool IsPathConflicted(const wxString &aPath) const
True while aPath is one of the files a merge or rebase stopped on.
#define _(s)
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.
APIEXPORT bool RemoveIgnoreRules(const wxFileName &aIgnoreFile, const std::vector< wxString > &aRules, wxString &aError)
Remove rules from an ignore file.
APIEXPORT wxString ExtensionIgnoreRule(const wxString &aProjectRelPath)
The rule that ignores every file sharing a path's extension, or nothing when it has none.
APIEXPORT IGNORE_STATE IgnoreState(KIGIT_COMMON &aCommon, const wxString &aProjectRelPath, bool aIsDirectory)
What git's rules and its index say about a project path, so the user is offered only what would take ...
APIEXPORT wxString PathIgnoreRule(const wxString &aProjectRelPath, bool aIsDirectory)
The rule that ignores one path and nothing else.
APIEXPORT std::vector< wxString > ReadIgnoreRules(const wxFileName &aIgnoreFile)
The rules an ignore file holds, in order, without its comments and blank lines.
std::unique_ptr< git_index, decltype([](git_index *aIndex) { git_index_free(aIndex); })> GitIndexPtr
A unique pointer for git_index objects with automatic cleanup.
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
What an ignore rule for one path would achieve.
bool tracked
The path, or a file inside it, is in the index, so a new rule would do nothing.
bool ignored
Git's rules already cover the path.