Skip to content

Commit 2262759

Browse files
committed
Add :cd argument to os/execute and os/spawn.
1 parent e8187fd commit 2262759

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/core/os.c

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1150,6 +1150,7 @@ static Janet os_execute_impl(int32_t argc, Janet *argv, JanetExecuteMode mode) {
11501150
JanetAbstract orig_in = NULL, orig_out = NULL, orig_err = NULL;
11511151
JanetHandle new_in = JANET_HANDLE_NONE, new_out = JANET_HANDLE_NONE, new_err = JANET_HANDLE_NONE;
11521152
JanetHandle pipe_in = JANET_HANDLE_NONE, pipe_out = JANET_HANDLE_NONE, pipe_err = JANET_HANDLE_NONE;
1153+
const char *chdir_path = NULL;
11531154
int stderr_is_stdout = 0;
11541155
int pipe_errflag = 0; /* Track errors setting up pipes */
11551156
int pipe_owner_flags = (is_spawn && (flags & 0x8)) ? JANET_PROC_ALLOW_ZOMBIE : 0;
@@ -1182,6 +1183,17 @@ static Janet os_execute_impl(int32_t argc, Janet *argv, JanetExecuteMode mode) {
11821183
}
11831184
}
11841185

1186+
/* Optional working directory. Available for both os/execute and os/spawn. */
1187+
if (argc > 2) {
1188+
JanetDictView tab = janet_getdictionary(argv, 2);
1189+
Janet workdir = janet_dictionary_get(tab.kvs, tab.cap, janet_ckeywordv("cd"));
1190+
if (janet_checktype(workdir, JANET_STRING)) {
1191+
chdir_path = (const char *) janet_unwrap_string(workdir);
1192+
} else if (!janet_checktype(workdir, JANET_NIL)) {
1193+
janet_panicf("expected string for `:cd` argumnet, got %v", workdir);
1194+
}
1195+
}
1196+
11851197
/* Clean up if any of the pipes have any issues */
11861198
if (pipe_errflag) {
11871199
if (pipe_in != JANET_HANDLE_NONE) close_handle(pipe_in);
@@ -1212,6 +1224,10 @@ static Janet os_execute_impl(int32_t argc, Janet *argv, JanetExecuteMode mode) {
12121224
}
12131225
const char *path = (const char *) janet_unwrap_string(exargs.items[0]);
12141226

1227+
if (chdir_path != NULL) {
1228+
startupInfo.lpCurrentDirectory = chdir_path;
1229+
}
1230+
12151231
/* Do IO redirection */
12161232

12171233
if (pipe_in != JANET_HANDLE_NONE) {
@@ -1305,6 +1321,9 @@ static Janet os_execute_impl(int32_t argc, Janet *argv, JanetExecuteMode mode) {
13051321
/* Posix spawn setup */
13061322
posix_spawn_file_actions_t actions;
13071323
posix_spawn_file_actions_init(&actions);
1324+
if (chdir_path != NULL) {
1325+
posix_spawn_file_actions_addchdir_np(&actions, chdir_path);
1326+
}
13081327
if (pipe_in != JANET_HANDLE_NONE) {
13091328
posix_spawn_file_actions_adddup2(&actions, pipe_in, 0);
13101329
posix_spawn_file_actions_addclose(&actions, pipe_in);

0 commit comments

Comments
 (0)