Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ integration: init-block
@echo "Removing any existing containers"
@bin/container rm --all
@echo "Starting CLI integration tests"
@$(SWIFT) test -c $(BUILD_CONFIGURATION) --filter TestCLINetwork
@$(SWIFT) test -c $(BUILD_CONFIGURATION) --filter TestCLIRunLifecycle
@$(SWIFT) test -c $(BUILD_CONFIGURATION) --filter TestCLIExecCommand
@$(SWIFT) test -c $(BUILD_CONFIGURATION) --filter TestCLIRunCommand
Expand Down
10 changes: 5 additions & 5 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 6 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ if let path = ProcessInfo.processInfo.environment["CONTAINERIZATION_PATH"] {
scDependency = .package(path: path)
scVersion = "latest"
} else {
scVersion = "0.1.1"
scVersion = "0.2.0"
scDependency = .package(url: "https://github.com/apple/containerization.git", exact: Version(stringLiteral: scVersion))
}

Expand Down Expand Up @@ -295,10 +295,13 @@ let package = Package(
.testTarget(
name: "CLITests",
dependencies: [
.product(name: "ContainerizationOS", package: "containerization"),
.product(name: "AsyncHTTPClient", package: "async-http-client"),
.product(name: "Containerization", package: "containerization"),
"ContainerClient",
.product(name: "ContainerizationExtras", package: "containerization"),
.product(name: "ContainerizationOS", package: "containerization"),
"ContainerBuild",
"ContainerClient",
"ContainerNetworkService",
],
path: "Tests/CLITests"
),
Expand Down
94 changes: 53 additions & 41 deletions Sources/CLI/Application.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,8 @@ struct Application: AsyncParsableCommand {
]
),
CommandGroup(
name: "System",
subcommands: [
BuilderCommand.self,
SystemCommand.self,
]
name: "Other",
subcommands: Self.otherCommands()
),
],
// Hidden command to handle plugins on unrecognized input.
Expand Down Expand Up @@ -112,42 +109,6 @@ struct Application: AsyncParsableCommand {
return PluginLoader(pluginDirectories: pluginDirectories, pluginFactories: pluginFactories, defaultResourcePath: statePath, log: log)
}()

func validate() throws {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NOTE: no changes...just reordered private functions to the end of the compilation unit

// Not really a "validation", but a cheat to run this before
// any of the commands do their business.
let debugEnvVar = ProcessInfo.processInfo.environment["CONTAINER_DEBUG"]
if self.global.debug || debugEnvVar != nil {
log.logLevel = .debug
}
// Ensure we're not running under Rosetta.
if try isTranslated() {
throw ValidationError(
"""
`container` is currently running under Rosetta Translation, which could be
caused by your terminal application. Please ensure this is turned off.
"""
)
}
}

private static func restoreCursorAtExit() {
let signalHandler: @convention(c) (Int32) -> Void = { signal in
let exitCode = ExitCode(signal + 128)
Application.exit(withError: exitCode)
}
// Termination by Ctrl+C.
signal(SIGINT, signalHandler)
// Termination using `kill`.
signal(SIGTERM, signalHandler)
// Normal and explicit exit.
atexit {
if let progressConfig = try? ProgressConfig() {
let progressBar = ProgressBar(config: progressConfig)
progressBar.resetCursor()
}
}
}

public static func main() async throws {
restoreCursorAtExit()

Expand Down Expand Up @@ -261,6 +222,57 @@ struct Application: AsyncParsableCommand {
return -1
}
}

func validate() throws {
// Not really a "validation", but a cheat to run this before
// any of the commands do their business.
let debugEnvVar = ProcessInfo.processInfo.environment["CONTAINER_DEBUG"]
if self.global.debug || debugEnvVar != nil {
log.logLevel = .debug
}
// Ensure we're not running under Rosetta.
if try isTranslated() {
throw ValidationError(
"""
`container` is currently running under Rosetta Translation, which could be
caused by your terminal application. Please ensure this is turned off.
"""
)
}
}

private static func otherCommands() -> [any ParsableCommand.Type] {
guard #available(macOS 26, *) else {
return [
BuilderCommand.self,
SystemCommand.self,
]
}

return [
BuilderCommand.self,
NetworkCommand.self,
SystemCommand.self,
]
}

