chore: import upstream snapshot with attribution
container project - merge build / Invoke build (push) Successful in 1s

This commit is contained in:
wehub-resource-sync
2026-07-13 12:06:18 +08:00
commit e84fb4a79e
474 changed files with 68321 additions and 0 deletions
@@ -0,0 +1,44 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
extension Application {
public struct ImageCommand: AsyncLoggableCommand {
public init() {}
public static let configuration = CommandConfiguration(
commandName: "image",
abstract: "Manage images",
subcommands: [
ImageDelete.self,
ImageInspect.self,
ImageList.self,
ImageLoad.self,
ImagePrune.self,
ImagePull.self,
ImagePush.self,
ImageSave.self,
ImageTag.self,
],
aliases: ["i"]
)
@OptionGroup
public var logOptions: Flags.Logging
}
}
@@ -0,0 +1,116 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerPersistence
import ContainerPlugin
import Containerization
import ContainerizationError
import Foundation
import Logging
extension Application {
public struct RemoveImageOptions: ParsableArguments {
public init() {}
@Flag(name: .shortAndLong, help: "Delete all images")
var all: Bool = false
@Flag(name: .shortAndLong, help: "Ignore errors for images that are not found")
var force: Bool = false
@Argument
var images: [String] = []
}
struct DeleteImageImplementation {
static func validate(options: RemoveImageOptions) throws {
if options.images.count == 0 && !options.all {
throw ContainerizationError(.invalidArgument, message: "no images specified and --all not supplied")
}
if options.images.count > 0 && options.all {
throw ContainerizationError(.invalidArgument, message: "explicitly supplied images conflict with the --all flag")
}
}
static func removeImage(options: RemoveImageOptions, containerSystemConfig: ContainerSystemConfig, log: Logger) async throws {
let (found, notFound) = try await {
if options.all {
let found = try await ClientImage.list()
let notFound: [String] = []
return (found, notFound)
}
return try await ClientImage.get(names: options.images, containerSystemConfig: containerSystemConfig)
}()
var failures: [String] = options.force ? [] : notFound
var didDeleteAnyImage = false
for image in found {
guard
!Utility.isInfraImage(
name: image.reference,
builderImage: containerSystemConfig.build.image,
initImage: containerSystemConfig.vminit.image
)
else {
continue
}
do {
try await ClientImage.delete(reference: image.reference, garbageCollect: false)
print(image.reference)
didDeleteAnyImage = true
} catch {
log.error("failed to delete \(image.reference): \(error)")
failures.append(image.reference)
}
}
let (_, size) = try await ClientImage.cleanUpOrphanedBlobs()
let formatter = ByteCountFormatter()
let freed = formatter.string(fromByteCount: Int64(size))
if didDeleteAnyImage {
log.info("Reclaimed \(freed) in disk space")
}
if failures.count > 0 {
throw ContainerizationError(.internalError, message: "failed to delete one or more images: \(failures)")
}
}
}
public struct ImageDelete: AsyncLoggableCommand {
@OptionGroup
var options: RemoveImageOptions
@OptionGroup
public var logOptions: Flags.Logging
public static let configuration = CommandConfiguration(
commandName: "delete",
abstract: "Delete one or more images",
aliases: ["rm"])
public init() {}
public func validate() throws {
try DeleteImageImplementation.validate(options: options)
}
public mutating func run() async throws {
let containerSystemConfig: ContainerSystemConfig = try await Application.loadContainerSystemConfig()
try await DeleteImageImplementation.removeImage(options: options, containerSystemConfig: containerSystemConfig, log: log)
}
}
}
@@ -0,0 +1,70 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerPersistence
import ContainerResource
import ContainerizationError
import Foundation
extension Application {
public struct ImageInspect: AsyncLoggableCommand {
public static let configuration = CommandConfiguration(
commandName: "inspect",
abstract: "Display information about one or more images")
@OptionGroup
public var logOptions: Flags.Logging
@Argument(help: "Images to inspect")
var images: [String]
public init() {}
public func run() async throws {
let containerSystemConfig: ContainerSystemConfig = try await Application.loadContainerSystemConfig()
let uniqueNames = Set(images)
let result = try await ClientImage.get(
names: Array(uniqueNames), containerSystemConfig: containerSystemConfig
)
if !result.error.isEmpty {
let missing = result.error.sorted()
throw ContainerizationError(
.notFound,
message: "image not found: \(missing.joined(separator: ", "))"
)
}
var printable: [ImageResource] = []
for image in result.images {
guard
!Utility.isInfraImage(
name: image.reference,
builderImage: containerSystemConfig.build.image,
initImage: containerSystemConfig.vminit.image
)
else { continue }
printable.append(
try await image.toImageResource(containerSystemConfig: containerSystemConfig)
)
}
try Output.emit(Output.renderJSON(printable, options: .pretty))
}
}
}
@@ -0,0 +1,145 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerPersistence
import ContainerPlugin
import ContainerResource
import Containerization
import ContainerizationError
import ContainerizationOCI
import Foundation
extension Application {
public struct ImageList: AsyncLoggableCommand {
public init() {}
public static let configuration = CommandConfiguration(
commandName: "list",
abstract: "List images",
aliases: ["ls"])
@Option(name: .long, help: "Format of the output")
var format: ListFormat = .table
@Flag(name: .shortAndLong, help: "Only output the image name")
var quiet = false
@Flag(name: .shortAndLong, help: "Verbose output")
var verbose = false
@OptionGroup
public var logOptions: Flags.Logging
public mutating func run() async throws {
let containerSystemConfig: ContainerSystemConfig = try await Application.loadContainerSystemConfig()
try Self.validate(quiet: quiet, verbose: verbose)
var images = try await ClientImage.list().filter { img in
!Utility.isInfraImage(name: img.reference, builderImage: containerSystemConfig.build.image, initImage: containerSystemConfig.vminit.image)
}
images.sort { $0.reference < $1.reference }
// Quiet mode prints references directly and skips the more expensive
// per-image manifest resolution.
if quiet && format == .table {
for image in images {
let processedReferenceString = try ClientImage.denormalizeReference(image.reference, containerSystemConfig: containerSystemConfig)
print(processedReferenceString)
}
return
}
let resources = try await Self.buildResources(images: images, containerSystemConfig: containerSystemConfig)
try Output.render(payload: resources, format: format) {
if verbose {
return Output.renderTable(resources.flatMap { VerboseImageRow.rows(for: $0) })
}
return Output.renderTable(resources)
}
}
private static func validate(quiet: Bool, verbose: Bool) throws {
if quiet && verbose {
throw ContainerizationError(.invalidArgument, message: "cannot use flag --quiet and --verbose together")
}
}
/// Builds the resource for each image, denormalizing the reference so the
/// display name omits the default registry.
private static func buildResources(images: [ClientImage], containerSystemConfig: ContainerSystemConfig) async throws -> [ImageResource] {
var resources: [ImageResource] = []
for image in images {
resources.append(
try await image.toImageResource(containerSystemConfig: containerSystemConfig)
)
}
return resources
}
}
}
/// A single row of the verbose image listing one per platform variant.
private struct VerboseImageRow: ListDisplayable {
let name: String
let tag: String
let indexDigest: String
let os: String
let arch: String
let variant: String
let fullSize: String
let created: String
let manifestDigest: String
static var tableHeader: [String] {
["NAME", "TAG", "INDEX DIGEST", "OS", "ARCH", "VARIANT", "FULL SIZE", "CREATED", "MANIFEST DIGEST"]
}
var tableRow: [String] {
[name, tag, indexDigest, os, arch, variant, fullSize, created, manifestDigest]
}
var quietValue: String {
name
}
/// Flattens an ImageResource into one verbose image row entry per platform variant.
static func rows(for resource: ImageResource) -> [VerboseImageRow] {
let formatter = ByteCountFormatter()
let reference = try? ContainerizationOCI.Reference.parse(resource.displayReference)
let name = reference?.name ?? resource.displayReference
let tag = reference?.tag ?? "<none>"
let indexDigest = Utility.trimDigest(digest: resource.configuration.descriptor.digest)
return
resource.variants
// Skip attestation manifests, which use the `unknown/unknown` platform.
.filter { !($0.platform.os == "unknown" && $0.platform.architecture == "unknown") }
.map { variant in
VerboseImageRow(
name: name,
tag: tag,
indexDigest: indexDigest,
os: variant.platform.os,
arch: variant.platform.architecture,
variant: variant.platform.variant ?? "",
fullSize: formatter.string(fromByteCount: variant.size),
created: variant.config.created ?? "",
manifestDigest: Utility.trimDigest(digest: variant.digest)
)
}
}
}
@@ -0,0 +1,113 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import Containerization
import ContainerizationError
import ContainerizationOS
import Foundation
import SystemPackage
import TerminalProgress
extension Application {
public struct ImageLoad: AsyncLoggableCommand {
public init() {}
public static let configuration = CommandConfiguration(
commandName: "load",
abstract: "Load images from an OCI compatible tar archive"
)
@Option(
name: .shortAndLong, help: "Path to the image tar archive", completion: .file(),
transform: { str in
FilePathOps.absolutePath(FilePath(str))
})
var input: FilePath?
@Flag(name: .shortAndLong, help: "Load images even if the archive contains invalid files")
public var force = false
@OptionGroup
public var logOptions: Flags.Logging
public func run() async throws {
let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).tar")
defer {
try? FileManager.default.removeItem(at: tempFile)
}
// Read from stdin; otherwise read from the input file
let resolvedPath: FilePath
if let input {
guard FileManager.default.fileExists(atPath: input.string) else {
log.error("file does not exist", metadata: ["path": "\(input)"])
Application.exit(withError: ArgumentParser.ExitCode(1))
}
resolvedPath = input
} else {
guard FileManager.default.createFile(atPath: tempFile.path(), contents: nil) else {
throw ContainerizationError(.internalError, message: "unable to create temporary file")
}
guard let fileHandle = try? FileHandle(forWritingTo: tempFile) else {
throw ContainerizationError(.internalError, message: "unable to open temporary file for writing")
}
let bufferSize = 4096
while true {
let chunk = FileHandle.standardInput.readData(ofLength: bufferSize)
if chunk.isEmpty { break }
fileHandle.write(chunk)
}
try fileHandle.close()
resolvedPath = FilePath(tempFile.path())
}
let progressConfig = try ProgressConfig(
showTasks: true,
showItems: true,
totalTasks: 2
)
let progress = ProgressBar(config: progressConfig)
defer {
progress.finish()
}
progress.start()
progress.set(description: "Loading tar archive")
let result = try await ClientImage.load(
from: resolvedPath.string,
force: force)
if !result.rejectedMembers.isEmpty {
log.warning("archive contains invalid members", metadata: ["paths": "\(result.rejectedMembers)"])
}
let taskManager = ProgressTaskCoordinator()
let unpackTask = await taskManager.startTask()
progress.set(description: "Unpacking image")
progress.set(itemsName: "entries")
for image in result.images {
try await image.unpack(platform: nil, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))
}
await taskManager.finish()
progress.finish()
for image in result.images {
print(image.reference)
}
}
}
}
@@ -0,0 +1,97 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerizationOCI
import Foundation
extension Application {
public struct ImagePrune: AsyncLoggableCommand {
public init() {}
public static let configuration = CommandConfiguration(
commandName: "prune",
abstract: "Remove unused or all images")
@OptionGroup
public var logOptions: Flags.Logging
@Flag(name: .shortAndLong, help: "Remove all unused images, not just dangling ones")
var all: Bool = false
public func run() async throws {
let allImages = try await ClientImage.list()
let imagesToPrune: [ClientImage]
if all {
// Find all images not used by any container
let client = ContainerClient()
let containers = try await client.list()
var imagesInUse = Set<String>()
for container in containers {
imagesInUse.insert(container.configuration.image.reference)
}
imagesToPrune = allImages.filter { image in
!imagesInUse.contains(image.reference)
}
} else {
// Find dangling images (images with no tag)
imagesToPrune = allImages.filter { image in
!hasTag(image.reference)
}
}
var prunedImages = [String]()
for image in imagesToPrune {
do {
try await ClientImage.delete(reference: image.reference, garbageCollect: false)
prunedImages.append(image.reference)
} catch {
log.error(
"failed to prune image",
metadata: [
"ref": "\(image.reference)",
"error": "\(error)",
])
}
}
let (deletedDigests, size) = try await ClientImage.cleanUpOrphanedBlobs()
for image in imagesToPrune {
print("untagged \(image.reference)")
}
for digest in deletedDigests {
print("deleted \(digest)")
}
let formatter = ByteCountFormatter()
formatter.countStyle = .file
let freed = formatter.string(fromByteCount: Int64(size))
log.info("Reclaimed \(freed) in disk space")
}
private func hasTag(_ reference: String) -> Bool {
do {
let ref = try ContainerizationOCI.Reference.parse(reference)
return ref.tag != nil && !ref.tag!.isEmpty
} catch {
return false
}
}
}
}
@@ -0,0 +1,110 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerPersistence
import ContainerPlugin
import Containerization
import ContainerizationOCI
import TerminalProgress
extension Application {
public struct ImagePull: AsyncLoggableCommand {
public static let configuration = CommandConfiguration(
commandName: "pull",
abstract: "Pull an image"
)
@OptionGroup
var registry: Flags.Registry
@OptionGroup
var progressFlags: Flags.Progress
@OptionGroup
var imageFetchFlags: Flags.ImageFetch
@Option(
name: .shortAndLong,
help: "Limit the pull to the specified architecture"
)
var arch: String?
@Option(
help: "Limit the pull to the specified OS"
)
var os: String?
@Option(
help: "Limit the pull to the specified platform (format: os/arch[/variant], takes precedence over --os and --arch) [environment: CONTAINER_DEFAULT_PLATFORM]"
)
var platform: String?
@OptionGroup
public var logOptions: Flags.Logging
@Argument var reference: String
public init() {}
public init(platform: String? = nil, scheme: String = "auto", reference: String) {
self.logOptions = Flags.Logging()
self.registry = Flags.Registry(scheme: scheme)
self.platform = platform
self.reference = reference
}
public func run() async throws {
let containerSystemConfig: ContainerSystemConfig = try await Application.loadContainerSystemConfig()
let p = try DefaultPlatform.resolve(platform: platform, os: os, arch: arch, log: log)
let scheme = try RequestScheme(registry.scheme)
let processedReference = try ClientImage.normalizeReference(reference, containerSystemConfig: containerSystemConfig)
let progressConfig = try self.progressFlags.makeConfig(
showTasks: true,
showItems: true,
ignoreSmallSize: true,
totalTasks: 2
)
let progress = ProgressBar(config: progressConfig)
defer {
progress.finish()
}
progress.start()
progress.set(description: "Fetching image")
progress.set(itemsName: "blobs")
let taskManager = ProgressTaskCoordinator()
let fetchTask = await taskManager.startTask()
let image = try await ClientImage.pull(
reference: processedReference, platform: p, scheme: scheme, containerSystemConfig: containerSystemConfig,
progressUpdate: ProgressTaskCoordinator.handler(for: fetchTask, from: progress.handler),
maxConcurrentDownloads: self.imageFetchFlags.maxConcurrentDownloads
)
progress.set(description: "Unpacking image")
progress.set(itemsName: "entries")
let unpackTask = await taskManager.startTask()
try await image.unpack(platform: p, progressUpdate: ProgressTaskCoordinator.handler(for: unpackTask, from: progress.handler))
await taskManager.finish()
progress.finish()
}
}
}
@@ -0,0 +1,84 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerPersistence
import ContainerPlugin
import Containerization
import ContainerizationOCI
import TerminalProgress
extension Application {
public struct ImagePush: AsyncLoggableCommand {
public static let configuration = CommandConfiguration(
commandName: "push",
abstract: "Push an image"
)
@OptionGroup
var registry: Flags.Registry
@OptionGroup
var progressFlags: Flags.Progress
@Option(
name: .shortAndLong,
help: "Limit the push to the specified architecture"
)
var arch: String?
@Option(
help: "Limit the push to the specified OS"
)
var os: String?
@Option(help: "Limit the push to the specified platform (format: os/arch[/variant], takes precedence over --os and --arch) [environment: CONTAINER_DEFAULT_PLATFORM]")
var platform: String?
@OptionGroup
public var logOptions: Flags.Logging
@Argument var reference: String
public init() {}
public func run() async throws {
let containerSystemConfig: ContainerSystemConfig = try await Application.loadContainerSystemConfig()
let p = try DefaultPlatform.resolve(platform: platform, os: os, arch: arch, log: log)
let scheme = try RequestScheme(registry.scheme)
let image = try await ClientImage.get(reference: reference, containerSystemConfig: containerSystemConfig)
let progressConfig = try self.progressFlags.makeConfig(
description: "Pushing image \(image.reference)",
itemsName: "blobs",
showItems: true,
showSpeed: false,
ignoreSmallSize: true
)
let progress = ProgressBar(config: progressConfig)
defer {
progress.finish()
}
progress.start()
_ = try await image.push(platform: p, scheme: scheme, containerSystemConfig: containerSystemConfig, progressUpdate: progress.handler)
progress.finish()
print(image.reference)
}
}
}
@@ -0,0 +1,39 @@
//===----------------------------------------------------------------------===//
// Copyright © 2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerResource
import ContainerizationOCI
extension ImageResource: ListDisplayable {
public static var tableHeader: [String] {
["NAME", "TAG", "DIGEST"]
}
public var tableRow: [String] {
// `displayReference` is already denormalized by the caller.
let reference = try? ContainerizationOCI.Reference.parse(displayReference)
return [
reference?.name ?? displayReference,
reference?.tag ?? "<none>",
Utility.trimDigest(digest: configuration.descriptor.digest),
]
}
public var quietValue: String {
name
}
}
@@ -0,0 +1,155 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerPersistence
import ContainerPlugin
import ContainerResource
import Containerization
import ContainerizationError
import ContainerizationOCI
import ContainerizationOS
import Foundation
import SystemPackage
import TerminalProgress
extension Application {
public struct ImageSave: AsyncLoggableCommand {
public init() {}
public static let configuration = CommandConfiguration(
commandName: "save",
abstract: "Save one or more images as an OCI compatible tar archive"
)
@Option(
name: .shortAndLong,
help: "Architecture for the saved image"
)
var arch: String?
@Option(
help: "OS for the saved image"
)
var os: String?
@Option(
name: .shortAndLong, help: "Pathname for the saved image", completion: .file(),
transform: { str in
FilePathOps.absolutePath(FilePath(str))
})
var output: FilePath?
@Option(
help: "Platform for the saved image (format: os/arch[/variant], takes precedence over --os and --arch) [environment: CONTAINER_DEFAULT_PLATFORM]"
)
var platform: String?
@OptionGroup
public var logOptions: Flags.Logging
@Argument var references: [String]
public func run() async throws {
let containerSystemConfig: ContainerSystemConfig = try await Application.loadContainerSystemConfig()
let p = try DefaultPlatform.resolve(platform: platform, os: os, arch: arch, log: log)
let progressConfig = try ProgressConfig(
description: "Saving image(s)"
)
let progress = ProgressBar(config: progressConfig)
defer {
progress.finish()
}
progress.start()
var images: [ImageDescription] = []
for reference in references {
do {
images.append(try await ClientImage.get(reference: reference, containerSystemConfig: containerSystemConfig).description)
} catch {
log.error("failed to get image for reference \(reference): \(error)")
}
}
guard images.count == references.count else {
throw ContainerizationError(.invalidArgument, message: "failed to save image(s)")
}
if let p {
for (reference, description) in zip(references, images) {
let image = ClientImage(description: description)
do {
_ = try await image.manifest(for: p)
} catch {
var available: [String] = []
if let index = try? await image.index() {
available = index.manifests
.compactMap { $0.platform?.description }
.filter { $0 != "unknown/unknown" }
}
let availableStr = available.isEmpty ? "none" : available.joined(separator: ", ")
throw ContainerizationError(
.invalidArgument,
message: "image \(reference) has no content for platform \(p.description); available platforms: \(availableStr)"
)
}
}
}
// Write to stdout; otherwise write to the output file
if let output {
try await ClientImage.save(references: references, out: output.string, platform: p, containerSystemConfig: containerSystemConfig)
} else {
let tempFile = FileManager.default.temporaryDirectory.appendingPathComponent("\(UUID().uuidString).tar")
defer {
try? FileManager.default.removeItem(at: tempFile)
}
guard FileManager.default.createFile(atPath: tempFile.path(), contents: nil) else {
throw ContainerizationError(.internalError, message: "unable to create temporary file")
}
try await ClientImage.save(references: references, out: tempFile.path(), platform: p, containerSystemConfig: containerSystemConfig)
guard let fileHandle = try? FileHandle(forReadingFrom: tempFile) else {
throw ContainerizationError(.internalError, message: "unable to open temporary file for reading")
}
let bufferSize = 4096
while true {
let chunk = fileHandle.readData(ofLength: bufferSize)
if chunk.isEmpty { break }
FileHandle.standardOutput.write(chunk)
}
try fileHandle.close()
}
progress.finish()
for reference in references {
if output == nil {
// stdout is carrying the OCI archive in this branch, so the
// saved-reference list goes to stderr via the logger. Printing
// it to stdout appends non-archive bytes after the tar EOF and
// corrupts the stream for redirection and pipelines (#1801).
log.info("\(reference)")
} else {
print(reference)
}
}
}
}
}
@@ -0,0 +1,46 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// 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 ContainerAPIClient
import ContainerPersistence
import ContainerPlugin
extension Application {
public struct ImageTag: AsyncLoggableCommand {
public init() {}
public static let configuration = CommandConfiguration(
commandName: "tag",
abstract: "Create a new reference for an existing image")
@Argument(help: "The existing image reference (format: image-name[:tag])")
var source: String
@Argument(help: "The new image reference")
var target: String
@OptionGroup
public var logOptions: Flags.Logging
public func run() async throws {
let containerSystemConfig: ContainerSystemConfig = try await Application.loadContainerSystemConfig()
let existing = try await ClientImage.get(reference: source, containerSystemConfig: containerSystemConfig)
let targetReference = try ClientImage.normalizeReference(target, containerSystemConfig: containerSystemConfig)
try await existing.tag(new: targetReference)
print(target)
}
}
}