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
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* format_string.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: chuhlig <chuhlig@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/17 19:30:11 by chuhlig #+# #+# */
/* Updated: 2025/01/14 14:21:36 by chuhlig ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#include "libft.h"
#include "minishell.h"
static void append_slice(char **dst, char *src, int start, int end);
static void append_var(char **dst, char *src, int *pos, t_env *env);
char *format_string(char *str, t_env *env)
{
char *result;
int pos;
int start;
int mode;
pos = 0;
start = 0;
mode = 0;
result = NULL;
if (str == NULL)
return (NULL);
while (str[pos] != '\0')
{
if (str[pos] == '\'')
{
append_slice(&result, str, start, pos);
start = pos + 1;
mode ^= 1;
}
if (str[pos] == '"' && !(mode & 1))
{
append_slice(&result, str, start, pos);
start = pos + 1;
}
if (str[pos] == '$' && !(mode & 1))
{
append_slice(&result, str, start, pos);
append_var(&result, str, &pos, env);
start = pos;
continue ;
}
pos++;
}
append_slice(&result, str, start, pos);
return (result);
}
static void append_slice(char **dst, char *src, int start, int end)
{
char *result;
int len;
int i;
if (*dst != NULL)
len = ft_strlen(*dst);
else
{
len = 0;
}
result = malloc(len + (end - start) + 1);
if (!result)
return ;
ft_strncpy(result, *dst, len);
i = 0;
while (start + i < end)
{
result[len + i] = src[start + i];
i++;
}
result[len + i] = '\0';
if (*dst != NULL)
free(*dst);
*dst = result;
}
static void append_var(char **dst, char *src, int *pos, t_env *env)
{
int i;
char *var;
char *value;
char *result;
i = 0;
*pos += 1;
while (src[*pos + i] != '\0' && src[*pos + i] != '\'' && src[*pos
+ i] != '"' && src[*pos + i] != '$')
{
i++;
}
var = malloc(i + 1);
if (var == NULL)
return ;
var[i] = '\0';
i--;
while (i >= 0)
{
var[i] = src[*pos + i];
i--;
}
value = env_get(env, var);
if (value != NULL)
{
result = ft_strjoin(*dst, value);
free(*dst);
*dst = result;
}
*pos += ft_strlen(var);
}
|