1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 08:27:45 +00:00

Shell: Refactor Shell::prompt to use GenericLexer to read the PROMPT var

This commit is contained in:
Adam Harald Jørgensen 2023-10-23 22:34:31 +02:00 committed by Ali Mohammad Pur
parent 1d26550370
commit 78b3703586

View file

@ -82,8 +82,7 @@ DeprecatedString Shell::prompt() const
if (m_next_scheduled_prompt_text.has_value()) if (m_next_scheduled_prompt_text.has_value())
return m_next_scheduled_prompt_text.release_value(); return m_next_scheduled_prompt_text.release_value();
auto build_prompt = [&]() -> DeprecatedString { auto const* ps1 = getenv("PROMPT");
auto* ps1 = getenv("PROMPT");
if (!ps1) { if (!ps1) {
if (uid == 0) if (uid == 0)
return "# "; return "# ";
@ -95,49 +94,46 @@ DeprecatedString Shell::prompt() const
} }
StringBuilder builder; StringBuilder builder;
for (char* ptr = ps1; *ptr; ++ptr) {
if (*ptr == '\\') { GenericLexer lexer { { ps1, strlen(ps1) } };
++ptr; while (!lexer.is_eof()) {
if (!*ptr) builder.append(lexer.consume_until('\\'));
if (!lexer.consume_specific('\\') || lexer.is_eof())
break; break;
switch (*ptr) {
case 'X': if (lexer.consume_specific('X')) {
builder.append("\033]0;"sv); builder.append("\033]0;"sv);
break;
case 'a': } else if (lexer.consume_specific('a')) {
builder.append(0x07); builder.append(0x07);
break;
case 'e': } else if (lexer.consume_specific('e')) {
builder.append(0x1b); builder.append(0x1b);
break;
case 'u': } else if (lexer.consume_specific('u')) {
builder.append(username); builder.append(username);
break;
case 'h': } else if (lexer.consume_specific('h')) {
builder.append({ hostname, strlen(hostname) }); builder.append({ hostname, strlen(hostname) });
break;
case 'w': { } else if (lexer.consume_specific('w')) {
DeprecatedString home_path = getenv("HOME"); DeprecatedString const home_path = getenv("HOME");
if (cwd.starts_with(home_path)) { if (cwd.starts_with(home_path)) {
builder.append('~'); builder.append('~');
builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length())); builder.append(cwd.substring_view(home_path.length(), cwd.length() - home_path.length()));
} else { } else {
builder.append(cwd); builder.append(cwd);
} }
break;
} } else if (lexer.consume_specific('p')) {
case 'p':
builder.append(uid == 0 ? '#' : '$'); builder.append(uid == 0 ? '#' : '$');
break;
} else {
lexer.consume();
} }
continue;
}
builder.append(*ptr);
} }
return builder.to_deprecated_string(); return builder.to_deprecated_string();
};
return build_prompt();
} }
DeprecatedString Shell::expand_tilde(StringView expression) DeprecatedString Shell::expand_tilde(StringView expression)