-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuiltin_export.c
98 lines (88 loc) · 1.89 KB
/
builtin_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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include "libft/libft.h"
#include "builtin.h"
#include "env.h"
#include "minishell.h"
static void put_export_err_msg(char *identifer)
{
char *tmp;
char *errmsg;
tmp = ft_strjoin("`", identifer);
check_malloc_has_succeeded("export", tmp);
errmsg = ft_strjoin(tmp, "': not a valid identifier");
free(tmp);
check_malloc_has_succeeded("export", errmsg);
put_minish_err_msg("export", errmsg);
free(errmsg);
}
static bool is_valid_env_key(char *key)
{
int i;
if (!ft_strlen(key))
return (false);
i = 0;
while (key[i])
{
if ((!ft_isalnum(key[i]) && key[i] != '_' && key[i] != '+')
|| (ft_isdigit(key[i]) && i == 0)
|| (key[i] == '+' && (i == 0 || key[i + 1] != '\0')))
return (false);
i++;
}
return (true);
}
static int export_strjoin_env(const char *key, const char *value)
{
t_var *env_var;
char *new_value;
key = ft_substr(key, 0, ft_strchr(key, '+') - key);
env_var = get_env(key);
if (!env_var || !env_var->value || !ft_strlen(env_var->value))
new_value = ft_strdup(value);
else
new_value = ft_strjoin(env_var->value, value);
ft_setenv(key, new_value, 0);
free((void *)key);
free(new_value);
return (0);
}
static int export_env(char *arg)
{
char **kvarr;
kvarr = split_first_c(arg, '=');
if (!is_valid_env_key(kvarr[0])
|| (ft_strchr(kvarr[0], '+') && !kvarr[1]))
{
put_export_err_msg(arg);
free_ptrarr((void **)kvarr);
return (1);
}
if (ft_strchr(kvarr[0], '+'))
export_strjoin_env(kvarr[0], kvarr[1]);
else
ft_setenv(kvarr[0], kvarr[1], 0);
free_ptrarr((void **)kvarr);
return (0);
}
/*
* builtin export command
*
* argv: ["export", "ABC=abc"]
*/
int builtin_export(char **argv)
{
int status;
if (ptrarr_len((void **)argv) < 2)
return (print_envs_with_declaration());
argv++;
status = 0;
while (*argv)
{
status |= export_env(*argv);
argv++;
}
return (status);
}