Skip to content

Commit

Permalink
Add handling for paths relative to home (~) in rz_sys_chdir
Browse files Browse the repository at this point in the history
 * Also, simplify `cd` command handler
  • Loading branch information
DMaroo committed Oct 21, 2021
1 parent 43a2288 commit 1aac430
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 54 deletions.
69 changes: 16 additions & 53 deletions librz/core/cmd/cmd_cmp.c
Original file line number Diff line number Diff line change
Expand Up @@ -511,71 +511,34 @@ RZ_IPI RzCmdStatus rz_cmd_cmp_disasm_handler(RzCore *core, int argc, const char
// cd
RZ_IPI RzCmdStatus rz_cmd_chdir_handler(RzCore *core, int argc, const char **argv) {
static char *olddir = NULL;
if (argc == 2) {
if (!strcmp(argv[1], "-")) {
if (olddir) {
char *newdir = olddir;
olddir = rz_sys_getdir();
if (chdir(newdir) == -1) {
RZ_LOG_ERROR("Cannot chdir to %s\n", newdir);
free(olddir);
olddir = newdir;
} else {
free(newdir);
}
}
} else if (argv[1][0] == '~') {
if (argv[1][1] == '/') {
char *homepath = rz_str_home(argv[1] + 2);
if (homepath) {
char *cwd = rz_sys_getdir();
if (chdir(homepath) != -1) {
RZ_LOG_ERROR("Cannot chdir to %s\n", homepath);
free(cwd);
} else {
free(olddir);
olddir = cwd;
}
free(homepath);
} else {
RZ_LOG_ERROR("Cannot find home\n");
}
bool ret = true;
if (!strcmp(argv[1], "-")) {
if (olddir) {
char *newdir = olddir;
olddir = rz_sys_getdir();
if (!rz_sys_chdir(newdir)) {
RZ_LOG_ERROR("Cannot chdir to %s\n", newdir);
free(olddir);
olddir = newdir;
} else {
char *cwd = rz_sys_getdir();
char *home = rz_sys_getenv(RZ_SYS_HOME);
if (!home || chdir(home) == -1) {
eprintf("Cannot find home.\n");
free(cwd);
} else {
free(olddir);
olddir = cwd;
}
free(home);
free(newdir);
ret = true;
}
} else {
char *cwd = rz_sys_getdir();
if (chdir(argv[1]) == -1) {
RZ_LOG_ERROR("Cannot chdir to %s\n", argv[1]);
free(cwd);
} else {
free(olddir);
olddir = cwd;
}
RZ_LOG_ERROR("No old directory found\n");
}
} else {
char *cwd = rz_sys_getdir();
char *home = rz_sys_getenv(RZ_SYS_HOME);
if (!home || chdir(home) == -1) {
eprintf("Cannot find home.\n");
if (!rz_sys_chdir(argv[1])) {
RZ_LOG_ERROR("Cannot chdir to %s\n", argv[1]);
free(cwd);
} else {
free(olddir);
olddir = cwd;
ret = true;
}
free(home);
}

return RZ_CMD_STATUS_OK;
return ret ? RZ_CMD_STATUS_OK : RZ_CMD_STATUS_ERROR;
}

// cf
Expand Down
15 changes: 14 additions & 1 deletion librz/util/sys.c
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,20 @@ RZ_API char *rz_sys_getdir(void) {
}

RZ_API bool rz_sys_chdir(const char *s) {
rz_return_val_if_fail(s, 0);
rz_return_val_if_fail(s, false);
char *homepath = NULL;
if (s[0] == '~') {
if (strlen(s) == 1) {
homepath = rz_sys_getenv(RZ_SYS_HOME);
} else if (s[1] == '/') {
homepath = rz_str_home(s + 2);
}
}
if (homepath) {
int ret = chdir(homepath) == 0;
free(homepath);
return ret == 0;
}
return chdir(s) == 0;
}

Expand Down

0 comments on commit 1aac430

Please sign in to comment.