private static func restoreCursorAtExit() {
let signalHandler: @convention(c) (Int32) -> Void = { signal in
let exitCode = ExitCode(signal + 128)
Application.exit(withError: exitCode)
}
// Termination by Ctrl+C.
signal(SIGINT, signalHandler)
// Termination using `kill`.
signal(SIGTERM, signalHandler)
// Normal and explicit exit.
atexit {
if let progressConfig = try? ProgressConfig() {
let progressBar = ProgressBar(config: progressConfig)
progressBar.resetCursor()
}
}
}
}

extension Application {
Expand Down
2 changes: 1 addition & 1 deletion Sources/CLI/Container/ContainerDelete.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ extension Application {
if containerIDs.count > 0 && all {
throw ContainerizationError(
.invalidArgument,
message: "explicitly supplied container IDs conflicts with the --all flag"
message: "explicitly supplied container ID(s) conflict with the --all flag"
)
}
}
Expand Down
33 changes: 33 additions & 0 deletions Sources/CLI/Network/NetworkCommand.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//

import ArgumentParser

extension Application {
struct NetworkCommand: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "network",
abstract: "Manage container networks",
subcommands: [
NetworkCreate.self,
NetworkDelete.self,
NetworkList.self,
NetworkInspect.self,
],
aliases: ["n"]
)
}
}
42 changes: 42 additions & 0 deletions Sources/CLI/Network/NetworkCreate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//

import ArgumentParser
import ContainerClient
import ContainerNetworkService
import ContainerizationError
import Foundation
import TerminalProgress

extension Application {
struct NetworkCreate: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "create",
abstract: "Create a new network")

@Argument(help: "Network name")
var name: String

@OptionGroup
var global: Flags.Global

func run() async throws {
let config = NetworkConfiguration(id: self.name, mode: .nat)
let state = try await ClientNetwork.create(configuration: config)
print(state.id)
}
}
}
116 changes: 116 additions & 0 deletions Sources/CLI/Network/NetworkDelete.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025 Apple Inc. and the container project authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//

import ArgumentParser
import ContainerClient
import ContainerNetworkService
import ContainerizationError
import Foundation

extension Application {
struct NetworkDelete: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "delete",
abstract: "Delete one or more networks",
aliases: ["rm"])

@Flag(name: .shortAndLong, help: "Remove all networks")
var all = false

@OptionGroup
var global: Flags.Global

@Argument(help: "Network names")
var networkNames: [String] = []

func validate() throws {
if networkNames.count == 0 && !all {
throw ContainerizationError(.invalidArgument, message: "no networks specified and --all not supplied")
}
if networkNames.count > 0 && all {
throw ContainerizationError(
.invalidArgument,
message: "explicitly supplied network name(s) conflict with the --all flag"
)
}
}

mutating func run() async throws {
let uniqueNetworkNames = Set<String>(networkNames)
let networks: [NetworkState]

if all {
networks = try await ClientNetwork.list()
} else {
networks = try await ClientNetwork.list()
.filter { c in
uniqueNetworkNames.contains(c.id)
}

// If one of the networks requested isn't present lets throw. We don't need to do
// this for --all as --all should be perfectly usable with no networks to remove,
// otherwise it'd be quite clunky.
if networks.count != uniqueNetworkNames.count {
let missing = uniqueNetworkNames.filter { id in
!networks.contains { n in
n.id == id
}
}
throw ContainerizationError(
.notFound,
message: "failed to delete one or more networks: \(missing)"
)
}
}

if uniqueNetworkNames.contains(ClientNetwork.defaultNetworkName) {
throw ContainerizationError(
.invalidArgument,
message: "cannot delete the default network"
)
}

var failed = [String]()
try await withThrowingTaskGroup(of: NetworkState?.self) { group in
for network in networks {
group.addTask {
do {
// delete atomically disables the IP allocator, then deletes
// the allocator disable fails if any IPs are still in use
try await ClientNetwork.delete(id: network.id)
print(network.id)
return nil
} catch {
log.error("failed to delete network \(network.id): \(error)")
return network
}
}
}

for try await network in group {
guard let network else {
continue
}
failed.append(network.id)
}
}

if failed.count > 0 {
throw ContainerizationError(.internalError, message: "delete failed for one or more networks: \(failed)")
}
}
}
}
Loading