From: Lukas Jiriste Date: Sun, 21 Jul 2024 12:24:50 +0000 (+0200) Subject: Add save_assignments function X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=bc9bc2d04639924d3660ad753ee53effb309b772;p=42%2Fminishell.git Add save_assignments function This function traverses the subtree of the command and extracts all ASSIGNMENT_WORD tokens to the assignments t_vec so that it is in the same form as the t_vecs in t_vars. --- diff --git a/src/execution.c b/src/execution.c index 40ec8af..eb14d4b 100644 --- a/src/execution.c +++ b/src/execution.c @@ -6,12 +6,91 @@ /* By: ljiriste +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/07/21 08:57:54 by ljiriste #+# #+# */ -/* Updated: 2024/07/21 13:11:50 by ljiriste ### ########.fr */ +/* Updated: 2024/07/21 14:24:33 by ljiriste ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" +int cmp_var_name(const char *a, const char *b) +{ + int namelen; + char *eq_ptr; + + eq_ptr = ft_strchr(a, '='); + namelen = eq_ptr - a; + eq_ptr = ft_strchr(b, '='); + if (namelen != eq_ptr - b) + return (1); + return (ft_strcmp(a, b, namelen)); +} + +void clear_old(t_vec *assignments, const char *new) +{ + size_t i; + char **assignment; + + i = assignments->size; + while (i > 0) + { + --i; + assignment = ft_vec_access(assignments, i); + if (cmp_var_name(*assignment, new)) + continue ; + ft_vec_erase(assignments, i, free); + } + return ; +} + +int add_assignment(t_vec *assignments, const char *assignment) +{ + size_t i; + char *copy; + + copy = ft_strdup(subnode->token.str); + if (!copy) + return (1); + clear_old(assignments, copy); + if (ft_vec_append(assignments, ©) == success) + return (0); + free(copy); + return (1); +} + +int save_assignments_prefix(t_vec *assignments, t_parse_tree_node *prefix) +{ + size_t i; + char *assignment; + t_parse_tree_node *subnode; + + i = 0; + while (i < prefix->children.size) + { + subnode = ft_vec_access(&prefix->children, i); + if (is_token_type(subnode, "ASSIGNMENT_WORD")) + { + if (add_assignment(assignments, subnode->token.str)) + return (1); + } + else if (is_token_type(subnode, "cmd_prefix")) + if (save_assignments_prefix(assignments, subnode)) + return (1); + ++i; + } + return (0); +} + +int save_assignments(t_vec *assignments, t_parse_tree_node *simple_command) +{ + t_parse_tree_node *subnode; + if (ft_vec_init(assignments, sizeof(char *)) != success) + return (1); + subnode = ft_vec_access(&simple_command->children, 0); + if (is_token_type(subnode, "cmd_prefix")) + return (save_assignments_prefix(assignments, subnode)); + return (0); +} + int ex_simple_command(t_parse_tree_node *simple_command, t_execution_env *env) { t_vec redirections;