83 lines
2.2 KiB
C
83 lines
2.2 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* content_expand.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: lperrey <lperrey@student.42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2021/11/07 02:01:33 by lperrey #+# #+# */
|
|
/* Updated: 2021/12/21 01:20:40 by lperrey ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "minishell.h"
|
|
|
|
static char *env_var_expansion(char *content, int *i);
|
|
static char *retrieve_var(char *content, int *i);
|
|
|
|
t_list *content_expand(char *content, int *i)
|
|
{
|
|
t_list *expand;
|
|
|
|
expand = ft_lstnew(NULL);
|
|
if (!expand)
|
|
return (NULL);
|
|
expand->content = env_var_expansion(content, i);
|
|
if (!expand->content)
|
|
{
|
|
free(expand);
|
|
return (NULL);
|
|
}
|
|
return (expand);
|
|
}
|
|
|
|
static char *env_var_expansion(char *content, int *i)
|
|
{
|
|
char *expansion;
|
|
|
|
(*i)++;
|
|
if (content[*i] == '?')
|
|
{
|
|
(*i)++;
|
|
expansion = ft_itoa(get_last_exit_status());
|
|
}
|
|
else if (content[*i] == '_' || ft_isalpha(content[*i]))
|
|
expansion = retrieve_var(content, i);
|
|
else
|
|
{
|
|
expansion = ft_calloc(1 + 1, 1);
|
|
if (!expansion)
|
|
return (NULL);
|
|
expansion[0] = '$';
|
|
}
|
|
return (expansion);
|
|
}
|
|
|
|
static char *retrieve_var(char *content, int *i)
|
|
{
|
|
char *expansion;
|
|
char *tmp;
|
|
int i_exp;
|
|
|
|
expansion = ft_calloc(ft_strlen(&content[*i - 1]) + 1, 1);
|
|
if (!expansion)
|
|
return (NULL);
|
|
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
|
|
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
|
|
*/
|