-
Notifications
You must be signed in to change notification settings - Fork 0
/
builtins.c
139 lines (125 loc) · 2.34 KB
/
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include "main.h"
#define SETOWD(V) (V = _strdup(_getenv("OLDPWD", data)))
/**
* change_dir - changes directory
* @data: a pointer to the data structure
*
* Return: (Success) 0 is returned
* ------- (Fail) negative number will returned
*/
int change_dir(sh_t *data)
{
char *home;
home = _getenv("HOME", data);
if (data->args[1] == NULL)
{
SETOWD(data->oldpwd);
if (chdir(home) < 0)
return (FAIL);
return (SUCCESS);
}
if (_strcmp(data->args[1], "-") == 0)
{
if (data->oldpwd == 0)
{
SETOWD(data->oldpwd);
if (chdir(home) < 0)
return (FAIL);
}
else
{
SETOWD(data->oldpwd);
if (chdir(data->oldpwd) < 0)
return (FAIL);
}
}
else
{
SETOWD(data->oldpwd);
if (chdir(data->args[1]) < 0)
return (FAIL);
}
return (SUCCESS);
}
#undef GETCWD
/**
* abort_prg - exit the program
* @data: a pointer to the data structure
*
* Return: (Success) 0 is returned
* ------- (Fail) negative number will returned
*/
int abort_prg(sh_t *data __attribute__((unused)))
{
int code, i = 0;
if (data->args[1] == NULL)
{
free_data(data);
exit(0);
}
while (data->args[1][i])
{
if (_isalpha(data->args[1][i++]) > 0)
{
data->error_msg = _strdup("Illegal number\n");
return (FAIL);
}
}
code = _atoi(data->args[1]);
free_data(data);
exit(code);
}
/**
* display_help - display the help menu
* @data: a pointer to the data structure
*
* Return: (Success) 0 is returned
* ------- (Fail) negative number will returned
*/
int display_help(sh_t *data)
{
int fd, fw, rd = 1;
char c;
fd = open(data->args[1], O_RDONLY);
if (fd < 0)
{
data->error_msg = _strdup("no help topics match\n");
return (FAIL);
}
while (rd > 0)
{
rd = read(fd, &c, 1);
fw = write(STDOUT_FILENO, &c, rd);
if (fw < 0)
{
data->error_msg = _strdup("cannot write: permission denied\n");
return (FAIL);
}
}
PRINT("\n");
return (SUCCESS);
}
/**
* handle_builtin - handle and manage the builtins cmd
* @data: a pointer to the data structure
*
* Return: (Success) 0 is returned
* ------- (Fail) negative number will returned
*/
int handle_builtin(sh_t *data)
{
blt_t blt[] = {
{"exit", abort_prg},
{"cd", change_dir},
{"help", display_help},
{NULL, NULL}
};
int i = 0;
while ((blt + i)->cmd)
{
if (_strcmp(data->args[0], (blt + i)->cmd) == 0)
return ((blt + i)->f(data));
i++;
}
return (FAIL);
}