1+ #ifndef NODEGIT_RUN_CMD_H
2+ #define NODEGIT_RUN_CMD_H
3+
4+ #include < iostream>
5+ #include < cstdio>
6+ #include < iostream>
7+ #include < stdexcept>
8+ #include < string>
9+ #include < array>
10+ #include " cmd.h"
11+
12+ namespace nodegit {
13+ // TODO:
14+ // This is just a first testing version to run commands in MacOS, Linux and Win32
15+ namespace runcommand {
16+ /* *
17+ * \brief Executes a command.
18+ *
19+ * \param cmd object storing all the information needed to execute a command. Result
20+ * of the execution will also be stored here.
21+ * \return true if command execution succeeded; false otherwise.
22+ */
23+ bool exec (Cmd *cmd) {
24+ // TODO: sanitize path
25+ assert (cmd != nullptr );
26+ std::string cwd = cmd->GetEnv (Cmd::Env::kCWD );
27+ std::string cmdCwd = cwd.empty () ? std::string (" " ) : std::string (" cd " ).append (cwd).append (" && " );
28+ std::string cmdArgs = cmd->Args ();
29+ std::string finalCmdArgs = cmdArgs.empty () ? std::string (" " ) : std::string (" " ).append (cmdArgs);
30+ std::string cmdRedirectErr = cmd->GetRedirectStdErr () ? " 2>&1" : std::string (" " );
31+ std::string finalCmd = cmdCwd + cmd->Command () + finalCmdArgs + cmdRedirectErr;
32+
33+ #ifdef WIN32
34+ auto pipe = _popen (finalCmd.c_str (), " r" );
35+ #else
36+ auto pipe = popen (finalCmd.c_str (), " r" );
37+ #endif
38+ if (!pipe) {
39+ cmd->errorMsg = " popen() failed!" ;
40+ return false ;
41+ }
42+
43+ std::array<char , 128 > buffer {};
44+ while (!feof (pipe)) {
45+ if (fgets (buffer.data (), 128 , pipe) != nullptr )
46+ cmd->out += buffer.data ();
47+ }
48+ #ifdef WIN32
49+ auto rc = _pclose (pipe);
50+ #else
51+ auto rc = pclose (pipe);
52+ #endif
53+
54+ if (rc != EXIT_SUCCESS) {
55+ cmd->errorMsg = " pclose() failed!" ;
56+ return false ;
57+ }
58+ return true ;
59+ }
60+ } // namespace runcommand
61+ } // namespace nodegit
62+ #endif // NODEGIT_RUN_CMD_H
0 commit comments