-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseline.c
152 lines (141 loc) · 3.76 KB
/
parseline.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
139
140
141
142
143
144
145
146
147
148
149
150
151
//
// Created by glavak on 11.02.17.
//
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "shell.h"
static char * blankskip(char * string)
{
while (isspace(*string) && *string) ++string;
return string;
}
int parseline(char * line)
{
int nargs, ncmds;
char * s;
char aflg = 0;
int rval;
int i;
int is_in_string_mode = 0;
static char delim[] = " \t|&<>;\n";
/* initialize */
bkgrnd = nargs = ncmds = rval = 0;
s = line;
infile = outfile = appfile = NULL;
cmds[0].arguments[0] = NULL;
for (i = 0; i < MAXCMDS; i++)
{
cmds[i].is_in_piped = 0;
cmds[i].is_out_piped = 0;
}
while (*s)
{ /* until line has been parsed */
s = blankskip(s); /* skip white space */
if (!*s) break; /* done with line */
/* handle <, >, |, &, and ; */
switch (*s)
{
case '"':cmds[ncmds].arguments[nargs] = s + 1;
nargs++;
cmds[ncmds].arguments[nargs] = (char *) NULL;
do
{
s++;
}
while (*s != '"');
*s = '\0';
s++;
break;
case '&':bkgrnd = 1;
*s++ = '\0';
break;
case '>':
if (*(s + 1) == '>')
{
aflg = 1;
*s++ = '\0';
}
*s++ = '\0';
s = blankskip(s);
if (!*s)
{
fprintf(stderr, "syntax error\n");
return (-1);
}
if (aflg)
{
appfile = s;
}
else
{
outfile = s;
}
s = strpbrk(s, delim);
if (isspace(*s))
{
*s++ = '\0';
}
break;
case '<':*s++ = '\0';
s = blankskip(s);
if (!*s)
{
fprintf(stderr, "syntax error\n");
return -1;
}
infile = s;
s = strpbrk(s, delim);
if (isspace(*s))
{
*s++ = '\0';
}
break;
case '|':
if (nargs == 0)
{
fprintf(stderr, "syntax error\n");
return (-1);
}
cmds[ncmds++].is_out_piped = 1;
cmds[ncmds].is_in_piped = 1;
*s++ = '\0';
nargs = 0;
break;
case ';':*s++ = '\0';
++ncmds;
nargs = 0;
break;
default:
/* a command argument */
if (nargs == 0)
{ /* next command */
rval = ncmds + 1;
}
cmds[ncmds].arguments[nargs] = s;
nargs++;
cmds[ncmds].arguments[nargs] = (char *) NULL;
s = strpbrk(s, delim);
if (isspace(*s))
{
*s++ = '\0';
}
break;
} /* close switch */
} /* close while */
/* error check */
/*
* The only errors that will be checked for are
* no command on the right side of a pipe
* no command to the left of a pipe is checked above
*/
if (cmds[ncmds - 1].is_out_piped)
{
if (nargs == 0)
{
fprintf(stderr, "syntax error\n");
return -1;
}
}
return rval;
}