ref: 2a05412dd738b8f4fd3094cf44098b350252b95f minishell/src/builtin/cd.c -rw-r--r-- 2.0 KiB View raw
                                                                                
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   minishell                                          :+:    :+:            */
/*                                                     +:+                    */
/*   By: dkroeke <dkroeke@student.codam.nl>           +#+                     */
/*       nloomans <nloomans@student.codam.nl>        +#+                      */
/*                                                  #+#    #+#                */
/*   License: MIT                                  ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include <ft_printf.h>
#include <libft.h>
#ifdef __linux__
# include <linux/limits.h>
#else
# include <limits.h>
#endif
#include <unistd.h>
#include "env.h"
#include "builtin.h"

static int	cd(t_env **env, char *old_path, char *new_path)
{
	if (chdir(new_path) == -1)
		return (-1);
	env_set(env, "OLDPWD", old_path);
	env_set(env, "PWD", new_path);
	return (0);
}

int			builtin_cd(int argc, char **argv, t_env **env)
{
	char	old_path[PATH_MAX];
	char	new_path[PATH_MAX];

	getcwd(old_path, PATH_MAX);
	if (argc > 2)
		return (ft_eprintf(1, "cd: to many arguments\n"));
	if (argc == 1)
	{
		if (!env_has(*env, "HOME"))
			return (ft_eprintf(1, "cd: $HOME not set\n"));
		ft_strlcpy(new_path, env_get_unsafe_ptr(*env, "HOME"), PATH_MAX);
	}
	else if (ft_strcmp(argv[1], "-") == 0)
	{
		if (!env_has(*env, "OLDPWD"))
			return (ft_eprintf(1, "cd: $OLDPWD not set\n"));
		ft_strlcpy(new_path, env_get_unsafe_ptr(*env, "OLDPWD"), PATH_MAX);
		ft_printf("%s\n", new_path);
	}
	else
		ft_strlcpy(new_path, argv[1], PATH_MAX);
	if (cd(env, old_path, new_path) == -1)
		return (ft_eprintf(1, "cd: unable to change dir '%s'\n", new_path));
	return (0);
}