`exec` drops `-e`, `-w`, `-u` and flattens the exit code to 1
mocker version: 0.9.7 (Homebrew) — macOS 27, container 1.5.0, arm64; reproduced on 0.9.6 and again on 0.9.7. Code references are against main @ 4402015.
Summary
Exec.swift declares Docker's -e, --env-file, -u, -w and -d (Exec.swift:23-38), but ContainerEngine.exec forwards only -i/-t (ContainerEngine.swift:435-446), although container exec 1.5.0 supports every one of them. The command also goes through the buffered runCLI, so stdout is held until exit, stderr is dropped whenever stdout is non-empty, every non-zero status becomes 1 (:449), and exec -it sh is not usable.
Reproduction
$ mocker run -d --name t alpine:3.20 sleep 120
$ mocker exec -e FOO=bar t printenv FOO
# Docker: bar
$ mocker exec -w /tmp t pwd
/ # Docker: /tmp
$ mocker exec -u nobody t id -u
0 # Docker: 65534
$ mocker exec t sh -c 'exit 3'; echo $?
1 # Docker: 3
Proposed behaviour (what the branch does)
exec builds its argument vector in a pure, tested helper (-e/--env-file/-u/-w/-d forwarded, all before the container name), runs container exec on the caller's stdio, and the CLI exits with the command's own status. compose exec forwards its -e/-u/-w/-d the same way.
After:
$ mocker exec -e FOO=bar t printenv FOO
bar
$ mocker exec -w /tmp t pwd
/tmp
$ mocker exec -u nobody t id -u
65534
$ mocker exec -e HOME t printenv HOME # bare -e inherits from the host, as in Docker
/Users/me
$ mocker exec t sh -c 'exit 3'; echo $?
3
A tested fix is on my fork, branch fix/exec-forward-flags (compare); the diff is below. Happy to open it as a PR if you want it, or you can take it from here — see the note in #
Proposed fix: git diff main...fix/exec-forward-flags
diff --git a/Sources/Mocker/Commands/Compose.swift b/Sources/Mocker/Commands/Compose.swift
index efff34b..dfcdd92 100644
--- a/Sources/Mocker/Commands/Compose.swift
+++ b/Sources/Mocker/Commands/Compose.swift
@@ -924,7 +924,11 @@ struct ComposeExec: AsyncParsableCommand {
}
let engine = try ContainerEngine(config: config)
- try await engine.exec(containerName, command: command, interactive: interactive, tty: tty)
+ let status = try await engine.exec(
+ containerName, command: command, interactive: interactive, tty: tty, detach: detach,
+ env: env, user: user, workdir: workdir
+ )
+ if status != 0 { throw ExitCode(status) }
}
}
diff --git a/Sources/Mocker/Commands/Exec.swift b/Sources/Mocker/Commands/Exec.swift
index 220356d..5abc4c2 100644
--- a/Sources/Mocker/Commands/Exec.swift
+++ b/Sources/Mocker/Commands/Exec.swift
@@ -49,6 +49,11 @@ struct Exec: AsyncParsableCommand {
func run() async throws {
let config = MockerConfig()
let engine = try ContainerEngine(config: config)
- try await engine.exec(container, command: command, interactive: interactive, tty: tty)
+ let status = try await engine.exec(
+ container, command: command, interactive: interactive, tty: tty, detach: detach,
+ env: env, envFiles: envFile, user: user, workdir: workdir
+ )
+ // Exit with the command's own status, as `docker exec` does.
+ if status != 0 { throw ExitCode(status) }
}
}
diff --git a/Sources/MockerKit/Container/ContainerEngine.swift b/Sources/MockerKit/Container/ContainerEngine.swift
index f4cc69d..376c9ac 100644
--- a/Sources/MockerKit/Container/ContainerEngine.swift
+++ b/Sources/MockerKit/Container/ContainerEngine.swift
@@ -432,22 +432,55 @@ public actor ContainerEngine {
// MARK: - Exec
- public func exec(_ identifier: String, command: [String], interactive: Bool = false, tty: Bool = false) async throws {
+ /// Argument vector for `container exec`. Pure, so the flag forwarding is unit-testable.
+ static func makeExecArguments(
+ name: String, command: [String], interactive: Bool = false, tty: Bool = false,
+ detach: Bool = false, env: [String] = [], envFiles: [String] = [],
+ user: String? = nil, workdir: String? = nil
+ ) -> [String] {
+ var args = ["exec"]
+ if interactive { args.append("-i") }
+ if tty { args.append("-t") }
+ if detach { args.append("-d") }
+ for e in env { args += ["-e", e] }
+ for f in envFiles { args += ["--env-file", f] }
+ if let user { args += ["-u", user] }
+ if let workdir { args += ["-w", workdir] }
+ args.append(name)
+ args += command
+ return args
+ }
+
+ /// Run `command` in a running container on the caller's stdio and return its exit status.
+ ///
+ /// The process inherits the terminal instead of going through `runCLI`, which held
+ /// stdout until exit, dropped stderr whenever stdout was non-empty, and made
+ /// `exec -it sh` unusable. The status is returned rather than flattened into an
+ /// error so the CLI can exit with the command's own code, as `docker exec` does.
+ @discardableResult
+ public func exec(
+ _ identifier: String, command: [String], interactive: Bool = false, tty: Bool = false,
+ detach: Bool = false, env: [String] = [], envFiles: [String] = [],
+ user: String? = nil, workdir: String? = nil
+ ) async throws -> Int32 {
let container = try await resolve(identifier)
guard container.state == .running else {
throw MockerError.containerNotRunning(identifier)
}
- var args = ["exec"]
- if interactive { args.append("-i") }
- if tty { args.append("-t") }
- args.append(container.name)
- args += command
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: Self.containerCLI)
+ process.arguments = Self.makeExecArguments(
+ name: container.name, command: command, interactive: interactive, tty: tty,
+ detach: detach, env: env, envFiles: envFiles, user: user, workdir: workdir
+ )
+ process.standardInput = FileHandle.standardInput
+ process.standardOutput = FileHandle.standardOutput
+ process.standardError = FileHandle.standardError
+ try process.run()
- let (output, exitCode) = try await runCLI(args)
- if !output.isEmpty { print(output) }
- if exitCode != 0 {
- throw MockerError.operationFailed("exec failed with exit code \(exitCode)")
+ return await withCheckedContinuation { continuation in
+ process.terminationHandler = { continuation.resume(returning: $0.terminationStatus) }
}
}
diff --git a/Tests/MockerKitTests/ContainerEngineExecArgsTests.swift b/Tests/MockerKitTests/ContainerEngineExecArgsTests.swift
new file mode 100644
index 0000000..01b1e86
--- /dev/null
+++ b/Tests/MockerKitTests/ContainerEngineExecArgsTests.swift
@@ -0,0 +1,35 @@
+import Testing
+@testable import MockerKit
+
+/// `ContainerEngine.makeExecArguments` — the pure argument-vector builder behind
+/// `mocker exec`. Every Docker flag mocker accepts must reach `container exec`,
+/// and all options must precede the container name.
+@Suite("ContainerEngine exec arguments")
+struct ContainerEngineExecArgsTests {
+
+ @Test("env, env-file, user, workdir and detach are forwarded before the name")
+ func flagsForwarded() {
+ let args = ContainerEngine.makeExecArguments(
+ name: "web", command: ["printenv"], interactive: true, tty: true, detach: true,
+ env: ["FOO=bar", "HOME"], envFiles: ["/tmp/a.env"], user: "nobody", workdir: "/tmp"
+ )
+ let nameIndex = args.firstIndex(of: "web")!
+ #expect(args.first == "exec")
+ #expect(args.last == "printenv")
+ for flag in ["-i", "-t", "-d", "-e", "--env-file", "-u", "-w"] {
+ #expect(args.firstIndex(of: flag)! < nameIndex, "\(flag) must precede the container name")
+ }
+ #expect(adjacent(args, "-e", "FOO=bar"))
+ #expect(adjacent(args, "-e", "HOME"))
+ #expect(adjacent(args, "--env-file", "/tmp/a.env"))
+ #expect(adjacent(args, "-u", "nobody"))
+ #expect(adjacent(args, "-w", "/tmp"))
+ }
+
+ private func adjacent(_ args: [String], _ flag: String, _ value: String) -> Bool {
+ for (i, a) in args.enumerated() where a == flag {
+ if i + 1 < args.count, args[i + 1] == value { return true }
+ }
+ return false
+ }
+}
Shipped in 0.9.8 (ref #109), checked with the Homebrew build on container 1.5.0. Thanks @BluPix!