-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat: Add container image tree command #2005
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dev-kvt
wants to merge
3
commits into
apple:main
Choose a base branch
from
dev-kvt:feature/container-image-tree
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+201
−0
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,200 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // 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 ArgumentParser | ||
| import ContainerAPIClient | ||
| import ContainerResource | ||
| import Containerization | ||
| import ContainerizationOCI | ||
| import Foundation | ||
|
|
||
| extension Application { | ||
| public struct ImageTree: AsyncLoggableCommand { | ||
| public init() {} | ||
| public static let configuration = CommandConfiguration( | ||
| commandName: "tree", | ||
| abstract: "Show images in a tree view based on parent-child relationships", | ||
| aliases: ["tr"] | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is likely a lesser used command, and it only saves two characters. |
||
| ) | ||
|
|
||
| @Flag(name: .shortAndLong, help: "Show image sizes") | ||
| var size = false | ||
|
|
||
| @OptionGroup | ||
| public var logOptions: Flags.Logging | ||
|
|
||
| public mutating func run() async throws { | ||
| let containerSystemConfig: ContainerSystemConfig = try await Application.loadContainerSystemConfig() | ||
|
|
||
| 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 } | ||
|
|
||
| let resources = try await Self.buildResources(images: images, containerSystemConfig: containerSystemConfig) | ||
|
|
||
| // Build tree | ||
| let rootNodes = buildTree(from: resources) | ||
|
|
||
| // Print tree | ||
| if rootNodes.isEmpty { | ||
| return | ||
| } | ||
|
|
||
| for node in rootNodes { | ||
| // Determine root print style. The root doesn't have the ├── marker | ||
| printRootNode(node) | ||
| } | ||
| } | ||
|
|
||
| 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 | ||
| } | ||
|
|
||
| private class Node { | ||
| let resource: ImageResource | ||
| let allDiffIDs: [[String]] | ||
| let displaySize: String | ||
| var children: [Node] = [] | ||
|
|
||
| init(resource: ImageResource, allDiffIDs: [[String]], displaySize: String) { | ||
| self.resource = resource | ||
| self.allDiffIDs = allDiffIDs | ||
| self.displaySize = displaySize | ||
| } | ||
| } | ||
|
|
||
| private func buildTree(from resources: [ImageResource]) -> [Node] { | ||
| let formatter = ByteCountFormatter() | ||
| var nodes: [Node] = [] | ||
|
|
||
| for resource in resources { | ||
| let allDiffIDs = resource.variants.map { $0.config.rootfs.diffIDs } | ||
| let totalSize = resource.variants.reduce(Int64(0)) { $0 + $1.size } | ||
| let sizeStr = formatter.string(fromByteCount: totalSize) | ||
| nodes.append(Node(resource: resource, allDiffIDs: allDiffIDs, displaySize: sizeStr)) | ||
| } | ||
|
|
||
| // Sort nodes by the minimum diffID count across all variants (parents have fewer layers) | ||
| nodes.sort { lhs, rhs in | ||
| let lhsMin = lhs.allDiffIDs.map(\.count).min() ?? 0 | ||
| let rhsMin = rhs.allDiffIDs.map(\.count).min() ?? 0 | ||
| return lhsMin < rhsMin | ||
| } | ||
|
|
||
| var roots: [Node] = [] | ||
|
|
||
| for node in nodes { | ||
| var foundParent = false | ||
| // Build a flat list of all placed nodes, sorted by most layers first (deepest match wins) | ||
| let candidates = roots.flatMap { getAllNodes(in: $0) } | ||
| .sorted { lhs, rhs in | ||
| let lhsMax = lhs.allDiffIDs.map(\.count).max() ?? 0 | ||
| let rhsMax = rhs.allDiffIDs.map(\.count).max() ?? 0 | ||
| return lhsMax > rhsMax | ||
| } | ||
|
|
||
| for potentialParent in candidates { | ||
| if isPrefixOfAny(potentialParent.allDiffIDs, of: node.allDiffIDs) { | ||
| potentialParent.children.append(node) | ||
| foundParent = true | ||
| break | ||
| } | ||
| } | ||
|
|
||
| if !foundParent { | ||
| roots.append(node) | ||
| } | ||
| } | ||
|
|
||
| // Sort roots and children alphabetically | ||
| roots.sort { $0.resource.displayReference < $1.resource.displayReference } | ||
| for root in roots { | ||
| sortChildren(of: root) | ||
| } | ||
|
|
||
| return roots | ||
| } | ||
|
|
||
| private func getAllNodes(in root: Node) -> [Node] { | ||
| var result = [root] | ||
| for child in root.children { | ||
| result.append(contentsOf: getAllNodes(in: child)) | ||
| } | ||
| return result | ||
| } | ||
|
|
||
| private func sortChildren(of node: Node) { | ||
| node.children.sort { $0.resource.displayReference < $1.resource.displayReference } | ||
| for child in node.children { | ||
| sortChildren(of: child) | ||
| } | ||
| } | ||
|
|
||
| private func isPrefixOfAny(_ parentDiffIDsList: [[String]], of childDiffIDsList: [[String]]) -> Bool { | ||
| for parentDiffIDs in parentDiffIDsList { | ||
| for childDiffIDs in childDiffIDsList { | ||
| if isPrefix(parentDiffIDs, of: childDiffIDs) { | ||
| return true | ||
| } | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| private func isPrefix(_ prefix: [String], of full: [String]) -> Bool { | ||
| guard prefix.count < full.count && prefix.count > 0 else { return false } | ||
| for i in 0..<prefix.count { | ||
| if prefix[i] != full[i] { | ||
| return false | ||
| } | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| private func printRootNode(_ node: Node) { | ||
| var line = node.resource.displayReference | ||
| if size { | ||
| line += " (\(node.displaySize))" | ||
| } | ||
| print(line) | ||
|
|
||
| for (index, child) in node.children.enumerated() { | ||
| printNode(child, prefix: "", isLast: index == node.children.count - 1) | ||
| } | ||
| } | ||
|
|
||
| private func printNode(_ node: Node, prefix: String, isLast: Bool) { | ||
| let marker = isLast ? "└── " : "├── " | ||
| var line = prefix + marker + node.resource.displayReference | ||
| if size { | ||
| line += " (\(node.displaySize))" | ||
| } | ||
| print(line) | ||
|
|
||
| let childPrefix = prefix + (isLast ? " " : "│ ") | ||
| for (index, child) in node.children.enumerated() { | ||
| printNode(child, prefix: childPrefix, isLast: index == node.children.count - 1) | ||
| } | ||
| } | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ContainerizationError-ContainerPersistence-ContainerPluginare all unused importsThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Indeed, these are redundancies that I inadvertently overlooked. Furthermore, I encountered an additional bottleneck during performance optimization and testing.
Should you find merit in this feature proposal, please consider actively contributing to its development.
As an active container user I felt this is a needed requirement for the project
@gnavadev
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this is a nice QoL improvement. However, I wonder if something like this would be better as a plugin or in a separate repository, maybe something like apple-container-tools? What do you think @jglogan ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
First of all, thank you both for the valuable discussion.@gnavadev and @jglogan
@gnavadev, thank you for the insightful suggestions and direction. I agree that this should be developed as a separate utility. When working with more complex workflows, it becomes difficult to keep track of active containers, and having a dedicated utility would make that much more manageable. It also aligns well with Apple's approach of providing focused, user-friendly utilities.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you @gnavadev for the thorough review and great suggestions! I’ve updated the branch with the following fixes:
Unused Imports: Removed ContainerizationError, ContainerPersistence, and ContainerPlugin.
Size Aggregation: Switched to using reduce to sum the size across all variants.
Tree-Building Logic & Performance:
Fixed the sorting mismatch by using min()/max() across all variants' diffID counts to align with the isPrefixOfAny matching logic.
Hoisted the candidate list generation out of the inner loop to avoid redundant flatMap/sorting operations on every iteration.