42_minishell/env_fill.c
Camille Chauvet a183971a7a bozo
2023-02-17 18:23:17 +01:00

78 lines
2.0 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* env_fill.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/16 16:29:08 by cchauvet #+# #+# */
/* Updated: 2023/02/17 17:31:16 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libftx/libftx.h"
#include "minishell.h"
#include "utils/utils.h"
static char *ft_get_value(t_list **env, const char *str, size_t start,
size_t stop)
{
char *key;
char *value;
key = ft_strndup(str + start, stop);
if (key == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (NULL);
}
value = get_value_by_key(key, env);
if (value == NULL)
value = "";
free(key);
return (value);
}
char *ft_env_filler(t_list **env, const char *str)
{
size_t i;
size_t y;
char *out;
char *temp;
char *value;
out = ft_strdup(str);
if (out == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (NULL);
}
i = 0;
while (out[i] != '\0')
{
while (ft_is_in_quote(out, i) == 1)
i++;
while (out[i] == '$')
{
y = i + 1;
while (out[y] != '\0' && out[y] != '$' && out[y] != ' '
&& out[y] != '"')
y++;
value = ft_get_value(env, out, i + 1, y - i - 1);
if (value == NULL)
return (NULL);
temp = ft_strreplace(out, value, i, y);
free(out);
if (temp == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (NULL);
}
out = temp;
}
if (out[i] != '\0')
i++;
}
return (out);
}