summaryrefslogtreecommitdiffstats
path: root/src/u_vars_next.c
blob: 8134de3621319d9e050967f5cd585e113a7af927 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   u_vars_next.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 <inttypes.h>
#include <stdlib.h>

#include "s_struct.h"

static int64_t
	u_get_var_line(const char varname[],
				t_msh *msh)
{
	char	**env_ptr;
	int64_t	i;

	env_ptr = msh->envp;
	i = 0;
	while (*env_ptr &&
		ft_strncmp(*env_ptr, varname, ft_strlen(varname)) != 0)
	{
		env_ptr++;
		i++;
	}
	if (*env_ptr)
		return (i);
	else
		return (-1);
}

/*
** void
** u_subst_var_value(const char varname[], const char newval[], t_msh *msh);
**
** DESCRIPTION
** The subst_var_value() changes the value of msh->envp
** variable varname[] with newval[]. If varname[] wasn't found
** in msh->envp, varname[] is searched in msh->vars.
*/

void
	u_subst_var_value(const char varname[],
					const char newval[],
					t_msh *msh)
{
	char	new_line_fmt[2048];
	int64_t	env_line;

	if ((env_line = u_get_var_line(varname + 1, msh)) > -1)
	{
		ft_memdel((void*)&msh->envp[env_line]);
		ft_sprintf(new_line_fmt, "%s=%s", varname + 1, newval);
		if (!(msh->envp[env_line] =
			  (char*)malloc((ft_strlen(new_line_fmt) + 1) * sizeof(char))))
		{
			/* TODO: Handle this fail */
		}
		(void)ft_strlcpy(msh->envp[env_line], new_line_fmt, ft_strlen(new_line_fmt) + 1);
	}
	else
	{
		/* TODO: Search in custom vars */
	}
}