minishell/src/parser/command_list/command_list.c

123 lines
3.3 KiB
C
Raw Normal View History

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* command_list.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: khais <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/02/24 17:49:46 by khais #+# #+# */
/* Updated: 2025/02/25 13:29:39 by khais ### ########.fr */
/* */
/* ************************************************************************** */
#include "command_list.h"
#include "libft.h"
#include <stdlib.h>
/*
** Match a string to an operator
**
** If the string does not match any operator, return OP_INVALID
*/
static t_operator match_op(char *op)
{
if (ft_strcmp("&&", op) == 0)
return (OP_AND);
return (OP_INVALID);
}
/*
** Count the number of pipelines in the given wordstream
**
** Pipelines are separated by operators || and &&.
**
** Does not do error checking about repeated operators, or operators in the
** wrong place.
*/
static int command_list_count_pipelines(t_wordlist *words)
{
t_wordlist *current_word;
int count;
current_word = words;
if (current_word == NULL)
return (0);
count = 1;
while (current_word != NULL)
{
if (match_op(current_word->word->word) != OP_INVALID)
count++;
current_word = current_word->next;
}
return (count);
}
/*
** Allocate memory for a new command_list, given the input word stream.
**
** Handles malloc error.
*/
static t_command_list *allocate_command_list(t_wordlist *words)
{
t_command_list *output;
if (words == NULL)
return (NULL);
output = ft_calloc(1, sizeof(t_command_list));
if (output == NULL)
return (NULL);
output->num_pipelines = command_list_count_pipelines(words);
output->pipelines
= ft_calloc(output->num_pipelines, sizeof(t_pipeline *));
if (output->pipelines == NULL)
return (free(output), NULL);
return (output);
}
/*
** Create a new command list from the given wordlist.
*/
t_command_list *command_list_from_wordlist(t_wordlist *words)
{
t_command_list *output;
t_wordlist *current_wordlist;
t_worddesc *current_word;
output = allocate_command_list(words);
if (output == NULL)
return (NULL);
current_wordlist = NULL;
current_word = wordlist_pop(&words);
while (current_word != NULL && match_op(current_word->word) == OP_INVALID)
{
current_wordlist = wordlist_push(current_wordlist, current_word);
current_word = wordlist_pop(&words);
}
if (current_word != NULL)
output->operator = match_op(current_word->word);
worddesc_destroy(current_word);
output->pipelines[0] = pipeline_from_wordlist(current_wordlist);
if (words != NULL)
output->pipelines[1] = pipeline_from_wordlist(words);
return (output);
}
/*
** destroy the given command list and all associated memory
*/
void command_list_destroy(t_command_list *cmd)
{
int i;
if (cmd == NULL)
return ;
i = 0;
while (i < cmd->num_pipelines)
{
pipeline_destroy(cmd->pipelines[i]);
i++;
}
free(cmd->pipelines);
free(cmd);
}