Files
42_INT_07_minishell/srcs/builtins/export.c
2021-12-05 18:15:23 +01:00

87 lines
2.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* export.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lperrey <lperrey@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/12/03 13:36:54 by lperrey #+# #+# */
/* Updated: 2021/12/05 18:14:31 by lperrey ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
char *ft_getenv(char *env_var);
size_t ft_getenv_position(char *env_var);
static int change_env_value(char *arg);
// in complete shell, must mark arguments for export
// (Not implemented in minishell)
int builtin_export(int argc, char *argv[], t_all *c) // 2 lignes de trop... NORME / 20
{
int i;
int exit_value;
int ret;
(void)argc;
exit_value = EXIT_SUCCESS;
i = 1;
while (argv[i])
{
if (ft_strchr(argv[i], '='))
{
ret = change_env_value(argv[i]);
if (ret == -1)
return (EXIT_FAILURE);
else if (ret == EXIT_FAILURE)
exit_value = EXIT_FAILURE;
if (ft_strncmp(argv[i], "PATH=", 5) == 0)
c->path = retrieve_path();
}
else if (!ft_is_posix_name(argv[i]))
{
shell_error("export: ", argv[i], ": not a valid identifier", 0);
exit_value = EXIT_FAILURE;
}
i++;
}
return (exit_value);
}
static int change_env_value(char *arg)
{
char **var_split;
int env_position;
var_split = ft_split(arg, '=');
if (!var_split)
return (ft_reti_perror(-1, "builtin_export, ft_split()"));
if (!ft_is_posix_name(var_split[0]))
{
shell_error("export: ", var_split[0], ": not a valid identifier", 0);
ft_free_2d_arr(var_split);
return (EXIT_FAILURE);
}
env_position = ft_getenv_position(var_split[0]);
ft_free_2d_arr(var_split);
if (environ[env_position] == NULL)
{
environ = ft_resize_2d_arr(environ, 1);
if (!environ)
return (ft_reti_perror(-1, "builtin_export, ft_resize_2d_arr()"));
}
environ[env_position] = ft_strdup(arg);
if (!environ[env_position])
return (ft_reti_perror(-1, "builtin_export, ft_strdup()"));
return (EXIT_SUCCESS);
}
/*
environment variables must be POSIX NAME :
3.235 Name
https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html
#tag_03_235
*/