-
Notifications
You must be signed in to change notification settings - Fork 0
/
s_builtins.c
124 lines (113 loc) · 2.61 KB
/
s_builtins.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
113
114
115
116
117
118
119
120
121
122
123
124
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* s_builtins.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ebalgruu <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/27 01:29:05 by ebalgruu #+# #+# */
/* Updated: 2021/11/27 01:29:08 by ebalgruu ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void ft_del_env(t_env *env)
{
t_env *tmp;
tmp = env->next;
env->next = tmp->next;
free(tmp->key);
free(tmp->sep);
free(tmp->value);
free(tmp);
}
int ft_check_first(t_env **env, char *str)
{
t_env *tmp;
tmp = *env;
if (!ft_strcmp(str, tmp->key))
{
*env = (*env)->next;
free(tmp->key);
free(tmp->sep);
free(tmp->value);
free(tmp);
return (1);
}
return (0);
}
int ft_unset(t_cmd *cmd, t_arg *arg)
{
int i;
t_env *tmp1;
t_env *tmp2;
i = 0;
while (cmd->cmd[++i])
{
if (!arg->envp)
break ;
if (cmd->cmd[i][0] == '_')
continue ;
if (ft_check_first(&arg->envp, cmd->cmd[i]))
continue ;
tmp1 = arg->envp;
tmp2 = tmp1->next;
while (tmp2 && ft_strcmp(cmd->cmd[i], tmp2->key))
{
tmp1 = tmp2;
tmp2 = tmp2->next;
}
if (tmp2)
ft_del_env(tmp1);
}
return (0);
}
char *get_cd(t_cmd *cmd, t_env *env, t_arg *arg)
{
char *cd;
char *pwd;
cd = NULL;
if (cmd->cmd[1][0] != '~')
{
cd = getcwd(NULL, 0);
if (!cd)
ft_exit(errno, "getcwd", arg);
pwd = ft_strjoin_pars(cd, "/", arg);
free(cd);
cd = ft_strjoin_pars(pwd, cmd->cmd[1], arg);
free(pwd);
return (cd);
}
while (env && ft_strcmp(env->key, "HOME"))
env = env->next;
if (env)
{
pwd = ft_substr_pars(cmd->cmd[1], 1, \
ft_strlen(cmd->cmd[1]) - 1, arg);
cd = ft_strjoin_pars(env->value, pwd, arg);
free(pwd);
}
return (cd);
}
int ft_cd(t_cmd *cmd, t_env *env, t_arg *arg)
{
char *cd;
cd = NULL;
if (!cmd->cmd[1])
{
while (env && ft_strcmp(env->key, "HOME"))
env = env->next;
if (env)
cd = ft_strdup_pars(env->value, arg);
}
else
cd = get_cd(cmd, env, arg);
if (!cd)
{
write(2, "cd: HOME not set\n", 17);
return (1);
}
chdir(cd);
arg->errnum = errno;
free(cd);
return (arg->errnum);
}