KiCad PCB EDA Suite
Loading...
Searching...
No Matches
project_template.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 (C) 2012 Brian Sidebotham <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25
26#include <wx/bitmap.h>
27#include <wx/dir.h>
28#include <wx/txtstrm.h>
29#include <wx/wfstream.h>
30#include <wx/log.h>
31#include <wx/textfile.h>
32#include <unordered_map>
33
35#include "project_template.h"
36
37
38#define SEP wxFileName::GetPathSeparator()
39
40
41PROJECT_TEMPLATE::PROJECT_TEMPLATE( const wxString& aPath )
42{
43 m_basePath = wxFileName::DirName( aPath );
44 m_metaPath = wxFileName::DirName( aPath + SEP + METADIR );
45 m_metaHtmlFile = wxFileName::FileName( aPath + SEP + METADIR + SEP + METAFILE_INFO_HTML );
46 m_metaIconFile = wxFileName::FileName( aPath + SEP + METADIR + SEP + METAFILE_ICON );
47
48 m_title = wxEmptyString;
49
50 // Test the project template requirements to make sure aPath is a valid template structure.
51 if( !wxFileName::DirExists( m_basePath.GetPath() ) )
52 {
53 // Error, the path doesn't exist!
54 m_title.Printf( _( "Could not open the template path '%s'" ), aPath );
55 }
56 else if( !wxFileName::DirExists( m_metaPath.GetPath() ) )
57 {
58 // Error, the meta information directory doesn't exist!
59 m_title.Printf( _( "Could not find the expected 'meta' directory at '%s'" ), m_metaPath.GetPath() );
60 }
61 else if( !wxFileName::FileExists( m_metaHtmlFile.GetFullPath() ) )
62 {
63 // Error, the meta information directory doesn't contain the informational html file!
64 m_title.Printf( _( "Could not find the expected meta HTML file at '%s'" ), m_metaHtmlFile.GetFullPath() );
65 }
66
67 // Try to load an icon
68 if( !wxFileName::FileExists( m_metaIconFile.GetFullPath() ) )
69 m_metaIcon = &wxNullBitmap;
70 else
71 m_metaIcon = new wxBitmap( m_metaIconFile.GetFullPath(), wxBITMAP_TYPE_PNG );
72}
73
74
75class FILE_TRAVERSER : public wxDirTraverser
76{
77public:
78 FILE_TRAVERSER( std::vector<wxFileName>& files, const wxString& exclude ) :
79 m_files( files ),
80 m_exclude( exclude )
81 {
82 }
83
84 virtual wxDirTraverseResult OnFile( const wxString& filename ) override
85 {
86 wxFileName fn( filename );
87 wxString path( fn.GetPathWithSep() );
88
90
91 if( IsIgnored( path, fn.GetFullName(), false ) )
92 return wxDIR_CONTINUE;
93
94 bool exclude = fn.GetName().Contains( "fp-info-cache" )
95 || fn.GetName().StartsWith( FILEEXT::LockFilePrefix );
96
97 if( !exclude )
98 m_files.emplace_back( wxFileName( filename ) );
99
100 return wxDIR_CONTINUE;
101 }
102
103 virtual wxDirTraverseResult OnDir( const wxString& dirname ) override
104 {
105 wxFileName dir( dirname );
106 wxString parent = dir.GetPathWithSep();
107
108 EnsureGitFiles( parent );
109
110 if( dir.GetFullName() == wxT( ".git" ) || IsIgnored( parent, dir.GetFullName(), true )
111 || dirname.StartsWith( m_exclude ) || dirname.EndsWith( "-backups" ) )
112 {
113 return wxDIR_IGNORE;
114 }
115
116 m_files.emplace_back( wxFileName::DirName( dirname ) );
117 EnsureGitFiles( dirname + wxFileName::GetPathSeparator() );
118 return wxDIR_CONTINUE;
119 }
120
121private:
122 void EnsureGitFiles( const wxString& path )
123 {
124 if( m_gitIgnores.find( path ) != m_gitIgnores.end() )
125 return;
126
127 wxString gitignore = path + wxT( ".gitignore" );
128
129 if( wxFileExists( gitignore ) )
130 {
131 wxFileInputStream input( gitignore );
132 wxTextInputStream text( input, wxT( "\x9" ), wxConvUTF8 );
133
134 while( input.IsOk() && !input.Eof() )
135 {
136 wxString line = text.ReadLine();
137
138 line.Trim().Trim( false );
139
140 if( line.IsEmpty() || line.StartsWith( wxT( "#" ) ) )
141 continue;
142
143 m_gitIgnores[path].push_back( line );
144 }
145
146 m_files.emplace_back( wxFileName( gitignore ) );
147 }
148 else
149 {
150 m_gitIgnores[path] = {};
151 }
152
153 wxString gitattributes = path + wxT( ".gitattributes" );
154
155 if( wxFileExists( gitattributes ) )
156 m_files.emplace_back( wxFileName( gitattributes ) );
157 }
158
159 bool IsIgnored( const wxString& path, const wxString& name, bool isDir )
160 {
161 auto it = m_gitIgnores.find( path );
162
163 if( it == m_gitIgnores.end() )
164 return false;
165
166 for( const wxString& pattern : it->second )
167 {
168 bool dirOnly = pattern.EndsWith( wxT( "/" ) );
169 wxString pat = dirOnly ? pattern.substr( 0, pattern.length() - 1 ) : pattern;
170
171 if( dirOnly && !isDir )
172 continue;
173
174 if( wxMatchWild( pat, name ) )
175 return true;
176 }
177
178 return false;
179 }
180
181 std::vector<wxFileName>& m_files;
182 wxString m_exclude;
183 std::unordered_map<wxString, std::vector<wxString>> m_gitIgnores;
184};
185
186
187std::vector<wxFileName> PROJECT_TEMPLATE::GetFileList()
188{
189 std::vector<wxFileName> files;
190 FILE_TRAVERSER sink( files, m_metaPath.GetPath() );
191 wxDir dir( m_basePath.GetPath() );
192
193 dir.Traverse( sink, wxEmptyString, ( wxDIR_FILES | wxDIR_DIRS ) );
194 return files;
195}
196
197
199{
200 return m_basePath.GetDirs()[m_basePath.GetDirCount() - 1];
201}
202
203
207
208
210{
211 return m_metaHtmlFile;
212}
213
214
216{
217 return m_metaIcon;
218}
219
220
221size_t PROJECT_TEMPLATE::GetDestinationFiles( const wxFileName& aNewProjectPath, std::vector<wxFileName>& aDestFiles )
222{
223 std::vector<wxFileName> srcFiles = GetFileList();
224
225 // Find the template file name base. this is the name of the .pro template file
226 wxString basename;
227 bool multipleProjectFilesFound = false;
228
229 for( wxFileName& file : srcFiles )
230 {
231 if( file.GetExt() == FILEEXT::ProjectFileExtension || file.GetExt() == FILEEXT::LegacyProjectFileExtension )
232 {
233 if( !basename.IsEmpty() && basename != file.GetName() )
234 multipleProjectFilesFound = true;
235
236 basename = file.GetName();
237 }
238 }
239
240 if( multipleProjectFilesFound )
241 basename = GetPrjDirName();
242
243 for( wxFileName& srcFile : srcFiles )
244 {
245 // Replace the template path
246 wxFileName destFile = srcFile;
247
248 // Replace the template filename with the project filename for the new project creation
249 wxString name = destFile.GetName();
250 name.Replace( basename, aNewProjectPath.GetName() );
251 destFile.SetName( name );
252
253 // Replace the template path with the project path.
254 wxString path = destFile.GetPathWithSep();
255 path.Replace( m_basePath.GetPathWithSep(), aNewProjectPath.GetPathWithSep() );
256 destFile.SetPath( path );
257
258 aDestFiles.push_back( destFile );
259 }
260
261 return aDestFiles.size();
262}
263
264
265bool PROJECT_TEMPLATE::CreateProject( wxFileName& aNewProjectPath, wxString* aErrorMsg )
266{
267 // CreateProject copy the files from template to the new project folder and renames files
268 // which have the same name as the template .kicad_pro file
269 bool result = true;
270
271 std::vector<wxFileName> srcFiles = GetFileList();
272
273 // Find the template file name base. this is the name of the .kicad_pro (or .pro) template
274 // file
275 wxString basename;
276 bool multipleProjectFilesFound = false;
277
278 for( wxFileName& file : srcFiles )
279 {
280 if( file.GetExt() == FILEEXT::ProjectFileExtension || file.GetExt() == FILEEXT::LegacyProjectFileExtension )
281 {
282 if( !basename.IsEmpty() && basename != file.GetName() )
283 multipleProjectFilesFound = true;
284
285 basename = file.GetName();
286 }
287 }
288
289 if( multipleProjectFilesFound )
290 basename = GetPrjDirName();
291
292 for( wxFileName& srcFile : srcFiles )
293 {
294 // Replace the template path
295 wxFileName destFile = srcFile;
296
297 // Replace the template filename with the project filename for the new project creation
298 wxString currname = destFile.GetName();
299
300 if( destFile.GetExt() == FILEEXT::DrawingSheetFileExtension )
301 {
302 // Don't rename drawing sheet definitions; they're often shared
303 }
304 else if( destFile.GetName().EndsWith( "-cache" ) || destFile.GetName().EndsWith( "-rescue" ) )
305 {
306 currname.Replace( basename, aNewProjectPath.GetName() );
307 }
308 else if( destFile.GetExt() == FILEEXT::LegacySymbolDocumentFileExtension
309 || destFile.GetExt() == FILEEXT::LegacySymbolLibFileExtension
310 // Footprint libraries are directories not files, so GetExt() won't work
311 || destFile.GetPath().EndsWith( '.' + FILEEXT::KiCadFootprintLibPathExtension ) )
312 {
313 // Don't rename project-specific libraries. This will break the library tables and
314 // cause broken links in the schematic/pcb.
315 }
316 else
317 {
318 currname.Replace( basename, aNewProjectPath.GetName() );
319 }
320
321 destFile.SetName( currname );
322
323 // Replace the template path with the project path for the new project creation
324 // but keep the sub directory name, if exists
325 wxString destpath = destFile.GetPathWithSep();
326 destpath.Replace( m_basePath.GetPathWithSep(), aNewProjectPath.GetPathWithSep() );
327
328 // Check to see if the path already exists, if not attempt to create it here.
329 if( !wxFileName::DirExists( destpath ) )
330 {
331 if( !wxFileName::Mkdir( destpath, 0777, wxPATH_MKDIR_FULL ) )
332 {
333 if( aErrorMsg )
334 {
335 if( !aErrorMsg->empty() )
336 *aErrorMsg += "\n";
337
338 wxString msg;
339
340 msg.Printf( _( "Cannot create folder '%s'." ), destpath );
341 *aErrorMsg += msg;
342 }
343
344 continue;
345 }
346 }
347
348 destFile.SetPath( destpath );
349
350 if( srcFile.FileExists() && !wxCopyFile( srcFile.GetFullPath(), destFile.GetFullPath() ) )
351 {
352 if( aErrorMsg )
353 {
354 if( !aErrorMsg->empty() )
355 *aErrorMsg += "\n";
356
357 wxString msg;
358
359 msg.Printf( _( "Cannot copy file '%s'." ), destFile.GetFullPath() );
360 *aErrorMsg += msg;
361 }
362
363 result = false;
364 }
365 }
366
367 return result;
368}
369
370
372{
373 wxFFileInputStream input( GetHtmlFile().GetFullPath() );
374 wxString separator( wxT( "\x9" ) );
375 wxTextInputStream text( input, separator, wxConvUTF8 );
376
377 /* Open HTML file and get the text between the title tags */
378 if( m_title == wxEmptyString )
379 {
380 int start = 0;
381 int finish = 0;
382 bool done = false;
383 bool hasStart = false;
384
385 while( input.IsOk() && !input.Eof() && !done )
386 {
387 wxString line = text.ReadLine();
388 wxString upperline = line.Clone().Upper();
389
390 start = upperline.Find( wxT( "<TITLE>" ) );
391 finish = upperline.Find( wxT( "</TITLE>" ) );
392 int length = finish - start - 7;
393
394 // find the opening tag
395 if( start != wxNOT_FOUND )
396 {
397 if( finish != wxNOT_FOUND )
398 {
399 m_title = line( start + 7, length );
400 done = true;
401 }
402 else
403 {
404 m_title = line.Mid( start + 7 );
405 hasStart = true;
406 }
407 }
408 else
409 {
410 if( finish != wxNOT_FOUND )
411 {
412 m_title += line.SubString( 0, finish - 1 );
413 done = true;
414 }
415 else if( hasStart )
416 m_title += line;
417 }
418 }
419
420 // Remove line endings
421 m_title.Replace( wxT( "\r" ), wxT( "" ) );
422 m_title.Replace( wxT( "\n" ), wxT( "" ) );
423
424 m_title.Trim( false ); // Trim from left
425 m_title.Trim(); // Trim from right
426 }
427
428 return &m_title;
429}
const char * name
virtual wxDirTraverseResult OnDir(const wxString &dirname) override
FILE_TRAVERSER(std::vector< wxFileName > &files, const wxString &exclude)
void EnsureGitFiles(const wxString &path)
virtual wxDirTraverseResult OnFile(const wxString &filename) override
std::unordered_map< wxString, std::vector< wxString > > m_gitIgnores
std::vector< wxFileName > & m_files
bool IsIgnored(const wxString &path, const wxString &name, bool isDir)
wxBitmap * GetIcon()
Get the 64px^2 icon for the project template.
size_t GetDestinationFiles(const wxFileName &aNewProjectPath, std::vector< wxFileName > &aDestFiles)
Fetch the list of destination files to be copied when the new project is created.
wxFileName m_metaHtmlFile
PROJECT_TEMPLATE(const wxString &aPath)
Create a new project instance from aPath.
std::vector< wxFileName > GetFileList()
Get a vector list of filenames for the template.
~PROJECT_TEMPLATE()
Non-virtual destructor (so no derived classes)
wxFileName GetHtmlFile()
Get the full Html filename for the project template.
wxString * GetTitle()
Get the title of the project (extracted from the html title tag)
bool CreateProject(wxFileName &aNewProjectPath, wxString *aErrorMsg=nullptr)
Copies and renames all template files to create a new project.
wxFileName m_metaIconFile
wxString GetPrjDirName()
Get the dir name of the project template (i.e.
#define _(s)
static const std::string ProjectFileExtension
static const std::string LegacyProjectFileExtension
static const std::string LegacySymbolLibFileExtension
static const std::string LockFilePrefix
static const std::string DrawingSheetFileExtension
static const std::string LegacySymbolDocumentFileExtension
static const std::string KiCadFootprintLibPathExtension
#define SEP()
#define METAFILE_ICON
An optional png icon, exactly 64px x 64px which is used in the template selector if present.
#define METADIR
A directory which contains information about the project template and does not get copied.
#define METAFILE_INFO_HTML
A required html formatted file which contains information about the project template.
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.