-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.c
More file actions
109 lines (96 loc) · 2.35 KB
/
parser.c
File metadata and controls
109 lines (96 loc) · 2.35 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
#include "main.h"
/**
* parser - make a Commands single list of commands and its logical operators.
*
* @buffer: buffer to be parsed.
*
* Return: pointer to the Commands single list.
*/
Commands *parser(char *buffer)
{
Commands *commands = NULL;
size_t index, prevIndex = 0, foundOp = 0, firstCMD = 1;
char **tokens = NULL;
char *safe_buffer = NULL;
safe_buffer = safeBuffer(buffer);
tokens = tokenizedArray(safe_buffer, " ");
free(safe_buffer);
for (index = 0; tokens[index] != NULL; index++)
{
if (_strcmp(tokens[index], "||") == 0 && firstCMD != 1)
foundOp = 1;
else if (_strcmp(tokens[index], "&&") == 0 && firstCMD != 1)
foundOp = 1;
else if (_strcmp(tokens[index], ";") == 0 && firstCMD != 1)
foundOp = 1;
if (foundOp)
{
add_node_end(prevIndex, index, tokens[index], tokens, &commands);
prevIndex = index + 1;
foundOp = 0;
}
if (tokens[index + 1] == NULL)
add_node_end(prevIndex, index + 1, NULL, tokens, &commands);
firstCMD = 0;
}
free_2D(tokens, index);
return (commands);
}
/**
* safeBuffer - delete the last character '\n'.
*
* @buffer: buffer to processed.
*
* Return: pointer to the safe buffer.
*/
void *safeBuffer(char *buffer)
{
char *safe_buffer;
int index, len;
for (len = 0; buffer[len + 1]; len++)
{
if (buffer[len] == '#' && (len == 0 || buffer[len - 1] == ' '))
break;
}
safe_buffer = malloc(len + 1);
for (index = 0; index < len; index++)
safe_buffer[index] = buffer[index];
safe_buffer[index] = '\0';
return (safe_buffer);
}
/**
* tokenizedArray - make each command and arg in
* the buffer into array.
*
* @safeBuffer: the buffer to be processed.
* @delim: delimiter.
*
* Return: array of tokenized commands.
*/
char **tokenizedArray(char *safeBuffer, char *delim)
{
char *tempSafeBuffer = NULL, *token = NULL;
char **tokenized_array = NULL;
size_t arrLen = 0;
tempSafeBuffer = _strdup(safeBuffer);
token = strtok(tempSafeBuffer, delim);
while (token != NULL)
{
arrLen++;
token = strtok(NULL, delim);
}
free(tempSafeBuffer);
tempSafeBuffer = _strdup(safeBuffer);
tokenized_array = malloc((arrLen + 1) * sizeof(char *));
token = strtok(tempSafeBuffer, delim);
arrLen = 0;
while (token != NULL)
{
tokenized_array[arrLen] = _strdup(token);
arrLen++;
token = strtok(NULL, delim);
}
tokenized_array[arrLen] = NULL;
free(tempSafeBuffer);
return (tokenized_array);
}