KiCad PCB EDA Suite
Loading...
Searching...
No Matches
jobs_runner.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) 2024 Mark Roszko <[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 modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * 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, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <common.h>
22#include <cli/exit_codes.h>
23#include <jobs_runner.h>
24#include <jobs/job_registry.h>
25#include <jobs/jobset.h>
29#include <kiway.h>
30#include <kiway_mail.h>
32#include <reporter.h>
33#include <optional>
34#include <wx/process.h>
35#include <wx/txtstrm.h>
36#include <wx/sstream.h>
37#include <wx/wfstream.h>
38#include <wx/mstream.h>
39#include <wx/tokenzr.h>
40#include <gestfich.h>
41
42JOBS_RUNNER::JOBS_RUNNER( KIWAY* aKiway, JOBSET* aJobsFile, PROJECT* aProject,
43 REPORTER& aReporter, JOBS_PROGRESS_REPORTER* aProgressReporter ) :
44 m_kiway( aKiway ),
45 m_jobsFile( aJobsFile ),
46 m_reporter( aReporter ),
47 m_progressReporter( aProgressReporter ),
48 m_project( aProject )
49{
50}
51
52
54{
55 bool success = true;
56
57 for( JOBSET_DESTINATION& destination : m_jobsFile->GetDestinations() )
58 success &= RunJobsForDestination( &destination, aBail );
59
60 return success;
61}
62
63
64int JOBS_RUNNER::runSpecialExecute( const JOBSET_JOB* aJob, REPORTER* aReporter, PROJECT* aProject )
65{
66 JOB_SPECIAL_EXECUTE* specialJob = static_cast<JOB_SPECIAL_EXECUTE*>( aJob->m_job.get() );
67 wxString cmd = ExpandEnvVarSubstitutions( specialJob->m_command, m_project );
68
69 aReporter->Report( cmd, RPT_SEVERITY_INFO );
70 aReporter->Report( wxEmptyString, RPT_SEVERITY_INFO );
71
72 wxProcess process;
73 process.Redirect();
74
76
77 wxInputStream* inputStream = process.GetInputStream();
78 wxInputStream* errorStream = process.GetErrorStream();
79
80 // Reads wxInputStream into a wxMemoryBuffer
81 auto streamToBuf = []( wxInputStream& aIs )
82 {
83 wxMemoryOutputStream memOut;
84 aIs >> memOut;
85
86 wxMemoryBuffer buf;
87 buf.AppendData( memOut.GetOutputStreamBuffer()->GetBufferStart(),
88 memOut.GetOutputStreamBuffer()->GetIntPosition() );
89
90 return buf;
91 };
92
93 if( inputStream && errorStream )
94 {
95 wxMemoryBuffer memInBuf = streamToBuf( *inputStream );
96 wxMemoryBuffer memErrBuf = streamToBuf( *errorStream );
97
98 if( !memInBuf.IsEmpty() )
99 {
100 wxString str = wxString::FromUTF8( memInBuf, memInBuf.GetDataLen() );
101 wxStringTokenizer tokenizer( str, "\r\n" );
102
103 while( tokenizer.HasMoreTokens() )
104 aReporter->Report( tokenizer.GetNextToken(), RPT_SEVERITY_INFO );
105 }
106
107 if( !memErrBuf.IsEmpty() )
108 {
109 wxString str = wxString::FromUTF8( memErrBuf, memErrBuf.GetDataLen() );
110 wxStringTokenizer tokenizer( str, "\r\n" );
111
112 while( tokenizer.HasMoreTokens() )
113 aReporter->Report( tokenizer.GetNextToken(), RPT_SEVERITY_ERROR );
114 }
115
116 if( specialJob->m_recordOutput )
117 {
118 if( specialJob->GetConfiguredOutputPath().IsEmpty() )
119 {
120 wxFileName fn( aJob->m_id );
121 fn.SetExt( wxT( "log" ) );
122 specialJob->SetConfiguredOutputPath( fn.GetFullPath() );
123 }
124
125 wxFFileOutputStream procOutput( specialJob->GetFullOutputPath( aProject ) );
126
127 if( !procOutput.IsOk() )
129
130 procOutput.WriteAll( memInBuf, memInBuf.GetDataLen() );
131 }
132 }
133
134 if( specialJob->m_ignoreExitcode )
135 return CLI::EXIT_CODES::OK;
136
137 return result;
138}
139
140
142 std::vector<wxString>& aPathsWritten )
143{
144 wxString source = ExpandEnvVarSubstitutions( aJob->m_source, aProject );
145
146 if( source.IsEmpty() )
148
149 wxString projectPath = aProject->GetProjectPath();
150 wxFileName sourceFn( source );
151 sourceFn.MakeAbsolute( projectPath );
152
153 wxFileName destFn( aJob->GetFullOutputPath( aProject ) );
154
155 if( !aJob->m_dest.IsEmpty() )
156 destFn.AppendDir( ExpandEnvVarSubstitutions( aJob->m_dest, aProject ) );
157
158 wxString errors;
159 bool success = CopyFilesOrDirectory( sourceFn.GetFullPath(), destFn.GetFullPath(), aJob->m_overwriteDest,
160 errors, aPathsWritten );
161
162 if( !success )
164
165 if( aJob->m_generateErrorOnNoCopy && aPathsWritten.empty() )
167
168 return CLI::EXIT_CODES::OK;
169}
170
171
172int JOBS_RUNNER::runSpecialArchive( const JOBSET_JOB* aJob, REPORTER* aReporter, PROJECT* aProject )
173{
174 JOB_SPECIAL_ARCHIVE* archiveJob = static_cast<JOB_SPECIAL_ARCHIVE*>( aJob->m_job.get() );
175
176 if( archiveJob->GetConfiguredOutputPath().IsEmpty() )
177 archiveJob->SetConfiguredOutputPath( wxT( "${PROJECTNAME}.zip" ) );
178
179 wxString zipFile = archiveJob->GetFullOutputPath( aProject );
180
181 if( !PROJECT_ARCHIVER::Archive( aProject->GetProjectPath(), zipFile, *aReporter, true,
182 archiveJob->m_includeExtraFiles ) )
183 {
185 }
186
187 return CLI::EXIT_CODES::OK;
188}
189
190
192{
193 bool genOutputs = true;
194 bool success = true;
195 std::vector<JOBSET_JOB> jobsForDestination = m_jobsFile->GetJobsForDestination( aDestination );
196 wxString msg;
197
198 wxFileName tmp;
199 tmp.AssignDir( wxFileName::GetTempDir() );
200 tmp.AppendDir( KIID().AsString() );
201
202 aDestination->m_lastRunSuccessMap.clear();
203 aDestination->m_lastRunReporters.clear();
204 aDestination->m_lastResolvedOutputPath.reset();
205
206 wxString tempDirPath = tmp.GetFullPath();
207
208 if( !wxFileName::Mkdir( tempDirPath, wxS_DIR_DEFAULT ) )
209 {
210 msg = wxString::Format( wxT( "Failed to create temporary directory %s" ), tempDirPath );
211 m_reporter.Report( msg, RPT_SEVERITY_ERROR );
212
213 aDestination->m_lastRunSuccess = false;
214
215 return false;
216 }
217
218 bool continueOuput = aDestination->m_outputHandler->OutputPrecheck();
219
220 if( !continueOuput )
221 {
222 msg = wxString::Format( wxT( "Destination precheck failed for destination %s" ),
223 aDestination->m_id );
224 m_reporter.Report( msg, RPT_SEVERITY_ERROR );
225
226 aDestination->m_lastRunSuccess = false;
227 return false;
228 }
229
230 msg += wxT( "|--------------------------------\n" );
231 msg += wxT( "| " );
232 msg += wxString::Format( wxT( "Running jobs for destination %s" ), aDestination->m_id );
233 msg += wxT( "\n" );
234 msg += wxT( "|--------------------------------\n" );
235
236 msg += wxString::Format( wxT( "|%-5s | %-50s\n" ), wxT( "No." ), wxT( "Description" ) );
237
238 int jobNum = 1;
239
240 for( const JOBSET_JOB& job : jobsForDestination )
241 {
242 msg += wxString::Format( wxT( "|%-5d | %-50s\n" ), jobNum, job.GetDescription() );
243 jobNum++;
244 }
245
246 msg += wxT( "|--------------------------------\n" );
247 msg += wxT( "\n" );
248 msg += wxT( "\n" );
249
250 m_reporter.Report( msg, RPT_SEVERITY_INFO );
251
252 std::vector<wxString> pathsWithOverwriteDisallowed;
253 std::vector<JOB_OUTPUT> outputs;
254
255 jobNum = 1;
256 int failCount = 0;
257 int successCount = 0;
258
259 wxSetEnv( OUTPUT_TMP_PATH_VAR_NAME, tempDirPath );
260
261 for( const JOBSET_JOB& job : jobsForDestination )
262 {
263 msg = wxT( "|--------------------------------\n" );
264
265 msg += wxString::Format( wxT( "| Running job %d: %s" ), jobNum, job.GetDescription() );
266
267 msg += wxT( "\n" );
268 msg += wxT( "|--------------------------------\n" );
269
270 m_reporter.Report( msg, RPT_SEVERITY_INFO );
271
273 {
274 msg.Printf( _( "Running job %d: %s" ), jobNum, job.GetDescription() );
275 m_progressReporter->AdvanceJob( msg );
276 m_progressReporter->KeepRefreshing();
277 }
278
279 jobNum++;
280
281 KIWAY::FACE_T iface = JOB_REGISTRY::GetKifaceType( job.m_type );
282
283 job.m_job->SetTempOutputDirectory( tempDirPath );
284
285 REPORTER* targetReporter = &m_reporter;
286
287 if( targetReporter == &NULL_REPORTER::GetInstance() )
288 {
289 aDestination->m_lastRunReporters[job.m_id] =
290 std::make_shared<JOBSET_OUTPUT_REPORTER>( tempDirPath, m_progressReporter );
291
292 targetReporter = aDestination->m_lastRunReporters[job.m_id].get();
293 }
294
295 // Use a redirect reporter so we don't have error flags set after running previous jobs
296 REDIRECT_REPORTER isolatedReporter( targetReporter );
298
299 if( iface < KIWAY::KIWAY_FACE_COUNT )
300 {
301 result = m_kiway->ProcessJob( iface, job.m_job.get(), &isolatedReporter, m_progressReporter );
302 }
303 else
304 {
305 // special jobs
306 if( job.m_job->GetType() == "special_execute" )
307 {
308 result = runSpecialExecute( &job, &isolatedReporter, m_project );
309 }
310 else if( job.m_job->GetType() == "special_copyfiles" )
311 {
312 JOB_SPECIAL_COPYFILES* copyJob = static_cast<JOB_SPECIAL_COPYFILES*>( job.m_job.get() );
313 std::vector<wxString> pathsWritten;
314
315 result = runSpecialCopyFiles( copyJob, m_project, pathsWritten );
316
317 if( !copyJob->m_overwriteDest )
318 {
319 pathsWithOverwriteDisallowed.insert( pathsWithOverwriteDisallowed.end(), pathsWritten.begin(),
320 pathsWritten.end() );
321 }
322 }
323 else if( job.m_job->GetType() == "special_archive" )
324 {
325 result = runSpecialArchive( &job, &isolatedReporter, m_project );
326 }
327 else
328 {
329 msg = wxString::Format( wxT( "Unsupported job type '%s'" ), job.m_type );
330 isolatedReporter.Report( msg, RPT_SEVERITY_ERROR );
332 }
333 }
334
335 aDestination->m_lastRunSuccessMap[job.m_id] = ( result == CLI::EXIT_CODES::SUCCESS );
336
338 {
339 wxString msg_fmt = wxT( "\033[32;1m%s\033[0m\n" );
340 msg = wxString::Format( msg_fmt, _( "Job successful" ) );
341
342 successCount++;
343 }
344 else
345 {
346 wxString msg_fmt = wxT( "\033[31;1m%s\033[0m\n" );
347 msg = wxString::Format( msg_fmt, _( "Job failed" ) );
348
349 failCount++;
350 }
351
352 msg += wxT( "\n\n" );
353 m_reporter.Report( msg, RPT_SEVERITY_INFO );
354
356 {
357 success = false;
358
359 if( aBail )
360 break;
361 }
362 else if( result != CLI::EXIT_CODES::SUCCESS )
363 {
364 genOutputs = false;
365 success = false;
366
367 if( aBail )
368 break;
369 }
370 }
371
372 wxUnsetEnv( OUTPUT_TMP_PATH_VAR_NAME );
373
374 if( genOutputs )
375 {
376 success &= aDestination->m_outputHandler->HandleOutputs( tempDirPath, m_project, pathsWithOverwriteDisallowed,
377 outputs, aDestination->m_lastResolvedOutputPath );
378 }
379
380 aDestination->m_lastRunSuccess = success;
381
382 msg = wxString::Format( wxT( "\n\n\033[33;1m%d %s, %d %s\033[0m\n" ),
383 successCount,
384 wxT( "jobs succeeded" ),
385 failCount,
386 wxT( "job failed" ) );
387
388 m_reporter.Report( msg, RPT_SEVERITY_INFO );
389
390 return success;
391}
virtual bool OutputPrecheck()
Checks if the output process can proceed before doing anything else This can include user prompts.
Definition jobs_output.h:45
virtual bool HandleOutputs(const wxString &aBaseTempPath, PROJECT *aProject, const std::vector< wxString > &aPathsWithOverwriteDisallowed, const std::vector< JOB_OUTPUT > &aOutputsToHandle, std::optional< wxString > &aResolvedOutputPath)=0
bool RunJobsAllDestinations(bool aBail=false)
REPORTER & m_reporter
Definition jobs_runner.h:79
KIWAY * m_kiway
Definition jobs_runner.h:77
JOBSET * m_jobsFile
Definition jobs_runner.h:78
JOBS_PROGRESS_REPORTER * m_progressReporter
Definition jobs_runner.h:80
bool RunJobsForDestination(JOBSET_DESTINATION *aDestination, bool aBail=false)
int runSpecialCopyFiles(const JOB_SPECIAL_COPYFILES *aJob, PROJECT *aProject, std::vector< wxString > &aPathsWritten)
int runSpecialArchive(const JOBSET_JOB *aJob, REPORTER *aReporter, PROJECT *aProject)
PROJECT * m_project
Definition jobs_runner.h:81
int runSpecialExecute(const JOBSET_JOB *aJob, REPORTER *aReporter, PROJECT *aProject)
JOBS_RUNNER(KIWAY *aKiway, JOBSET *aJobsFile, PROJECT *aProject, REPORTER &aReporter, JOBS_PROGRESS_REPORTER *aProgressReporter)
static KIWAY::FACE_T GetKifaceType(const wxString &aName)
void SetConfiguredOutputPath(const wxString &aPath)
Sets the configured output path for the job, this path is always saved to file.
Definition job.cpp:157
wxString GetFullOutputPath(PROJECT *aProject) const
Returns the full output path for the job, taking into account the configured output path,...
Definition job.cpp:150
wxString GetConfiguredOutputPath() const
Returns the configured output path for the job.
Definition job.h:235
Definition kiid.h:46
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:311
FACE_T
Known KIFACE implementations.
Definition kiway.h:317
@ KIWAY_FACE_COUNT
Definition kiway.h:326
static REPORTER & GetInstance()
Definition reporter.cpp:179
static bool Archive(const wxString &aSrcDir, const wxString &aDestFile, REPORTER &aReporter, bool aVerbose=true, bool aIncludeExtraFiles=false)
Create an archive of the project.
Container for project specific data.
Definition project.h:63
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:183
REPORTER & Report(const wxString &aMsg, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) override
Report a string with a given severity.
Definition reporter.cpp:356
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:72
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:101
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition common.cpp:721
The common library.
#define _(s)
int ExecuteCommandThroughShell(const wxString &aCommand, wxProcess *aProcess)
Run a user-supplied command line through the platform shell so glob expansion, pipes,...
Definition gestfich.cpp:272
bool CopyFilesOrDirectory(const wxString &aSourcePath, const wxString &aDestDir, bool aAllowOverwrites, wxString &aErrors, std::vector< wxString > &aPathsWritten)
Definition gestfich.cpp:541
#define OUTPUT_TMP_PATH_VAR_NAME
static const int ERR_ARGS
Definition exit_codes.h:31
static const int OK
Definition exit_codes.h:30
static const int ERR_RC_VIOLATIONS
Rules check violation count was greater than 0.
Definition exit_codes.h:37
static const int SUCCESS
Definition exit_codes.h:29
static const int ERR_INVALID_OUTPUT_CONFLICT
Definition exit_codes.h:34
static const int ERR_UNKNOWN
Definition exit_codes.h:32
static PGM_BASE * process
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_INFO
std::unordered_map< wxString, std::shared_ptr< JOBSET_OUTPUT_REPORTER > > m_lastRunReporters
Definition jobset.h:142
std::shared_ptr< JOBS_OUTPUT_HANDLER > m_outputHandler
Definition jobset.h:136
std::optional< wxString > m_lastResolvedOutputPath
Definition jobset.h:143
std::optional< bool > m_lastRunSuccess
Definition jobset.h:140
std::unordered_map< wxString, std::optional< bool > > m_lastRunSuccessMap
Definition jobset.h:141
wxString m_id
Definition jobset.h:133
wxString m_id
Definition jobset.h:87
std::shared_ptr< JOB > m_job
Definition jobset.h:90
wxString result
Test unit parsing edge cases and error handling.