summaryrefslogtreecommitdiffstats
path: root/src/p_subst_vars.c
blob: 823970bc5985dbd024b0b8068030c33c4f4b9ae2 (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   p_subst_vars.c                                     :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: rbousset <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:19:27 by rbousset          #+#    #+#             */
/*   Updated: 2020/02/14 17:19:29 by rbousset         ###   ########lyon.fr   */
/*                                                                            */
/* ************************************************************************** */

#include <libft.h>
#include <stddef.h>

#include "d_define.h"
#include "s_struct.h"
#include "u_parse.h"
#include "u_utils.h"
#include "u_vars.h"

static char	*p_double_them_bs(char varval[])
{
	char	*ptr;

	ptr = varval;
	while (*ptr != C_NUL)
	{
		if (*ptr == C_BACKS)
		{
			ptr = ft_memmove(ptr + 1, ptr, ft_strlen(ptr) + 1);
			varval[ptr - varval] = C_BACKS;
		}
		ptr++;
	}
	return (varval);
}

static void	p_subst_this_var(char **p, long i, char word[], t_msh *msh)
{
	char	tmp[ARG_MAX];
	char	varval[ARG_MAX];
	char	*ptr;
	size_t	varlen;

	ptr = word;
	varlen = i + 1;
	while (ptr[varlen] != C_NUL &&
		ft_ischarset("$=\\/@%^*+{}[]<>(),.-", ptr[varlen]) == FALSE
		&& ft_iswhitespace(ptr[varlen]) == FALSE)
		varlen += 1;
	ft_strlcpy(tmp, ptr + i, varlen + 1 - i);
	u_get_var_value(varval, tmp, ARG_MAX, msh);
	p_double_them_bs(varval);
	(void)ft_memmove(ptr + (i + ft_strlen(varval)),
		ptr + varlen,
		(ft_strlen(ptr + varlen) + 1) * sizeof(char));
	(void)ft_memmove(word + i, varval, ft_strlen(varval) * sizeof(char));
	*(p) = word + (i + ft_strlen(varval) - 1);
}

void		p_subst_vars(char word[], t_msh *msh)
{
	char			*ptr;
	t_quote_mode	mode;

	mode = Q_NONE;
	ptr = word;
	while (*ptr != C_NUL)
	{
		if (*ptr == C_DQUOTE)
			mode = u_meet_dquote(word, ptr, mode);
		else if (*ptr == C_SQUOTE)
			mode = u_meet_squote(word, ptr, mode);
		if ((mode == Q_NONE || mode == Q_DOUBLE) && *ptr == C_DOLLAR &&
			u_is_not_escaped(word, ptr) == TRUE)
		{
			p_subst_this_var(&ptr, (ptr - word), word, msh);
		}
		ptr++;
	}
}