42_minishell/env_fill.c
2023-02-20 15:41:03 +01:00

104 lines
2.4 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* env_fill.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/16 16:29:08 by cchauvet #+# #+# */
/* Updated: 2023/02/20 15:39:28 by starnakin ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static char *ft_get_value(t_list **env, char *key)
{
char *value;
value = get_value_by_key(key, env);
if (value == NULL)
value = "";
return (value);
}
static char *ft_get_key(char *str)
{
char *key;
size_t i;
i = 1;
if (ft_strncmp(str, "$$", 2) == 0)
{
key = ft_strdup("$");
if (key == NULL)
ft_eprintf("minishell: malloc failed\n");
return (key);
}
if (str[i] == ' ' || str[i] == '\0')
{
key = ft_strdup("");
if (key == NULL)
ft_eprintf("minishell: malloc failed\n");
return (key);
}
while (str[i] != '\0' && str[i] != '$' && str[i] != ' '
&& str[i] != '"')
i++;
key = ft_strndup(str + 1, i - 1);
if (key == NULL)
ft_eprintf("minishell: malloc failed\n");
return (key);
}
char *ft_env_filler(t_list **env, const char *str)
{
size_t i;
char *key;
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] == '$')
{
key = ft_get_key(out + i);
if (key == NULL)
{
free(out);
return (NULL);
}
value = ft_get_value(env, key);
if (value == NULL)
{
free(key);
free(out);
return (NULL);
}
temp = ft_strreplace(out, value, i, ft_strlen(key) + 1 + i);
free(key);
i = i + ft_strlen(value);
free(out);
if (temp == NULL)
{
ft_eprintf("minishell: malloc failed\n");
return (NULL);
}
out = temp;
}
if (out[i] != '\0')
i++;
}
return (out);
}