minishell/src/get_command.c
Khaïs COLIN 6576c47b56
exec: command to toggle execution
Execution starts out being enabled. But it can be toggled on and off by using
the .exec command.
2025-04-15 15:17:51 +02:00

76 lines
2.2 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_command.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: khais <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/02/19 18:03:11 by khais #+# #+# */
/* Updated: 2025/04/09 14:03:39 by khais ### ########.fr */
/* */
/* ************************************************************************** */
// stdio must be included before readline
#include <stdio.h>
#include <readline/history.h>
#include <readline/readline.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include "libft.h"
#include "get_command.h"
/*
** remove one '\n' from the end of the string, if it exists
*/
static char *strip_newline(char *str)
{
size_t last_char_idx;
if (str == NULL)
return (NULL);
last_char_idx = ft_strlen(str) - 1;
if (str[last_char_idx] == '\n')
str[last_char_idx] = '\0';
return (str);
}
static char *handle_special_command(char *line, t_minishell *app)
{
if (line == NULL)
return (NULL);
if (ft_strcmp(".debug", line) == 0)
{
app->debug = !app->debug;
ft_printf("[dbg: %d]\n", (int)app->debug);
line[0] = '\0';
}
if (ft_strcmp(".exec", line) == 0)
{
app->exec = !app->exec;
ft_printf("[exec: %d]\n", (int)app->exec);
line[0] = '\0';
}
return (line);
}
/*
** get a command line using readline.
**
** returned buffer must be freed by caller.
** will add command to history if appropriate.
**
** Also handles special commands, which are not further processed.
*/
char *get_command(t_minishell *app)
{
char *line;
if (isatty(STDIN_FILENO))
line = readline("$ ");
else
line = strip_newline(get_next_line(STDIN_FILENO));
if (line != NULL && line[0] != '\0')
add_history(line);
return (handle_special_command(line, app));
}