-
Notifications
You must be signed in to change notification settings - Fork 0
/
expansions.c
112 lines (103 loc) · 2.56 KB
/
expansions.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
#include "shell.h"
/**
* expand_variables - expand variables
* @data: a pointer to a struct of the program's data
*
* Return: nothing, but sets errno.
*/
void expand_variables(data_of_program *data)
{
int i, j;
char line[BUFFER_SIZE] = {0}, expansion[BUFFER_SIZE] = {'\0'}, *temp;
if (data->input_line == NULL)
return;
buffer_add(line, data->input_line);
for (i = 0; line[i]; i++)
if (line[i] == '#')
line[i--] = '\0';
else if (line[i] == '$' && line[i + 1] == '?')
{
line[i] = '\0';
long_to_string(errno, expansion, 10);
buffer_add(line, expansion);
buffer_add(line, data->input_line + i + 2);
}
else if (line[i] == '$' && line[i + 1] == '$')
{
line[i] = '\0';
long_to_string(getpid(), expansion, 10);
buffer_add(line, expansion);
buffer_add(line, data->input_line + i + 2);
}
else if (line[i] == '$' && (line[i + 1] == ' ' || line[i + 1] == '\0'))
continue;
else if (line[i] == '$')
{
for (j = 1; line[i + j] && line[i + j] != ' '; j++)
expansion[j - 1] = line[i + j];
temp = env_get_key(expansion, data);
line[i] = '\0', expansion[0] = '\0';
buffer_add(expansion, line + i + j);
temp ? buffer_add(line, temp) : 1;
buffer_add(line, expansion);
}
if (!str_compare(data->input_line, line, 0))
{
free(data->input_line);
data->input_line = str_duplicate(line);
}
}
/**
* expand_alias - expans aliases
* @data: a pointer to a struct of the program's data
*
* Return: nothing, but sets errno.
*/
void expand_alias(data_of_program *data)
{
int i, j, was_expanded = 0;
char line[BUFFER_SIZE] = {0}, expansion[BUFFER_SIZE] = {'\0'}, *temp;
if (data->input_line == NULL)
return;
buffer_add(line, data->input_line);
for (i = 0; line[i]; i++)
{
for (j = 0; line[i + j] && line[i + j] != ' '; j++)
expansion[j] = line[i + j];
expansion[j] = '\0';
temp = get_alias(data, expansion);
if (temp)
{
expansion[0] = '\0';
buffer_add(expansion, line + i + j);
line[i] = '\0';
buffer_add(line, temp);
line[str_length(line)] = '\0';
buffer_add(line, expansion);
was_expanded = 1;
}
break;
}
if (was_expanded)
{
free(data->input_line);
data->input_line = str_duplicate(line);
}
}
/**
* buffer_add - append string at end of the buffer
* @buffer: buffer to be filled
* @str_to_add: string to be copied in the buffer
* Return: nothing, but sets errno.
*/
int buffer_add(char *buffer, char *str_to_add)
{
int length, i;
length = str_length(buffer);
for (i = 0; str_to_add[i]; i++)
{
buffer[length + i] = str_to_add[i];
}
buffer[length + i] = '\0';
return (length + i);
}