/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* expand_token.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lperrey +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/07 02:01:33 by lperrey #+# #+# */ /* Updated: 2021/12/15 13:33:18 by lperrey ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" static char *env_var_expansion(char *content, int *i); t_list *expand_token(char *content) { int in_quotes; int i; int i_exp; t_list head; t_list *expand; in_quotes = 0; i = 0; head.next = NULL; expand = &head; while (content[i]) { if (content[i] == '$') { expand->next = ft_lstnew(NULL); expand = expand->next; if (!expand) {//todo wrap perror("expand_token() error"); return (ft_lstclear(&head.next, free)); } expand->content = env_var_expansion(content, &i); if (!expand->content) {//todo wrap perror("expand_token() error"); return (ft_lstclear(&head.next, free)); } } else { expand->next = ft_lstnew_generic(sizeof(t_list), ft_strlen(&content[i]) + 1); expand = expand->next; i_exp = 0; if (!expand) {//todo wrap perror("expand_token() error"); return (ft_lstclear(&head.next, free)); } while (content[i] && (content[i] != '$' || in_quotes == IN_QUOTES)) { // quoting if (content[i] == '\'' && in_quotes != IN_DQUOTES) { if (in_quotes == IN_QUOTES) in_quotes = 0; else in_quotes = IN_QUOTES; } ((char *)expand->content)[i_exp++] = content[i++]; } } } return (head.next); } static char *env_var_expansion(char *content, int *i) { char *expansion; char *tmp; int i_exp; (*i)++; // skip '$' if (content[*i] == '?') { (*i)++; expansion = ft_itoa(get_last_exit_status()); return (expansion); } expansion = ft_calloc(ft_strlen(&content[*i - 1]) + 1, 1); // - 1 pour le premier skip if (!expansion) return (NULL); expansion[0] = '$'; if (content[*i] != '_' && !ft_isalpha(content[*i])) return (expansion); i_exp = 0; while (content[*i] == '_' || ft_isalnum(content[*i])) expansion[i_exp++] = content[(*i)++]; tmp = getenv(expansion); ft_free_null(&expansion); if (tmp) expansion = ft_strdup(tmp); else // fix zob, a mieux faire expansion = ft_calloc(1, 1);; // return (expansion); } /* environment variables must be POSIX NAME : 3.235 Name https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html #tag_03_235 */