-
Notifications
You must be signed in to change notification settings - Fork 0
/
cd.c
84 lines (78 loc) · 2.21 KB
/
cd.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bde-sous <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/09/30 12:30:35 by bde-sous #+# #+# */
/* Updated: 2023/10/10 14:47:36 by ledos-sa ### ########.fr */
/* */
/* ************************************************************************** */
#include "builtins.h"
#include "libft/libft.h"
#include "minishell.h"
#include <string.h>
#include <unistd.h>
static char *cdaux(char **info, t_envp *env, char *saux)
{
char *end;
char *ret;
if (info[1] != NULL)
{
if (info[1][0] == '~')
end = ft_strjoin(ft_find_value(env, "HOME"), &info[1][1]);
else if (info[1][0] == '-')
end = ft_strjoin(ft_find_value(env, "OLDPWD"), &info[1][1]);
else if (info[1][0] == '/')
end = ft_strdup(info[1]);
else
end = ft_strjoin(saux, info[1]);
ret = end;
}
else
{
if (ft_find_value(env, "HOME") == NULL)
ret = 0;
else
ret = ft_strdup(ft_find_value(env, "HOME"));
}
free(saux);
return (ret);
}
void cd_process_node(t_envp *node, t_envp *env, char *var)
{
if (node)
{
free(node->key);
node->key = getcwd(0, 0);
}
else
ft_add_node(&env, ft_create_node(var, getcwd(0, 0)));
}
void cd(char **info, t_envp *env, t_info *tinfo)
{
char *saux;
t_envp *node;
char *path;
char aux[2048];
saux = ft_strjoin(getcwd(aux, 2048), "/");
path = cdaux(info, env, saux);
if (path == NULL)
{
printf("cd: HOME not set\n");
return ;
}
node = tnode(env, "OLDPWD");
cd_process_node(node, env, ft_strdup("OLDPWD"));
node = tnode(env, "PWD");
if (chdir(path) != 0)
{
perror("cd");
tinfo->exit_code = 1;
}
else
tinfo->exit_code = 0;
free(path);
cd_process_node(node, env, "PWD");
}