42_minishell/main.c
Etienne Rey-bethbeder 0b56e95868 _
2023-04-14 16:17:35 +02:00

116 lines
2.8 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/16 15:16:14 by cchauvet #+# #+# */
/* Updated: 2023/04/14 16:10:20 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "data/data.h"
#include "env/env.h"
#include "libftx/libft/libft.h"
#include "libftx/libft/list.h"
#include "libftx/libftx.h"
#include "bozoshell.h"
#include "signal/signal.h"
#include <stdlib.h>
static char *ft_get_user_input(void)
{
char *line;
char *prompt;
char *pwd;
pwd = get_pwd(2);
if (pwd == NULL)
return (NULL);
prompt = ft_strmerger(2, pwd, "$ ");
free(pwd);
if (prompt == NULL)
{
ft_eprintf("bozoshell: malloc failed\n");
return (NULL);
}
line = readline(prompt);
if (line != NULL && ft_strcmp(line, "") != 0)
add_history(line);
free(prompt);
if (line == NULL)
ft_printf("exit\n");
return (line);
}
static int ft_minishell(t_data *data, char *line)
{
char *line_clean;
if (ft_syntax_verif(data, line))
return (0);
line_clean = ft_formater(data, line);
if (line_clean == NULL || line_clean[0] == '\0')
return (0);
if (ft_cmds_parser(data, line_clean))
{
free(line_clean);
return (0);
}
free(line_clean);
if (ft_cmds_executor(data) == 1)
return (1);
ft_lstiter(*data->cmds, ft_cmdwaiter);
ft_lstclear(data->cmds, ft_cmddel);
return (0);
}
int ft_init_data(t_data *data, char **env)
{
data->exit_code = ft_get_exit_code();
data->cmds = malloc(sizeof(t_cmd *));
if (data->cmds == NULL)
{
ft_eprintf("bozoshell: malloc failed\n");
return (1);
}
*data->cmds = NULL;
data->env = init_env(env);
if (data->env == NULL)
{
ft_eprintf("bozoshell: malloc failed\n");
free(data->cmds);
return (1);
}
return (0);
}
int main(int ac, char **av, char **env)
{
t_data data;
char *line;
(void) ac;
(void) av;
signal(SIGINT, ft_ctrlc);
signal(SIGQUIT, SIG_IGN);
if (ft_init_data(&data, env))
return (1);
line = ft_get_user_input();
while (line != NULL)
{
if (ft_minishell(&data, line) == 1)
break ;
free(line);
line = ft_get_user_input();
if (line == NULL)
break ;
}
ft_lstclear(data.cmds, ft_cmddel);
free(data.cmds);
ft_lstclear(data.env, env_del);
free(data.env);
return (*data.exit_code);
}