KiCad PCB EDA Suite
Loading...
Searching...
No Matches
project_archiver.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) 2020 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 along
17 * with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include <memory>
21#include <wx/dir.h>
22#include <wx/filedlg.h>
23#include <wx/fs_zip.h>
24#include <wx/uri.h>
25#include <wx/wfstream.h>
26#include <wx/zipstrm.h>
27
28#include <core/arraydim.h>
29#include <macros.h>
31#include <reporter.h>
33#include <wxstream_helper.h>
34#include <wx/log.h>
35
36
37#define ZipFileExtension wxT( "zip" )
38
39
41{
42}
43
44
45// Unarchive Files code comes from wxWidgets sample/archive/archive.cpp
46bool PROJECT_ARCHIVER::Unarchive( const wxString& aSrcFile, const wxString& aDestDir,
47 REPORTER& aReporter )
48{
49 wxFFileInputStream stream( aSrcFile );
50
51 if( !stream.IsOk() )
52 {
53 aReporter.Report( _( "Could not open archive file." ), RPT_SEVERITY_ERROR );
54 return false;
55 }
56
57 const wxArchiveClassFactory* archiveClassFactory =
58 wxArchiveClassFactory::Find( aSrcFile, wxSTREAM_FILEEXT );
59
60 if( !archiveClassFactory )
61 {
62 aReporter.Report( _( "Invalid archive file format." ), RPT_SEVERITY_ERROR );
63 return false;
64 }
65
66 std::unique_ptr<wxArchiveInputStream> archiveStream( archiveClassFactory->NewStream( stream ) );
67
68 wxString fileStatus;
69
70 for( wxArchiveEntry* entry = archiveStream->GetNextEntry(); entry;
71 entry = archiveStream->GetNextEntry() )
72 {
73 fileStatus.Printf( _( "Extracting file '%s'." ), entry->GetName() );
74 aReporter.Report( fileStatus, RPT_SEVERITY_INFO );
75
76 wxString fullname = aDestDir + entry->GetName();
77
78 // Ensure the target directory exists and create it if not
79 wxString t_path = wxPathOnly( fullname );
80
81 if( !wxDirExists( t_path ) )
82 {
83 wxFileName::Mkdir( t_path, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL );
84 }
85
86 // Directory entries need only be created, not extracted (0 size)
87 if( entry->IsDir() )
88 continue;
89
90
91 wxTempFileOutputStream outputFileStream( fullname );
92
93 if( CopyStreamData( *archiveStream, outputFileStream, entry->GetSize() ) )
94 outputFileStream.Commit();
95 else
96 aReporter.Report( _( "Error extracting file!" ), RPT_SEVERITY_ERROR );
97
98 // Now let's set the filetimes based on what's in the zip
99 wxFileName outputFileName( fullname );
100 wxDateTime fileTime = entry->GetDateTime();
101 // For now we set access, mod, create to the same datetime
102 // create (third arg) is only used on Windows
103 outputFileName.SetTimes( &fileTime, &fileTime, &fileTime );
104 }
105
106 aReporter.Report( wxT( "Extracted project." ), RPT_SEVERITY_INFO );
107 return true;
108}
109
110
111bool PROJECT_ARCHIVER::Archive( const wxString& aSrcDir, const wxString& aDestFile,
112 REPORTER& aReporter, bool aVerbose, bool aIncludeExtraFiles )
113{
114 // List of file extensions that are always archived
115 static const wxChar* extensionList[] = {
116 wxT( "*.kicad_pro" ),
117 wxT( "*.kicad_prl" ),
118 wxT( "*.kicad_sch" ),
119 wxT( "*.kicad_sym" ),
120 wxT( "*.kicad_pcb" ),
121 wxT( "*.kicad_mod" ),
122 wxT( "*.kicad_dru" ),
123 wxT( "*.kicad_wks" ),
124 wxT( "*.wbk" ),
125 wxT( "fp-lib-table" ),
126 wxT( "sym-lib-table" )
127 };
128
129 // List of additional file extensions that are only archived when aIncludeExtraFiles is true
130 static const wxChar* extraExtensionList[] = {
131 wxT( "*.pro" ), // Legacy project files
132 wxT( "*.sch" ), // Legacy schematic files
133 wxT( "*.lib" ), wxT( "*.dcm" ), // Legacy schematic library files
134 wxT( "*.cmp" ),
135 wxT( "*.brd" ), // Legacy PCB files
136 wxT( "*.mod" ), // Legacy footprint library files
137 wxT( "*.stp" ), wxT( "*.step" ), // 3d files
138 wxT( "*.wrl" ),
139 wxT( "*.g?" ), wxT( "*.g??" ), // Gerber files
140 wxT( "*.gm??"), // Some gerbers like .gm12 (from protel export)
141 wxT( "*.gbrjob" ), // Gerber job files
142 wxT( "*.pos" ), // our position files
143 wxT( "*.drl" ), wxT( "*.nc" ), wxT( "*.xnc" ), // Fab drill files
144 wxT( "*.d356" ),
145 wxT( "*.rpt" ),
146 wxT( "*.net" ),
147 wxT( "*.py" ),
148 wxT( "*.pdf" ),
149 wxT( "*.txt" ),
150 wxT( "*.cir" ), wxT( "*.sub" ), wxT( "*.model" ), // SPICE files
151 wxT( "*.ibs" )
152 };
153
154 bool success = true;
155 wxString msg;
156 wxString oldCwd = wxGetCwd();
157
158 wxSetWorkingDirectory( aSrcDir );
159
160 wxFFileOutputStream ostream( aDestFile );
161
162 if( !ostream.IsOk() ) // issue to create the file. Perhaps not writable dir
163 {
164 msg.Printf( _( "Failed to create file '%s'." ), aDestFile );
165 aReporter.Report( msg, RPT_SEVERITY_ERROR );
166 return false;
167 }
168
169 wxZipOutputStream zipstream( ostream, -1, wxConvUTF8 );
170
171 // Build list of filenames to put in zip archive
172 wxString currFilename;
173
174 wxArrayString files;
175
176 for( unsigned ii = 0; ii < arrayDim( extensionList ); ii++ )
177 wxDir::GetAllFiles( aSrcDir, &files, extensionList[ii] );
178
179 if( aIncludeExtraFiles )
180 {
181 for( unsigned ii = 0; ii < arrayDim( extraExtensionList ); ii++ )
182 wxDir::GetAllFiles( aSrcDir, &files, extraExtensionList[ii] );
183 }
184
185 for( unsigned ii = 0; ii < files.GetCount(); ++ii )
186 {
187 if( files[ii].EndsWith( wxS( ".ibs" ) ) )
188 {
189 wxFileName package( files[ ii ] );
190 package.MakeRelativeTo( aSrcDir );
191 package.SetExt( wxS( "pkg" ) );
192
193 if( package.Exists() )
194 files.push_back( package.GetFullName() );
195 }
196 }
197
198 files.Sort();
199
200 unsigned long uncompressedBytes = 0;
201
202 // Our filename collector can store duplicate filenames. for instance *.gm2
203 // matches both *.g?? and *.gm??.
204 // So skip duplicate filenames (they are sorted, so it is easy.
205 wxString lastStoredFile;
206
207 for( unsigned ii = 0; ii < files.GetCount(); ii++ )
208 {
209 if( lastStoredFile == files[ii] ) // duplicate name: already stored
210 continue;
211
212 lastStoredFile = files[ii];
213
214 wxFileSystem fsfile;
215
216 wxFileName curr_fn( files[ii] );
217 curr_fn.MakeRelativeTo( aSrcDir );
218 currFilename = curr_fn.GetFullPath();
219
220 // Read input file and add it to the zip file:
221 wxFSFile* infile = fsfile.OpenFile( wxFileSystem::FileNameToURL( curr_fn ) );
222
223 if( infile )
224 {
225 zipstream.PutNextEntry( currFilename, infile->GetModificationTime() );
226 infile->GetStream()->Read( zipstream );
227 zipstream.CloseEntry();
228
229 uncompressedBytes += infile->GetStream()->GetSize();
230
231 if( aVerbose )
232 {
233 msg.Printf( _( "Archived file '%s'." ), currFilename );
234 aReporter.Report( msg, RPT_SEVERITY_INFO );
235 }
236
237 delete infile;
238 }
239 else
240 {
241 if( aVerbose )
242 {
243 msg.Printf( _( "Failed to archive file '%s'." ), currFilename );
244 aReporter.Report( msg, RPT_SEVERITY_ERROR );
245 }
246
247 success = false;
248 }
249 }
250
251 auto reportSize =
252 []( unsigned long aSize ) -> wxString
253 {
254 constexpr float KB = 1024.0;
255 constexpr float MB = KB * 1024.0;
256
257 if( aSize >= MB )
258 return wxString::Format( wxT( "%0.2f MB" ), aSize / MB );
259 else if( aSize >= KB )
260 return wxString::Format( wxT( "%0.2f KB" ), aSize / KB );
261 else
262 return wxString::Format( wxT( "%lu bytes" ), aSize );
263 };
264
265 size_t zipBytesCnt = ostream.GetSize();
266
267 if( zipstream.Close() )
268 {
269 msg.Printf( _( "Zip archive '%s' created (%s uncompressed, %s compressed)." ),
270 aDestFile,
271 reportSize( uncompressedBytes ),
272 reportSize( zipBytesCnt ) );
273 aReporter.Report( msg, RPT_SEVERITY_INFO );
274 }
275 else
276 {
277 msg.Printf( wxT( "Failed to create file '%s'." ), aDestFile );
278 aReporter.Report( msg, RPT_SEVERITY_ERROR );
279 success = false;
280 }
281
282 wxSetWorkingDirectory( oldCwd );
283 return success;
284}
constexpr std::size_t arrayDim(T const (&)[N]) noexcept
Returns # of elements in an array.
Definition: arraydim.h:31
bool Archive(const wxString &aSrcDir, const wxString &aDestFile, REPORTER &aReporter, bool aVerbose=true, bool aIncludeExtraFiles=false)
Creates an archive of the project.
bool Unarchive(const wxString &aSrcFile, const wxString &aDestDir, REPORTER &aReporter)
Extracts an archive of the current project over existing files Warning: this will overwrite files in ...
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:71
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
#define _(s)
This file contains miscellaneous commonly used macros and functions.
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_INFO
static const std::vector< std::string > extensionList
Definition of file extensions used in Kicad.
static bool CopyStreamData(wxInputStream &inputStream, wxOutputStream &outputStream, wxFileOffset size)