112 lines
2.9 KiB
C
112 lines
2.9 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* export.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2023/02/14 14:27:08 by cchauvet #+# #+# */
|
|
/* Updated: 2023/04/04 13:38:27 by erey-bet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "./builtins_private.h"
|
|
|
|
static int error(char *str, char *to_free1, char *to_free2)
|
|
{
|
|
write(2, "bozoshell: export: `", 20);
|
|
write(2, str, ft_strlen(str));
|
|
write(2, "': not a valid identifier\n", 26);
|
|
if (to_free1 != NULL)
|
|
free(to_free1);
|
|
if (to_free2 != NULL)
|
|
free(to_free2);
|
|
return (1);
|
|
}
|
|
|
|
void print_export(t_list **env, int fd)
|
|
{
|
|
t_list *current;
|
|
|
|
current = *env;
|
|
while (current->next != NULL)
|
|
{
|
|
write(fd, "declare -x ", 11);
|
|
ft_putstr_fd(((t_env *)(current->content))->key, fd);
|
|
if (((t_env *)(current->content))->value != NULL)
|
|
{
|
|
ft_putstr_fd("=", fd);
|
|
write(fd, "\"", 1);
|
|
ft_putstr_fd(((t_env *)(current->content))->value, fd);
|
|
write(fd, "\"\n", 2);
|
|
}
|
|
else
|
|
write(fd, "\n", 2);
|
|
current = current->next;
|
|
}
|
|
}
|
|
|
|
int set_key_value_export(t_list **env, char *args, char **key, char **value)
|
|
{
|
|
*key = ft_strndup(args, ft_strnchr(args, '='));
|
|
if (*key == NULL)
|
|
return (1);
|
|
if (ft_strlen(*key) == 0)
|
|
return (1);
|
|
if (possible_key(*key) == 2)
|
|
{
|
|
(*key)[ft_strlen(*key) - 1] = '\0';
|
|
if (get_value_by_key(*key, env) == NULL)
|
|
*value = ft_strdup(ft_strchr(args, '=') + 1);
|
|
else
|
|
*value = ft_strjoin(get_value_by_key(*key, env),
|
|
ft_strchr(args, '=') + 1);
|
|
}
|
|
else
|
|
*value = ft_strdup(ft_strchr(args, '=') + 1);
|
|
return (0);
|
|
}
|
|
|
|
int add_export(t_list **env, char *args)
|
|
{
|
|
char *key;
|
|
char *value;
|
|
|
|
if (ft_strchr(args, '=') != NULL)
|
|
{
|
|
if (set_key_value_export(env, args, &key, &value))
|
|
return (error(args, key, NULL));
|
|
}
|
|
else
|
|
{
|
|
key = ft_strdup(args);
|
|
value = get_value_by_key(key, env);
|
|
if (value != NULL)
|
|
value = ft_strdup(value);
|
|
if (possible_key(key) == 2)
|
|
return (error(key, key, value));
|
|
}
|
|
if (!possible_key(key))
|
|
return (error(args, key, value));
|
|
create_value_by_key(key, value, env);
|
|
return (0);
|
|
}
|
|
|
|
int ft_export(t_list **env, char **args, int fd)
|
|
{
|
|
int err;
|
|
int i;
|
|
|
|
err = 0;
|
|
if (args[0] == NULL)
|
|
print_export(env, fd);
|
|
else
|
|
{
|
|
i = -1;
|
|
while (args[++i])
|
|
if (add_export(env, args[i]) == 1)
|
|
err = 1;
|
|
}
|
|
return (err);
|
|
}
|