/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* expand_token.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lperrey +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/07 02:01:33 by lperrey #+# #+# */ /* Updated: 2021/11/07 04:36:12 by lperrey ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" t_list *ft_lstnew_generic(size_t lst_sizse, size_t content_size); enum e_in_quote_state { NOT_IN = 0, IN_QUOTES = '\'', IN_DQUOTES = '\"' }; static t_list *ret_parameter_expansion(t_token *t, int *i); t_list *expand_token(t_token *t) { int in_quotes; int i; t_list head; t_list *expand; in_quotes = 0; i = 0; head.next = NULL; expand = &head; while (t->content[i]) { if (t->content[i] == '$') { expand->next = ret_parameter_expansion(t, &i); if (!expand->next) {//todo wrap perror("expand_token() error"); return (ft_lstclear(&head.next, free)); } } else { expand->next = ft_lstnew_generic(sizeof(t_list), ft_strlen(&t->content[i]) + 1); if (!expand->next) {//todo wrap perror("expand_token() error"); return (ft_lstclear(&head.next, free)); } while (t->content[i] && (t->content[i] != '$' && in_quotes != IN_QUOTES)) { // quoting if (t->content[i] == '\'' && in_quotes != IN_DQUOTES) { if (in_quotes == IN_QUOTES) in_quotes = 0; else in_quotes = IN_QUOTES; } i++; } } } return (head.next); } // a voir si je retourne pas plutot un "char *". // Malloc la lst dans la fonction est peut-ĂȘtre un peu superflu et pas super clair. // et aussi changer "t_token *t" en "char *content", inutile d'avoir le token entier. static t_list *ret_parameter_expansion(t_token *t, int *i) { t_list *expand; char *tmp; int i_tmp; tmp = ft_calloc(ft_strlen(&t->content[*i]) + 1, 1); if (!tmp) return (NULL); expand = ft_lstnew(NULL); if (!expand) return (ft_retp_free(NULL, tmp, free)); (*i)++; // skip '$' if (t->content[*i] == '?') { i++; expand->content = ft_itoa(g_all->last_exit_status); return (ft_retp_free(expand, tmp, free)); } else if (t->content[*i] != '_' && !ft_isalpha(t->content[*i])) { tmp[0] = '$'; expand->content = tmp; return (expand); } i_tmp = 0; while (t->content[*i] == '_' || ft_isalnum(t->content[*i])) tmp[i_tmp++] = t->content[*i++]; expand->content = getenv(tmp); free(tmp); if (expand->content) expand->content = ft_strdup(expand->content); else expand->content = ft_calloc(1, 1); if (!expand->content) return (ft_retp_free(NULL, expand, free)); return (expand); }