// Copyright (C) 2023, Jakob Wakeling // All rights reserved. #include "../util/optget.h" #include "../util/util.h" #include #include #include #include #include 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" ;