summaryrefslogtreecommitdiffstats
path: root/src/s_set_cwd.c
blob: 38eb750e8859895da85f6eac066c043faa2ae9c5 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   s_init_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 <dirent.h>
#include <errno.h>
#include <libft.h>
#ifdef __linux__
# include <linux/limits.h>
#else
# include <limits.h>
#endif
#include <paths.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "b_export_next.h"
#include "f_fail.h"
#include "s_destroy.h"
#include "s_struct.h"
#include "u_vars.h"
#include "u_vars_next.h"

static void
	s_set_cwd_next(char *cwd, char *fmt, t_msh *msh)
{
	if (getcwd(cwd, PATH_MAX) != NULL)
	{
		ft_sprintf(fmt, "%s=%s", "PWD", cwd);
		b_export_with_equals(fmt, msh);
	}
	else
	{
		ft_dprintf(STDERR_FILENO, "minishell: %s\n", strerror(errno));
	}
}

void
	s_set_cwd(char cwd[], t_msh *msh)
{
	char	fmt[PATH_MAX];
	DIR		*dir;

	u_get_var_value(cwd, "$PWD", PATH_MAX, msh);
	if (cwd[0] == C_NUL)
	{
		if (getcwd(cwd, PATH_MAX) != NULL)
		{
			ft_sprintf(fmt, "%s=%s", "PWD", cwd);
			b_export_with_equals(fmt, msh);
		}
		else
		{
			ft_dprintf(STDERR_FILENO, "minishell: %s\n", strerror(errno));
		}
		return ;
	}
	if ((dir = opendir(cwd)) != NULL)
	{
		closedir(dir);
	}
	else if (errno == ENOENT)
	{
		s_set_cwd_next(cwd, fmt, msh);
	}
}