#include "config.h"
#include <sys/queue.h>
#include <bitstring.h>
#include <errno.h>
#include <limits.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "../common/common.h"
int
ex_cd(SCR *sp, EXCMD *cmdp)
{
struct passwd *pw;
ARGS *ap;
CHAR_T savech;
char *dir, *p, *t;
char buf[PATH_MAX * 2];
if (F_ISSET(sp->ep, F_MODIFIED) &&
!FL_ISSET(cmdp->iflags, E_C_FORCE) && sp->frp->name[0] != '/') {
msgq(sp, M_ERR,
"File modified since last complete write; write or use ! to override");
return (1);
}
switch (cmdp->argc) {
case 0:
if ((dir = getenv("HOME")) == NULL || *dir == '\0') {
if ((pw = getpwuid(getuid())) == NULL ||
pw->pw_dir == NULL || pw->pw_dir[0] == '\0') {
msgq(sp, M_ERR,
"Unable to find home directory location");
return (1);
}
dir = pw->pw_dir;
}
break;
case 1:
dir = cmdp->argv[0]->bp;
break;
default:
abort();
}
if (!chdir(dir))
return (0);
if (cmdp->argc == 0 ||
(ap = cmdp->argv[0])->bp[0] == '/' ||
(ap->len == 1 && ap->bp[0] == '.') ||
(ap->len >= 2 && ap->bp[0] == '.' && ap->bp[1] == '.' &&
(ap->bp[2] == '/' || ap->bp[2] == '\0')))
goto err;
for (p = t = O_STR(sp, O_CDPATH);; ++p)
if (*p == '\0' || *p == ':') {
if (t < p - 1) {
savech = *p;
*p = '\0';
(void)snprintf(buf,
sizeof(buf), "%s/%s", t, dir);
*p = savech;
if (!chdir(buf)) {
if (getcwd(buf, sizeof(buf)) != NULL)
msgq_str(sp, M_INFO, buf, "New current directory: %s");
return (0);
}
}
t = p + 1;
if (*p == '\0')
break;
}
err: msgq_str(sp, M_SYSERR, dir, "%s");
return (1);
}