-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathms_replace_env.c
More file actions
90 lines (83 loc) · 2.45 KB
/
ms_replace_env.c
File metadata and controls
90 lines (83 loc) · 2.45 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ms_replace_env.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jinsecho <jinsecho@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/28 16:06:41 by jinsecho #+# #+# */
/* Updated: 2024/12/17 23:22:17 by jinsecho ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
static void replace_env_find(t_cmd *cmd, char **ptr, char *line, int *n)
{
char *tmp;
int i;
i = 0;
while (ft_isalnum(line[*n]) || line[*n] == '_')
(*n)++;
tmp = (char *)malloc(sizeof(char) * (*n));
if (tmp == NULL)
exit (EXIT_FAILURE);
ft_strlcpy(tmp, line + 1, *n);
while (cmd->envp[i])
{
if (ft_envchr(cmd->envp[i], tmp))
{
*ptr = ft_strdup(ft_strchr(cmd->envp[i], '=') + 1);
free(tmp);
return ;
}
i++;
}
*ptr = ft_strdup("");
free(tmp);
}
static char *ms_str_replace_env(t_cmd *cmd, char *line, int *n)
{
char *ptr;
*n = 1;
if (line[*n] == '?')
{
*n = 2;
ptr = ft_itoa(cmd->sts.process_status);
}
else if (ft_isalpha(line[*n]) || line[*n] == '_')
replace_env_find(cmd, &ptr, line, n);
else if (ft_isdigit(line[*n]))
{
*n = 2;
ptr = ft_strdup("");
}
else
ptr = ft_strdup("");
return (ptr);
}
void ms_line_replace_env(t_cmd *cmd, char **ptr, char *line)
{
t_env_var env;
env.cnt = 0;
while ((*ptr)[env.cnt] != '$' && (*ptr)[env.cnt])
(env.cnt)++;
while ((*ptr)[env.cnt])
{
env.env_tmp = ms_str_replace_env(cmd, &(*ptr)[env.cnt], &env.n);
if (env.n == 1)
(env.cnt)++;
else
{
env.len = ft_strlen(line) + ft_strlen(env.env_tmp);
*ptr = ft_realloc(*ptr, env.len + 1);
env.str_tmp = ft_strdup(&(*ptr)[env.cnt] + env.n);
ft_strlcpy(\
&(*ptr)[env.cnt], env.env_tmp, ft_strlen(env.env_tmp) + 1);
ft_strlcat(*ptr, env.str_tmp, env.len + 1);
env.cnt += ft_strlen(env.env_tmp);
free(env.str_tmp);
}
while ((*ptr)[env.cnt] != '$' && (*ptr)[env.cnt])
(env.cnt)++;
free(env.env_tmp);
}
}