-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexport.c
112 lines (102 loc) · 2.75 KB
/
export.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* export.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: brmoretti <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/01/29 11:08:03 by brmoretti #+# #+# */
/* Updated: 2024/02/20 00:51:44 by brmoretti ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/minishell.h"
void print_environ_sorted(void);
int is_valid_identifier(char *str);
static void add_to_env(char *new_env_var)
{
char **env_vars;
char **new_env_vars;
int i;
env_vars = environ_holder(NULL, 0);
i = 0;
while (env_vars[i])
i++;
new_env_vars = malloc(sizeof(char *) * (i + 2));
i = -1;
while (env_vars[++i])
new_env_vars[i] = ft_strdup(env_vars[i]);
new_env_vars[i] = new_env_var;
new_env_vars[++i] = NULL;
environ_holder(NULL, 1);
environ_holder(new_env_vars, 0);
}
static char *new_env_var_generator(const char *name, const char *value)
{
char *new_env_var;
char *eq_value;
char *tmp;
if (!value)
return (ft_strdup(name));
if (*value == '\"' || *value == '\'')
eq_value = ft_strndup(value + 1, ft_strlen(value) - 2);
else
eq_value = ft_strdup(value);
tmp = eq_value;
eq_value = ft_strjoin("=", eq_value);
free(tmp);
new_env_var = ft_strjoin(name, eq_value);
free(eq_value);
return (new_env_var);
}
static void ft_setenv(const char *name, const char *value)
{
char **env_vars;
char *new_env_var;
char *env_var;
int i;
env_vars = environ_holder(NULL, 0);
new_env_var = new_env_var_generator(name, value);
i = -1;
while (env_vars[++i])
{
env_var = key_name(env_vars[i]);
if (!ft_strcmp(env_var, name))
{
free(env_var);
free(env_vars[i]);
env_vars[i] = new_env_var;
return ;
}
free(env_var);
}
add_to_env(new_env_var);
}
int export(char **args)
{
int i;
char *equal_sign;
char *name;
int status;
i = 0;
status = 0;
if (!args[1])
print_environ_sorted();
while (args[++i])
{
if (!is_valid_identifier(args[i]) && status++)
continue ;
name = key_name(args[i]);
if (ft_strcmp(name, "="))
{
free(name);
break ;
}
equal_sign = ft_strchr(args[i], '=');
if (equal_sign)
ft_setenv(name, equal_sign + 1);
else
ft_setenv(name, NULL);
free(name);
}
return (!!status);
}