01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
|
// Copyright (C) 2023, Jakob Wakeling
// All rights reserved.
#include "../util/optget.h"
#include "../util/util.h"
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *const help;
extern const char *const version; /* main.c */
int bltn_cd(int, char *av[]) {
struct opt opt = OPTGET_INIT; opt.str = "LP"; opt.lops = (struct lop[]){
{ "help", ARG_NUL, 256 },
{ "version", ARG_NUL, 257 },
{ NULL, 0, 0 },
};
struct { s32 mode; } args = {};
for (int c; (c = optget(&opt, av, 1)) != -1;) {
switch (c) {
case 'L': { args.mode = 0; } break;
case 'P': { args.mode = 1; } break;
case 256: { fputs(help, stdout); } return 0;
case 257: { fputs(version, stdout); } return 0;
default: {} return -1;
}
}
char *path = av[opt.ind] ? av[opt.ind] : getenv("HOME");
if (chdir(path)) {
fprintf(stderr, "%s: %s: %s\n", av[0], path, strerror(errno));
errno = 0; return -1;
}
path = getcwd(NULL, 0); setenv("PWD", path, 1);
free(path); return 0;
}
static const char *const help =
"cd - change directory\n"
"Usage:\n"
" cd [-L|-P] [directory]\n"
"Options:\n"
" -L Handle the operand dot-dot logically\n"
" -P Handle the operand dot-dot physically\n"
" --help Display help information\n"
" --version Display version information\n"
;
|