]> git.tdb.fi Git - builder.git/blob - source/externaltask.h
cb8464beab873ef24146b49a5ab02bd6a9aaa21c
[builder.git] / source / externaltask.h
1 #ifndef EXTERNALTASK_H_
2 #define EXTERNALTASK_H_
3
4 #include <string>
5 #include <vector>
6 #include <msp/fs/path.h>
7 #include <msp/io/pipe.h>
8 #include "task.h"
9
10 /**
11 Runs an external command.  A zero exit status is translated to a SUCCESS status
12 for the task, and anything else is treated as an error.  Output can optionally
13 be captured.
14 */
15 class ExternalTask: public Task
16 {
17 public:
18         enum Destination
19         {
20                 PASSTHROUGH,  //< Do not touch the stream
21                 CAPTURE,      //< Capture the stream
22                 IGNORE        //< Redirect the stream to oblivion
23         };
24
25         typedef std::vector<std::string> Arguments;
26
27 private:
28         Arguments argv;
29         Msp::FS::Path work_dir;
30         int pid;
31         int exit_code;
32         Destination stdout_dest;
33         Destination stderr_dest;
34         Msp::IO::Pipe *capture_pipe;
35         std::string output;
36
37 public:
38         /** Creates an ExternalTask with an argument array and an optional working
39         directory.  The first element of the argument array should be the command
40         name.  If the working directory is not specified, no chdir is done. */
41         ExternalTask(const Arguments &, const Msp::FS::Path & = Msp::FS::Path());
42
43         virtual ~ExternalTask();
44
45         virtual std::string get_command() const;
46         virtual void start();
47         virtual Status check();
48         virtual Status wait();
49 private:
50         Status do_wait(bool);
51
52 public:
53         /// Sets destination for stdout.  Has no effect after the task is started.
54         void set_stdout(Destination);
55
56         /// Sets destination for stderr.  Has no effect after the task is started.
57         void set_stderr(Destination);
58
59         /** Returns captured output, if any.  This may be called while the task is
60         still running, but it will always return all output. */
61         const std::string &get_output() const { return output; }
62
63         /** Executes a command and captures its output.  Stderr is ignored, but if
64         the command exits with a nonzero status, an exception is thrown. */
65         static std::string run_and_capture_output(const Arguments &, const Msp::FS::Path & = Msp::FS::Path());
66 };
67
68 #endif