-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathft_built_cd.c
More file actions
executable file
·121 lines (110 loc) · 2.75 KB
/
ft_built_cd.c
File metadata and controls
executable file
·121 lines (110 loc) · 2.75 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_built_cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: khsadira <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/09/11 09:59:06 by khsadira #+# #+# */
/* Updated: 2018/10/10 09:33:30 by khsadira ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_minishell.h"
static char *get_cd_path(t_env *env, char *arg)
{
char *tmp;
tmp = NULL;
if (arg == NULL)
{
if ((tmp = ft_search_env("HOME", env)))
return (tmp);
else
{
ft_putendl_fd("cd: HOME not set", 2);
return (NULL);
}
}
else
return (arg);
}
static int check_error_path(char *path, char *arg)
{
struct stat stbuf;
DIR *diropen;
if (path == NULL)
return (-1);
if (lstat(path, &stbuf) == -1)
{
ft_no_such_file_or_dir("cd: ", arg);
return (-1);
}
if (!S_ISDIR(stbuf.st_mode) && !S_ISLNK(stbuf.st_mode))
{
ft_not_dir("cd: ", arg);
return (-1);
}
if (!(diropen = opendir(path)))
{
ft_permission_denied("cd: ", arg);
return (-1);
}
else
closedir(diropen);
return (1);
}
static t_env *init_pwd(t_env *env)
{
char *cwd;
cwd = getcwd(NULL, 0);
env = ft_setenv_c("PWD", cwd, env);
return (env);
}
static t_env *ft_cd_oldpwd(t_env *env)
{
char *tmp;
char *pwd;
char *cwd;
tmp = NULL;
pwd = NULL;
cwd = NULL;
if (!(tmp = ft_search_env("OLDPWD", env)))
{
ft_putendl_fd("cd : OLDPWD not set", 2);
return (env);
}
cwd = ft_strdup(tmp);
if (!(pwd = ft_search_env("PWD", env)))
pwd = "";
env = ft_setenv_c("OLDPWD", ft_strdup(pwd), env);
chdir(cwd);
ft_strdel(&cwd);
cwd = getcwd(NULL, 0);
env = ft_setenv_c("PWD", cwd, env);
return (env);
}
t_env *ft_built_cd(t_lst *list, t_env *env)
{
char *path;
char *cwd;
char *pwd;
if (ft_dstrlen(list->arg) > 2)
{
ft_putendl_fd("cd: too many arguments", 2);
return (env);
}
if (ft_strequ(list->arg[1], "-"))
return (env = ft_cd_oldpwd(env));
env = init_pwd(env);
path = get_cd_path(env, list->arg[1]);
if (check_error_path(path, list->arg[1]) == -1)
return (env);
if (path)
{
pwd = ft_search_env("PWD", env);
env = ft_setenv_c("OLDPWD", ft_strdup(pwd), env);
chdir(path);
cwd = getcwd(NULL, 0);
env = ft_setenv_c("PWD", cwd, env);
}
return (env);
}