env: Add -u option to unset environment variables

This commit is contained in:
Tim Ledbetter 2023-06-25 11:53:26 +01:00 committed by Andreas Kling
parent b9e7998b53
commit 6aa87e2119
Notes: sideshowbarker 2024-07-17 07:20:49 +09:00

View file

@ -17,24 +17,44 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
bool ignore_env = false;
StringView split_string {};
Vector<DeprecatedString> values;
Vector<DeprecatedString> values_to_set;
Vector<DeprecatedString> values_to_unset;
Core::ArgsParser args_parser;
args_parser.set_stop_on_first_non_option(true);
args_parser.add_option(ignore_env, "Start with an empty environment", "ignore-environment", 'i');
args_parser.add_option(split_string, "Process and split S into separate arguments; used to pass multiple arguments on shebang lines", "split-string", 'S', "S");
args_parser.add_option(Core::ArgsParser::Option {
.argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
.help_string = "Remove variable from the environment",
.long_name = "unset",
.short_name = 'u',
.value_name = "name",
.accept_value = [&values_to_unset](StringView value) {
values_to_unset.append(value);
return true;
},
});
args_parser.add_positional_argument(values, "Environment and commands", "env/command", Core::ArgsParser::Required::No);
args_parser.add_positional_argument(values_to_set, "Environment and commands", "env/command", Core::ArgsParser::Required::No);
args_parser.parse(arguments);
if (ignore_env)
if (ignore_env) {
clearenv();
} else {
for (auto const& value : values_to_unset) {
if (unsetenv(value.characters()) < 0) {
warnln("env: cannot unset '{}': {}", value, strerror(errno));
return 1;
}
}
}
size_t argv_start;
for (argv_start = 0; argv_start < values.size(); ++argv_start) {
if (values[argv_start].contains('=')) {
putenv(const_cast<char*>(values[argv_start].characters()));
for (argv_start = 0; argv_start < values_to_set.size(); ++argv_start) {
if (values_to_set[argv_start].contains('=')) {
putenv(const_cast<char*>(values_to_set[argv_start].characters()));
} else {
break;
}
@ -47,8 +67,8 @@ ErrorOr<int> serenity_main(Main::Arguments arguments)
}
}
for (size_t i = argv_start; i < values.size(); ++i) {
new_argv.append(values[i]);
for (size_t i = argv_start; i < values_to_set.size(); ++i) {
new_argv.append(values_to_set[i]);
}
if (new_argv.size() == 0) {