-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuiltin_cd.c
99 lines (91 loc) · 2.39 KB
/
builtin_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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* builtin_cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: phelebra <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/08/02 11:27:31 by phelebra #+# #+# */
/* Updated: 2023/08/02 13:36:07 by phelebra ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void handle_cd_home(const char *home_dir, char *cwd)
{
if (chdir(home_dir) != 0)
perror("cd");
else
setenv("OLDPWD", cwd, 1);
}
void handle_cd_oldpwd(const char *oldpwd, char *cwd)
{
if (oldpwd != NULL)
{
if (chdir(oldpwd) != 0)
perror("cd");
else
setenv("OLDPWD", cwd, 1);
}
else
{
you_fucked_up("OLDPWD is not set", -1);
}
}
void handle_cd_cmd(char *cmd, char *cwd)
{
if (chdir(cmd) != 0)
perror("cd");
else
setenv("OLDPWD", cwd, 1);
}
char *prepare_cd_cmd_and_get_cwd(char **args, const char *home_dir,
char **cwd)
{
char *cmd;
cmd = NULL;
*cwd = malloc(1024 * sizeof(char));
if (*cwd == NULL)
return (NULL);
if (getcwd(*cwd, 1024) == NULL)
{
perror("getcwd");
free(*cwd);
*cwd = NULL;
return (NULL);
}
if (args[1] != NULL)
{
if (args[1][0] == '~')
cmd = builtin_cd_expand_home(&args[1], (char *)home_dir);
else
cmd = strdup(args[1]);
}
return (cmd);
}
int builtin_cd(char **args)
{
const char *home_dir = getenv("HOME");
const char *oldpwd = getenv("OLDPWD");
char *cmd;
char *cwd;
cmd = NULL;
cwd = NULL;
if (home_dir == NULL)
you_fucked_up("Could not get home directory", -1);
if (args[1] == NULL)
{
cwd = getcwd(cwd, 1024);
handle_cd_home(home_dir, cwd);
}
else
{
cmd = prepare_cd_cmd_and_get_cwd(args, home_dir, &cwd);
if (cwd == NULL || cmd == NULL)
return (free(cwd), free(cmd), 1);
if (strcmp(args[1], "-") == 0)
handle_cd_oldpwd(oldpwd, cwd);
else
handle_cd_cmd(cmd, cwd);
}
return (free(cwd), free(cmd), 1);
}