You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

136 lines
2.8 KiB

3 years ago
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* env.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/02/16 09:41:29 by narnaud #+# #+# */
/* Updated: 2022/05/06 13:39:03 by narnaud ### ########.fr */
3 years ago
/* */
/* ************************************************************************** */
#include "minishell.h"
int is_valid_identifier(char *ident)
3 years ago
{
if (ft_isalpha(ident[0]) || ident[0] == '_')
3 years ago
{
while (*ident)
{
if (!ft_isalpha(*ident) && !ft_isdigit(*ident) && *ident != '_')
return (0);
ident++;
}
3 years ago
return (1);
}
return (0);
}
3 years ago
void clean_env(t_datas *datas)
{
int i;
int j;
3 years ago
3 years ago
i = 0;
j = 0;
while (i < 1024)
{
if (!datas->envp[i])
{
j = 1;
while (!datas->envp[i + j] && (i + j) < 1024)
j++;
if (i + j == 1024)
return ;
datas->envp[i] = datas->envp[i + j];
datas->envp[i + j] = NULL;
}
i++;
}
}
int ft_unset(t_datas *datas, t_command *cmd)
3 years ago
{
3 years ago
char **env;
int i;
int j;
int name_len;
if (cmd->argc < 2)
return (1);
3 years ago
env = datas->envp;
i = 1;
while (i < cmd->argc && datas->envp[i - 1])
{
name_len = ft_strlen(cmd->argv[i]);
j = 0;
while (datas->envp[j])
{
env = ft_split(datas->envp[j], '=');
if (!ft_strncmp(cmd->argv[i], env[0], name_len + 1))
{
free(datas->envp[j]);
datas->envp[j] = NULL;
clean_env(datas);
continue;
}
ft_free_split(env);
j++;
}
i++;
3 years ago
}
return (0);
}
int ft_env(t_datas *datas, t_command *cmd)
3 years ago
{
int i;
int fd_out;
if (cmd->fd[1])
fd_out = cmd->fd[1];
else
fd_out = 1;
i = 0;
while (datas->envp[i])
3 years ago
{
ft_putstr_fd(datas->envp[i], fd_out);
ft_putchar_fd('\n', fd_out);
i++;
3 years ago
}
return (0);
}
int ft_export(t_datas *datas, t_command *cmd)
3 years ago
{
char **new;
3 years ago
int name_len;
3 years ago
char **env;
int i;
i = 0;
3 years ago
if (cmd->argc < 2)
return (0);
new = ft_split(cmd->argv[1], '=');
3 years ago
name_len = ft_strlen(new[0]);
3 years ago
if (!is_valid_identifier(new[0]))
{
ft_putstr_fd("export: not an identifier: ", 2);
ft_putstr_fd(new[0], 2);
ft_putchar_fd('\n', 2);
3 years ago
return (0);
}
while (datas->envp[i])
3 years ago
{
env = ft_split(datas->envp[i], '=');
3 years ago
if (!ft_strncmp(new[0], env[0], name_len + 1))
3 years ago
{
3 years ago
datas->envp[i] = ft_strdup(cmd->argv[1]);
3 years ago
return (1);
}
3 years ago
ft_free_split(env);
3 years ago
i++;
}
3 years ago
datas->envp[i] = ft_strdup(cmd->argv[1]);
3 years ago
return (1);
}