@@ -2,6 +2,7 @@ import Foundation
22import ArgumentParser
33import FragmentZip
44import BuddyFoundation
5+ import VirtualCore
56
67extension CatalogCommand {
78 struct ImageCommand : AsyncParsableCommand {
@@ -102,9 +103,11 @@ extension CatalogCommand {
102103 downloadSize: UInt64 ( contentLength)
103104 )
104105
105- let index = catalog. restoreImages. firstIndex ( where: { $0. id == image. id } )
106+ let index = catalog. index ( forInserting: image)
107+ let isUpdate = catalog. restoreImages [ index] . id == image. id
106108
107- if let index {
109+ /// Replacing an existing image requires a flag.
110+ if isUpdate {
108111 guard force else {
109112 fputs ( " \n ❌ Build \( image. id) already exists in the catalog. Use --force flag to update it. \n \n " , stderr)
110113 Darwin . exit ( 1 )
@@ -113,9 +116,9 @@ extension CatalogCommand {
113116 catalog. restoreImages. remove ( at: index)
114117 }
115118
116- catalog. restoreImages. insert ( image, at: index ?? 0 )
119+ catalog. restoreImages. insert ( image, at: index)
117120
118- let successMessage = index == nil ? " Added image to catalog" : " Updated image in catalog"
121+ let successMessage = isUpdate ? " Updated image in catalog" : " Added image to catalog"
119122 fputs ( " ✅ \( successMessage) : \n \n " , stderr)
120123
121124 fputs ( " \( image) \n \n " , stderr)
@@ -127,3 +130,15 @@ extension CatalogCommand {
127130 }
128131 }
129132}
133+
134+ private extension SoftwareCatalog {
135+ func index( forInserting image: RestoreImage ) -> Int {
136+ if let existingIndex = restoreImages. firstIndex ( where: { $0. id == image. id } ) {
137+ existingIndex /// Replace image at its current index (client must delete existing one before replacing)
138+ } else if let placementIndex = restoreImages. firstIndex ( where: { $0. group == image. group && $0. version <= image. version } ) {
139+ placementIndex /// Place image before the first image of the same release group and OS version
140+ } else {
141+ 0 /// Place image in first slot
142+ }
143+ }
144+ }
0 commit comments