aboutsummaryrefslogtreecommitdiff
path: root/src/builtins_part_two.c
blob: e461861d50d66f89ac2724d67a32d8cba9d77045 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   builtins_part_two.c                                :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: chuhlig <chuhlig@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/10/25 20:52:16 by chuhlig           #+#    #+#             */
/*   Updated: 2025/01/20 19:12:33 by chuhlig          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "env.h"

void	update_oldpwd(t_env **env)
{
	t_env	*current;
	t_env	*prev;
	char	cwd[1028];
	char	*tmp;

	prev = NULL;
	current = *env;
	while (current)
	{
		if (ft_strncmp(current->name, "OLDPWD", 6) == 0)
			break ;
		prev = current;
		current = current->next;
	}
	getcwd(cwd, sizeof(cwd));
	tmp = ft_strdup(cwd);
	free(current->value);
	current->value = tmp;
}

void	update_pwd(t_env **env)
{
	t_env	*current;
	t_env	*prev;
	char	cwd[1028];
	char	*tmp;

	prev = NULL;
	current = *env;
	while (current)
	{
		if (ft_strncmp(current->name, "PWD", 3) == 0)
			break ;
		prev = current;
		current = current->next;
	}
	getcwd(cwd, sizeof(cwd));
	tmp = ft_strdup(cwd);
	free(current->value);
	current->value = tmp;
}

int	cd(t_env **env, char **av)
{
	t_env	*current;

	current = *env;
	if (av[1] == NULL)
	{
		update_oldpwd(env);
		while (current)
		{
			if (ft_strncmp(current->name, "HOME", 4) == 0)
				break ;
			current = current->next;
		}
		if (chdir(current->value) == -1)
			return (1);
		update_pwd(env);
	}
	else
	{
		update_oldpwd(env);
		if (chdir(av[1]) == -1)
			return (1);
		update_pwd(env);
	}
	return (0);
}

int	pwd(t_env *env)
{
	while (env)
	{
		if (ft_strncmp(env->name, "PWD", 4) == 0)
		{
			ft_printf("%s\n", env->value);
			break ;
		}
		env = env->next;
	}
	return (0);
}

int	ft_env(t_env *env)
{
	while (env != NULL)
	{
		if (ft_strchr(env->name, '?'))
		{
			env = env->next;
			continue ;
		}
		printf("%s", env->name);
		printf("=%s\n", env->value);
		env = env->next;
	}
	return (0);
}