minishell/srcs/cmd_cd.c
Tanguy MAZE 9dc92563e3 WIP added basic cd command
The command only works with `-`, absolut paths and empty arg
No option has been added
2019-01-21 17:35:57 +01:00

93 lines
2.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cmd_cd.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tmaze <tmaze@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/01/07 16:44:40 by tmaze #+# #+# */
/* Updated: 2019/01/21 17:06:19 by tmaze ### ########.fr */
/* */
/* ************************************************************************** */
#include "minishell.h"
void put_error_cd(char *file, char *msg)
{
ft_putstr("cd: ");
ft_putstr(file);
ft_putstr(": ");
ft_putendl(msg);
}
char *check_path_slash_cd(char *exec)
{
int i;
struct stat info;
if (ft_isin(exec, '/') != -1 && ft_isin(exec, '.') == -1)
{
if ((i = access(exec, F_OK)) != 0)
put_error_cd(exec, "no such file or directory");
if (i != 0)
return (NULL);
if ((i = stat(exec, &info)) != 0)
put_error_cd(exec, "can't determine info");
if (i != 0)
return (NULL);
if (!S_ISDIR(info.st_mode))
{
put_error_cd(exec, "not a directory");
return (NULL);
}
if ((i = access(exec, X_OK)) != 0)
put_error_cd(exec, "permission denied");
if (i != 0)
return (NULL);
return (exec);
}
return (NULL);
}
int cmd_cd_core(char *path, t_list **env)
{
t_envelem *pwd;
char *oldpwd;
if (check_path_slash_cd(path) == NULL)
return (1);
if (chdir(path) == -1
|| (pwd = env_getelemfromkey("PWD", *env)) == NULL)
{
put_error_cd(path, "error");
return (1);
}
if ((oldpwd = ft_strdup(pwd->val)) == NULL)
{
put_error_cd(path, "error");
return (1);
}
if (env_addupdate("PWD", path, env) == NULL
|| env_addupdate("OLDPWD", oldpwd, env) == NULL)
{
put_error_cd(path, "error");
ft_strdel(&oldpwd);
return (1);
}
ft_strdel(&oldpwd);
return (0);
}
int cmd_cd(char **argv, t_list **env)
{
t_envelem *elem;
if (!argv[1] && (elem = env_getelemfromkey("HOME", *env))->val != NULL)
return (cmd_cd_core(elem->val, env));
else if (argv[1] && argv[1][0] == '/')
return (cmd_cd_core(argv[1], env));
else if (argv[1] && argv[1][0] == '-' && (elem = env_getelemfromkey("OLDPWD", *env)) != NULL)
return (cmd_cd_core(elem->val, env));
return (0);
}