HelenOS sources
This source file includes following definitions.
- chdir_and_remember
- help_cmd_cd
- cmd_cd
#include <stdio.h>
#include <stdlib.h>
#include <str.h>
#include <errno.h>
#include <vfs/vfs.h>
#include "util.h"
#include "errors.h"
#include "entry.h"
#include "cmds.h"
#include "cd.h"
static const char *cmdname = "cd";
static char previous_directory[PATH_MAX] = "";
static char previous_directory_tmp[PATH_MAX];
static bool previous_directory_valid = true;
static bool previous_directory_set = false;
static errno_t chdir_and_remember(const char *new_dir)
{
errno_t rc = vfs_cwd_get(previous_directory_tmp, PATH_MAX);
previous_directory_valid = (rc == EOK);
previous_directory_set = true;
rc = vfs_cwd_set(new_dir);
if (rc != EOK)
return rc;
str_cpy(previous_directory, PATH_MAX, previous_directory_tmp);
return EOK;
}
void help_cmd_cd(unsigned int level)
{
if (level == HELP_SHORT) {
printf("`%s' changes the current working directory.\n", cmdname);
} else {
printf(
" %s <directory>\n"
" Change directory to <directory>, e.g `%s /sbin'\n",
cmdname, cmdname);
}
return;
}
int cmd_cd(char **argv, cliuser_t *usr)
{
int argc;
errno_t rc = EOK;
argc = cli_count_args(argv);
bool hyphen_override = false;
char *target_directory = argv[1];
if (argc == 3) {
if (!str_cmp(argv[1], "--")) {
hyphen_override = true;
argc--;
target_directory = argv[2];
}
}
if (argc > 2) {
cli_error(CL_EFAIL, "Too many arguments to `%s'", cmdname);
return CMD_FAILURE;
}
if (argc < 2) {
printf("%s - no directory specified. Try `help %s extended'\n",
cmdname, cmdname);
return CMD_FAILURE;
}
if (!str_cmp(target_directory, "-") && !hyphen_override) {
if (!previous_directory_valid) {
cli_error(CL_EFAIL, "Cannot switch to previous directory");
return CMD_FAILURE;
}
if (!previous_directory_set) {
cli_error(CL_EFAIL, "No previous directory to switch to");
return CMD_FAILURE;
}
char *prev_dup = str_dup(previous_directory);
if (prev_dup == NULL) {
cli_error(CL_ENOMEM, "Cannot switch to previous directory");
return CMD_FAILURE;
}
rc = chdir_and_remember(prev_dup);
free(prev_dup);
} else {
rc = chdir_and_remember(target_directory);
}
if (rc == 0) {
cli_set_prompt(usr);
return CMD_SUCCESS;
} else {
switch (rc) {
case ENOMEM:
cli_error(CL_EFAIL, "Destination path too long");
break;
case ENOENT:
cli_error(CL_ENOENT, "Invalid directory `%s'", target_directory);
break;
default:
cli_error(CL_EFAIL, "Unable to change to `%s'", target_directory);
break;
}
}
return CMD_FAILURE;
}
HelenOS homepage, sources at GitHub