42_minishell/main.c

165 lines
3.4 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/16 15:16:14 by cchauvet #+# #+# */
/* Updated: 2023/02/24 11:04:40 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libftx/libftx.h"
#include "minishell.h"
#include <readline/readline.h>
static char *ft_get_user_input()
{
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("minishell: malloc failed\n");
return (NULL);
}
line = readline(prompt);
if (line != NULL && ft_strcmp(line, "") != 0)
add_history(line);
free(prompt);
return (line);
}
static int ft_minishell(t_data *data, char *line)
{
t_list **cmds;
char *line_clean;
int infile;
int outfile;
if (ft_syntatic_verif(data, line))
return (1);
line_clean = ft_normalizer(line);
if (line_clean == NULL)
return (1);
outfile = ft_outfile(data, line_clean);
if (outfile == -2)
{
free(line_clean);
return (0);
}
infile = ft_infile(data, line_clean);
if (infile == -2)
{
if (outfile > 2)
close(outfile);
free(line_clean);
return (0);
}
if (ft_gen_exit_code_var(data))
{
if (outfile > 2)
close(outfile);
if (infile > 2)
close(infile);
ft_lstclear(cmds, ft_cmddel);
free(cmds);
free(line_clean);
return (1);
}
cmds = ft_parse_cmds(data, line_clean, infile, outfile);
if (cmds == NULL)
{
if (outfile > 2)
close(outfile);
if (infile > 2)
close(infile);
ft_lstclear(cmds, ft_cmddel);
free(cmds);
free(line_clean);
return (1);
}
if (ft_cmds_executor(data, cmds))
{
if (outfile > 2)
close(outfile);
if (infile > 2)
close(infile);
ft_lstclear(cmds, ft_cmddel);
free(cmds);
free(line_clean);
return (1);
}
ft_lstclear(cmds, ft_cmddel);
free(cmds);
free(line_clean);
return (0);
}
void ft_ctrlc(int num)
{
(void) num;
if (*ft_get_heredoc() != -1)
{
close(*ft_get_heredoc());
*ft_get_heredoc() = -1;
}
else
{
rl_replace_line("", 0);
rl_on_new_line();
ft_putchar_fd('\n', 1);
rl_redisplay();
}
}
void ft_quit(int num)
{
(void) num;
if (*ft_get_heredoc())
{
ft_printf("pb");
}
else
ft_printf("bozoman");
}
int main(int ac, char **av, char **env)
{
t_data data;
char *line;
(void) ac;
(void) av;
signal(SIGINT, ft_ctrlc);
signal(SIGQUIT, ft_quit);
data.exit_code = 0;
data.exit_code_str = NULL;
ft_gen_exit_code_var(&data);
data.env = init_env(env);
if (data.env == NULL)
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 ;
}
free(data.exit_code_str);
ft_lstclear(data.env, env_del);
free(data.env);
return (data.exit_code);
}