-
Notifications
You must be signed in to change notification settings - Fork 0
/
cd.c
132 lines (122 loc) · 2.98 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
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
125
126
127
128
129
130
131
132
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hchorfi <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/02/16 17:51:27 by hchorfi #+# #+# */
/* Updated: 2021/05/21 15:10:46 by hchorfi ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
int ft_change_oldpwd(char *val)
{
char *tmp;
t_list *newlist;
char *tmp_free;
newlist = g_data.env_var;
while (newlist)
{
tmp = ft_substr(newlist->content, 0, 7);
if (!ft_strncmp(tmp, "OLDPWD=", 8))
{
tmp_free = newlist->content;
newlist->content = ft_strjoin("OLDPWD=", val);
free(tmp_free);
free(tmp);
return (0);
}
else
newlist = newlist->next;
free(tmp);
}
ft_lstadd_back(&g_data.env_var, ft_lstnew(ft_strjoin("OLDPWD=", val)));
return (0);
}
int ft_change_pwd(char *val)
{
char *tmp;
t_list *newlist;
char *tmp_free;
newlist = g_data.env_var;
while (newlist)
{
tmp = ft_substr(newlist->content, 0, 4);
if (!ft_strncmp(tmp, "PWD=", 5))
{
tmp_free = newlist->content;
newlist->content = ft_strjoin("PWD=", val);
free(tmp_free);
free(tmp);
return (0);
}
else
newlist = newlist->next;
free(tmp);
}
ft_lstadd_back(&g_data.env_var, ft_lstnew(ft_strjoin("PWD=", val)));
return (0);
}
char *ft_get_home(void)
{
char *tmp;
char *home;
t_list *newlist;
newlist = g_data.env_var;
while (newlist)
{
tmp = ft_substr(newlist->content, 0, 5);
if (!ft_strncmp(tmp, "HOME=", 6))
{
free(tmp);
return ((char *)newlist->content + 5);
}
else
newlist = newlist->next;
free(tmp);
}
return (NULL);
}
int cd_error(int error, char *str)
{
if (error == 1)
{
ft_putstrs_er(
"minishell: ", str, ": No such file or directory\n", NULL);
return (g_data.ret = 1);
}
else if (error == 2)
{
ft_putstr_fd("minishell: cd: HOME not set\n", 2);
return (g_data.ret = 1);
}
return (0);
}
int ft_cd(t_command *command)
{
char pwd[PATH_MAX];
char oldpwd[PATH_MAX];
char *val;
if (!getcwd(oldpwd, PATH_MAX))
ft_putstrs_er(strerror(errno), "\n", NULL, NULL);
val = command->tokens[1];
if (!val)
{
val = ft_get_home();
if (!val)
return (cd_error(2, NULL));
if (*val == 0)
return (g_data.ret = 0);
}
if (!chdir(val))
{
if (!getcwd(pwd, PATH_MAX))
ft_putstrs_er(strerror(errno), "\n", NULL, NULL);
ft_change_pwd(pwd);
ft_change_oldpwd(oldpwd);
return (g_data.ret = 0);
}
else
return (cd_error(1, val));
}