aboutsummaryrefslogtreecommitdiff
path: root/src/builtin/export.c
blob: 6fbb88f6cda0b7053d3c7bcffd1b2f66c64a3f25 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   export.c                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: charles <charles@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/04/01 17:11:34 by charles           #+#    #+#             */
/*   Updated: 2020/07/19 18:46:48 by charles          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

/*
** \file   export.c
** \brief  `export` builtin
*/

#include "minishell.h"

static void	st_put_declare_x(char *s)
{
	char	*equal_ptr;

	// could use errorf on stdout
	if (s == NULL)
		return ;
	ft_putstr("declare -x ");
	if ((equal_ptr = ft_strchr(s, '=')) == NULL)
		equal_ptr = ft_strchr(s, '\0');
	write(STDOUT_FILENO, s, equal_ptr - s);
	ft_putchar('=');
	ft_putchar('"');
	ft_putstr(equal_ptr + 1);
	ft_putchar('"');
	ft_putchar('\n');
}

int			builtin_export(char **argv, t_env env)
{
	int		status;
	size_t  i;
	char	*equal_ptr;
	bool	skip;

	if (argv[1] == NULL)
	{
		ft_veciter(env, (void (*)(void*))st_put_declare_x);
		return (0);
	}
	status = 0;
	i = 0;
	while (argv[++i] != NULL)
	{
		skip = (equal_ptr = ft_strchr(argv[i], '=')) == NULL;
		if (!skip)
			*equal_ptr = '\0';
		if (!utils_valid_identifier(argv[i]))
		{
			if (!skip)
				*equal_ptr = '=';
			errorf("export: `%s': not a valid identifier\n", argv[i]);
			status = 1;
			continue;
		}
		if (skip)
			continue;
		if (env_export(env, argv[i], equal_ptr + 1) == NULL)
			return (127); // malloc error
	}
	return (status);
}