diff --git a/src/builtin.c b/src/builtin.c index cf023a3..b562c82 100644 --- a/src/builtin.c +++ b/src/builtin.c @@ -6,7 +6,7 @@ /* By: jschaft +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/06/03 12:02:45 by jschaft #+# #+# */ -/* Updated: 2024/07/01 14:20:51 by mcolonna ### ########.fr */ +/* Updated: 2024/07/02 11:26:26 by mcolonna ### ########.fr */ /* */ /* ************************************************************************** */ diff --git a/src/builtin2.c b/src/builtin2.c index abe9df3..659793d 100644 --- a/src/builtin2.c +++ b/src/builtin2.c @@ -6,7 +6,7 @@ /* By: jschaft +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/06/25 13:28:29 by jschaft #+# #+# */ -/* Updated: 2024/07/01 14:18:19 by mcolonna ### ########.fr */ +/* Updated: 2024/07/02 11:21:53 by mcolonna ### ########.fr */ /* */ /* ************************************************************************** */ @@ -90,35 +90,41 @@ int echo_builtin(t_env *env, t_call call, int std[2]) return (0); } -static int go_home(t_env *env) +static const char *go_home(t_env *env, bool to_old) { - return (chdir(variables_get(env->variables, "HOME"))); + if (!to_old) + return (variables_get(env->variables, "HOME")); + else + return (variables_get(env->variables, "OLDPWD")); } // Execute the builtin cd for the specified path. // Return 0 if success, errno if error. int cd_builtin(t_env *env, t_call call, int std[2]) { - int r; - int argc; + int r; + const char *pwd; + bool go_oldpwd; (void)std; - argc = 0; - while (call.argv[argc]) - argc++; - if (argc == 2) - r = chdir(call.argv[1]); - else if (argc == 1) - r = go_home(env); + go_oldpwd = call.argc > 1 && str_eq(call.argv[1], "-"); + if (call.argc == 1 || go_oldpwd) + pwd = go_home(env, go_oldpwd); + else if (call.argc == 2) + pwd = call.argv[1]; else - { - print_line(fatal_error, 2, "cd: too many arguments"); - return (1); - } + return (print_line(fatal_error, 2, "cd: too many arguments"), 1); + r = chdir(pwd); if (r) - { - perror("cd"); - return (errno); - } + return (perror("cd"), errno); + mem_free((char *)variables_get(env->variables, "OLDPWD")); + variables_set(env->variables, "OLDPWD", + variables_get(env->variables, "PWD")); + pwd = getcwd(NULL, 0); + variables_set(env->variables, "PWD", + str_dup(fatal_error, env->mc_global, pwd)); + if (go_oldpwd) + print_line(fatal_error, 1, pwd); + free((char *)pwd); return (0); }