-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_structs.c
130 lines (121 loc) · 2.87 KB
/
generate_structs.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* generate_structs.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: eusatiko <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/09 09:59:34 by eusatiko #+# #+# */
/* Updated: 2024/10/14 13:14:16 by eusatiko ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
t_cmd *generate_structs(t_tok *head, int numargs, int numredir)
{
t_cmd *cmd;
int idx_a;
int idx_r;
int err;
err = 0;
cmd = init_struct(numargs, numredir, &err);
idx_a = 1;
idx_r = 0;
while (head->type != END && !err)
{
if (head->type == PIPE)
{
cmd->next = generate_structs(head->next, numargs, numredir);
if (!cmd->next)
cmd = free_cmd(cmd, 0);
break ;
}
err = fill_struct(head, cmd, &idx_a, &idx_r);
head = head->next;
}
if (err)
cmd = free_cmd(cmd, 0);
return (cmd);
}
t_cmd *init_struct(int numargs, int numredir, int *err)
{
t_cmd *cmd;
cmd = ft_calloc(1, sizeof(t_cmd));
if (cmd)
{
cmd->args = ft_calloc(numargs + 3, sizeof(char *));
if (cmd->args)
{
cmd->redirect = ft_calloc(numredir + 1, sizeof(t_redirect));
if (cmd->redirect)
return (cmd);
}
}
free_cmd(cmd, 0);
*err = -1;
return (NULL);
}
int fill_struct(t_tok *head, t_cmd *cmd, int *idx_a, int *idx_r)
{
if (head->type == CMD)
{
cmd->cmd = ft_strdup(head->word);
if (!cmd->cmd)
return (-1);
}
else if (head->type == ARGS)
{
cmd->args[*idx_a] = ft_strdup(head->word);
if (!cmd->args[*idx_a])
return (-1);
*idx_a = *idx_a + 1;
}
else if (head->type >= HEREDOC)
{
cmd->redirect[*idx_r].type = head->type;
cmd->redirect[*idx_r].value = ft_strdup(head->word);
if (!cmd->redirect[*idx_r].value)
return (-1);
*idx_r = *idx_r + 1;
}
cmd->cmd_check = BIN;
return (0);
}
t_cmd *free_cmd(t_cmd *cmd, int i)
{
if (!cmd)
return (NULL);
if (cmd->cmd)
free(cmd->cmd);
if (cmd->args)
{
i = 0;
while (cmd->args[++i])
{
free(cmd->args[i]);
cmd->args[i] = NULL;
}
if (cmd->args[0])
{
free(cmd->args[0]);
cmd->args = NULL;
}
free(cmd->args);
cmd->args = NULL;
}
if (cmd->redirect)
free_redirs(cmd->redirect);
free(cmd);
return (NULL);
}
void free_redirs(t_redirect *redir)
{
int i;
i = -1;
while (redir[++i].value)
{
if (redir[i].type == HEREDOC)
unlink(redir[i].value);
free(redir[i].value);
}
free(redir);
}