Skip to content

Instantly share code, notes, and snippets.

@su8
Created December 3, 2025 09:54
Show Gist options
  • Select an option

  • Save su8/27b438b568dd66eb4977d56ed4af553a to your computer and use it in GitHub Desktop.

Select an option

Save su8/27b438b568dd66eb4977d56ed4af553a to your computer and use it in GitHub Desktop.
1.diff
70a71
> std::vector<char*> splitArgs(const std::string &cmd);
187a189,203
> // Split a string by spaces into arguments
> std::vector<char*> splitArgs(const std::string &cmd) {
> std::istringstream iss(cmd);
> std::string token;
> std::vector<char*> args;
> while (iss >> token) {
> char *arg = new char[token.size() + 1];
> std::strcpy(arg, token.c_str());
> args.push_back(arg);
> }
> args.push_back(nullptr); // execvp expects null-terminated array
> return args;
> }
>
> // Function to expand environment variables in a string
190c206,207
< std::regex envPattern(R"(\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?)");
---
> // Pattern matches $VAR or ${VAR}
> std::regex envPattern(R"(\$([A-Za-z_][A-Za-z0-9_]*)|\$\{([A-Za-z_][A-Za-z0-9_]*)\})");
192,197c209,217
< auto start = result.cbegin();
< while (std::regex_search(start, result.cend(), match, envPattern)) {
< const char *val = getenv(match[1].str().c_str());
< std::string replacement = val ? val :"";
< result.replace(match.position(0), match.length(0), replacement);
< start = result.cbegin();
---
> auto searchStart = result.cbegin();
> // Search and replace all matches
> while (std::regex_search(searchStart, result.cend(), match, envPattern)) {
> std::string varName = match[1].matched ? match[1].str() : match[2].str();
> const char *envValue = std::getenv(varName.c_str());
> // Replace with value or empty string if not found
> result.replace(match.position(0), match.length(0), envValue ? envValue : "");
> // Move search start forward
> searchStart = result.cbegin() + match.position(0) + (envValue ? std::string(envValue).length() : 0);
454a475,477
> // Expand variables in command
> std::string expanded = expandEnvVars(commands[i]));
> std::vector<char *> args = splitArgs(expanded);
458c481
< if (fd < 0) { perror("open infile"); exit(1); }
---
> if (fd < 0) { perror("open infile"); exit(EXIT_FAILURE); }
465c488
< if (fd < 0) { perror("open outfile"); exit(1); }
---
> if (fd < 0) { perror("open outfile"); exit(EXIT_FAILURE); }
470c493,494
< if (execvp(commands[i].args[0], commands[i].args.data()) == -1) {
---
> if (!args.empty() && args[0]) {
> if (execvp(args[0], args.data()) == -1) {
472c496,497
< exit(1);
---
> exit(EXIT_FAILURE);
> }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment