Shell: Add unalias builtin

Add shell unalias builtin to remove aliases
This commit is contained in:
TheFightingCatfish 2021-07-13 04:00:25 +08:00 committed by Ali Mohammad Pur
parent 5140994c69
commit 72e661b542
Notes: sideshowbarker 2024-07-18 09:08:45 +09:00
3 changed files with 57 additions and 3 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, the SerenityOS developers.
* Copyright (c) 2020-2021, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@ -67,6 +67,45 @@ int Shell::builtin_alias(int argc, const char** argv)
return fail ? 1 : 0;
}
int Shell::builtin_unalias(int argc, const char** argv)
{
bool remove_all { false };
Vector<const char*> arguments;
Core::ArgsParser parser;
parser.set_general_help("Remove alias from the list of aliases");
parser.add_option(remove_all, "Remove all aliases", nullptr, 'a');
parser.add_positional_argument(arguments, "List of aliases to remove", "alias", Core::ArgsParser::Required::No);
if (!parser.parse(argc, const_cast<char**>(argv), Core::ArgsParser::FailureBehavior::PrintUsage))
return 1;
if (remove_all) {
m_aliases.clear();
cache_path();
return 0;
}
if (arguments.is_empty()) {
warnln("unalias: not enough arguments");
parser.print_usage(stderr, argv[0]);
return 1;
}
bool failed { false };
for (auto& argument : arguments) {
if (!m_aliases.contains(argument)) {
warnln("unalias: {}: alias not found", argument);
failed = true;
continue;
}
m_aliases.remove(argument);
remove_entry_from_cache(argument);
}
return failed ? 1 : 0;
}
int Shell::builtin_bg(int argc, const char** argv)
{
int job_id = -1;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, the SerenityOS developers.
* Copyright (c) 2020-2021, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@ -1362,6 +1362,19 @@ void Shell::add_entry_to_cache(const String& entry)
cached_path.insert(index, entry);
}
void Shell::remove_entry_from_cache(const String& entry)
{
size_t index { 0 };
auto match = binary_search(
cached_path.span(),
entry,
&index,
[](const auto& a, const auto& b) { return strcmp(a.characters(), b.characters()); });
if (match)
cached_path.remove(index);
}
void Shell::highlight(Line::Editor& editor) const
{
auto line = editor.line();

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, the SerenityOS developers.
* Copyright (c) 2020-2021, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
@ -30,6 +30,7 @@
__ENUMERATE_SHELL_BUILTIN(exit) \
__ENUMERATE_SHELL_BUILTIN(export) \
__ENUMERATE_SHELL_BUILTIN(glob) \
__ENUMERATE_SHELL_BUILTIN(unalias) \
__ENUMERATE_SHELL_BUILTIN(unset) \
__ENUMERATE_SHELL_BUILTIN(history) \
__ENUMERATE_SHELL_BUILTIN(umask) \
@ -287,6 +288,7 @@ private:
Optional<int> resolve_job_spec(const String&);
void cache_path();
void add_entry_to_cache(const String&);
void remove_entry_from_cache(const String&);
void stop_all_jobs();
const Job* m_current_job { nullptr };
LocalFrame* find_frame_containing_local_variable(const String& name);