-
Notifications
You must be signed in to change notification settings - Fork 0
/
com_builtins3.c
128 lines (119 loc) · 2.5 KB
/
com_builtins3.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
#include "main.h"
/**
* _getenvi - gets a variable from environment given its name
* @name: variable name
* Return: the index of the found var...
*/
int _getenvi(const char *name)
{
int i = 0;
char *var = NULL, *tmp = NULL;
if (name == NULL)
return (-1);
tmp = _strdup((char *)name);
var = _strcat(tmp, "=");
free(tmp);
while (environ[i])
{
if (_strsearch(environ[i], var, 0) == 1)
{
free(var);
return (i);
}
i++;
}
free(var);
return (0);
}
/**
* builtin_setenv - sets the environmental variable given
* @var: the variable
* @value: the value of the variable
* Return: nothing
*/
void builtin_setenv(char *var, char *value)
{
int i = 0, num_entries = 0, indx = -1, add_size = 2;
char *new_entry = NULL, **new_environ;
if (_getenv(var) != NULL)
{
indx = _getenvi(var);
add_size = 1;
}
new_entry = (char *)malloc(_strlen(var) + _strlen(value) + 2);
if (new_entry == NULL)
return;
_strcpy(new_entry, var);
_strcpy(new_entry + _strlen(var), "=");
_strcpy(new_entry + _strlen(var) + 1, value);
while (environ[num_entries] != NULL)
num_entries++;
new_environ = (char **)malloc((num_entries + add_size) * sizeof(char *));
if (new_environ == NULL)
return;
for (i = 0; i < num_entries; i++)
{
if (i == indx)
{
new_environ[i] = _strdup(new_entry);
free(new_entry);
}
else
new_environ[i] = _strdup(environ[i]);
}
if (indx == -1)
{
new_environ[i] = _strdup(new_entry);
free(new_entry);
}
new_environ[num_entries + 1] = NULL;
environ = new_environ;
}
/**
* builtin_cd - changes directory
* @tokens: the array of tokens
* @iter: the iteration for printing errors..
* Return: no return
*/
void builtin_cd(char **tokens, UINT iter)
{
int ret = 0;
char *dir, *curr = NULL, cwd[4096];
if (_getenv("OLDPWD") == NULL)
builtin_setenv("OLDPWD", _getenv("PWD"));
if (tokens[1] == NULL)
{
dir = _getenv("HOME");
goto JUMPED;
}
if (_strcmp(tokens[1], "-") == 0)
{
ret = chdir(_getenv("OLDPWD"));
if (ret == 0)
{
_puts(_getenv("OLDPWD"));
_putchar('\n');
}
return;
}
else if (_strcmp(tokens[1], "$HOME") == 0)
dir = _getenv("HOME");
else
dir = tokens[1];
JUMPED:
if (getcwd(cwd, sizeof(cwd)) != NULL)
builtin_setenv("OLDPWD", getcwd(cwd, sizeof(cwd)));
ret = chdir(dir);
if (ret == -1 && tokens[1] != NULL)
{
print_err(iter, tokens[0], "can't cd to ");
_puts2(tokens[1], STDERR_FILENO);
_putchar2('\n', STDERR_FILENO);
}
if (ret == 0)
{
curr = getcwd(cwd, sizeof(cwd));
if (curr != NULL)
builtin_setenv("PWD", cwd);
}
}