@@ -18,9 +18,6 @@ package controller
1818
1919import (
2020 "context"
21- "crypto/sha256"
22- "encoding/hex"
23- "encoding/json"
2421 "fmt"
2522 "os"
2623 "path/filepath"
@@ -41,7 +38,6 @@ import (
4138 "k8s.io/apimachinery/pkg/types"
4239 ctrl "sigs.k8s.io/controller-runtime"
4340 "sigs.k8s.io/controller-runtime/pkg/client"
44- "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
4541 "sigs.k8s.io/controller-runtime/pkg/log"
4642 "sigs.k8s.io/yaml"
4743
@@ -168,7 +164,11 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
168164 if err != nil {
169165 return nil , err
170166 }
171- defer os .RemoveAll (tmpDir )
167+ defer func () {
168+ if err := os .RemoveAll (tmpDir ); err != nil {
169+ log .FromContext (ctx ).Error (err , "failed to remove temporary image repository" )
170+ }
171+ }()
172172
173173 cloneOpts := & git.CloneOptions {
174174 URL : repo .Spec .URL ,
@@ -222,77 +222,25 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
222222
223223 paths := repo .Spec .Paths
224224 if len (paths ) == 0 {
225- paths = []string {"images/" }
225+ paths = []string {"images" }
226+ }
227+ files , err := imageRepositoryFiles (tmpDir , paths )
228+ if err != nil {
229+ return nil , err
226230 }
227231
228232 var imported []string
229233 desired := map [string ]struct {}{}
230234
231- for _ , scanPath := range paths {
232- fullPath := filepath .Join (tmpDir , scanPath )
233- _ = filepath .Walk (fullPath , func (p string , info os.FileInfo , err error ) error {
234- if err != nil || info == nil || info .IsDir () {
235- return nil
236- }
237- if ! strings .HasSuffix (p , ".yaml" ) && ! strings .HasSuffix (p , ".yml" ) {
238- return nil
239- }
240- data , err := os .ReadFile (p )
241- if err != nil {
242- return nil
243- }
244- // try to parse as unstructured
245- var u map [string ]interface {}
246- if err := yaml .Unmarshal (data , & u ); err != nil {
247- return nil
248- }
249- kind , _ := u ["kind" ].(string )
250- apiVersion , _ := u ["apiVersion" ].(string )
251- if kind != "Image" || ! strings .Contains (apiVersion , "kubeworkspaces.io" ) {
252- return nil
253- }
254- metaObj , _ := u ["metadata" ].(map [string ]interface {})
255- name , _ := metaObj ["name" ].(string )
256- if name == "" {
257- return nil
258- }
259-
260- // build object
261- obj := & unstructured.Unstructured {Object : u }
262- labels := obj .GetLabels ()
263- if labels == nil {
264- labels = map [string ]string {}
265- }
266- labels [imageRepositoryLabelKey ] = repo .Name
267- labels [imageRepositoryManagedBy ] = imageRepositoryManagedVal
268- obj .SetLabels (labels )
269- ann := obj .GetAnnotations ()
270- if ann == nil {
271- ann = map [string ]string {}
272- }
273- ann [imageRepositorySourceURL ] = repo .Spec .URL
274- ann [imageRepositorySourceRef ] = repo .Spec .Ref
275- ann [imageRepositorySourceSHA ] = commit
276- ann [imageRepositorySourcePath ] = strings .TrimPrefix (p , tmpDir + "/" )
277- obj .SetAnnotations (ann )
278-
279- existing := & unstructured.Unstructured {}
280- existing .SetGroupVersionKind (schema.GroupVersionKind {Group : "kubeworkspaces.io" , Version : "v1alpha1" , Kind : "Image" })
281- err = r .Get (ctx , types.NamespacedName {Name : name }, existing )
282- if apierrors .IsNotFound (err ) {
283- if err := r .Create (ctx , obj ); err != nil {
284- return nil
285- }
286- } else if err == nil {
287- obj .SetResourceVersion (existing .GetResourceVersion ())
288- if err := r .Update (ctx , obj ); err != nil {
289- return nil
290- }
291- }
235+ for _ , p := range files {
236+ name , err := r .syncImageFile (ctx , repo , commit , tmpDir , p )
237+ if err != nil {
238+ return nil , fmt .Errorf ("sync %s: %w" , strings .TrimPrefix (p , tmpDir + "/" ), err )
239+ }
240+ if name != "" {
292241 imported = append (imported , name )
293242 desired [name ] = struct {}{}
294- return nil
295- })
243+ }
296244 }
297245
298246 // GC
@@ -317,12 +265,86 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
317265 }
318266 }
319267
320- res := & syncResult {commit : commit , imported : uniq }
321- _ , _ = json .Marshal (res )
322- _ = sha256 .Sum256 ([]byte (commit ))
323- _ = hex .EncodeToString ([]byte {})
324- _ = controllerutil .AddFinalizer
325- return res , nil
268+ return & syncResult {commit : commit , imported : uniq }, nil
269+ }
270+
271+ // syncImageFile imports one manifest and returns its name, or an empty name for
272+ // documents that are not named Images.
273+ func (r * ImageRepositoryReconciler ) syncImageFile (ctx context.Context , repo * kubeworkspacesiov1alpha1.ImageRepository , commit , root , path string ) (string , error ) {
274+ data , err := os .ReadFile (path )
275+ if err != nil {
276+ return "" , err
277+ }
278+ var u map [string ]interface {}
279+ if err := yaml .Unmarshal (data , & u ); err != nil {
280+ return "" , fmt .Errorf ("parse %s: %w" , path , err )
281+ }
282+ kind , _ := u ["kind" ].(string )
283+ apiVersion , _ := u ["apiVersion" ].(string )
284+ if kind != "Image" || ! strings .Contains (apiVersion , "kubeworkspaces.io" ) {
285+ return "" , nil
286+ }
287+ obj := & unstructured.Unstructured {Object : u }
288+ name := obj .GetName ()
289+ if name == "" {
290+ return "" , nil
291+ }
292+ labels := obj .GetLabels ()
293+ if labels == nil {
294+ labels = map [string ]string {}
295+ }
296+ labels [imageRepositoryLabelKey ] = repo .Name
297+ labels [imageRepositoryManagedBy ] = imageRepositoryManagedVal
298+ obj .SetLabels (labels )
299+ ann := obj .GetAnnotations ()
300+ if ann == nil {
301+ ann = map [string ]string {}
302+ }
303+ ann [imageRepositorySourceURL ] = repo .Spec .URL
304+ ann [imageRepositorySourceRef ] = repo .Spec .Ref
305+ ann [imageRepositorySourceSHA ] = commit
306+ ann [imageRepositorySourcePath ] = strings .TrimPrefix (path , root + "/" )
307+ obj .SetAnnotations (ann )
308+
309+ existing := & unstructured.Unstructured {}
310+ existing .SetGroupVersionKind (schema.GroupVersionKind {Group : "kubeworkspaces.io" , Version : "v1alpha1" , Kind : "Image" })
311+ err = r .Get (ctx , types.NamespacedName {Name : name }, existing )
312+ if apierrors .IsNotFound (err ) {
313+ err = r .Create (ctx , obj )
314+ } else if err == nil {
315+ obj .SetResourceVersion (existing .GetResourceVersion ())
316+ err = r .Update (ctx , obj )
317+ }
318+ if err != nil {
319+ return "" , err
320+ }
321+ return name , nil
322+ }
323+
324+ // imageRepositoryFiles lists only direct YAML children of each configured
325+ // directory. ReadDir accepts paths with or without a trailing slash. Resolve all
326+ // directories before importing so a missing path fails the sync without pruning.
327+ func imageRepositoryFiles (root string , paths []string ) ([]string , error ) {
328+ var files []string
329+ seen := map [string ]bool {}
330+ for _ , scanPath := range paths {
331+ fullPath := filepath .Join (root , strings .TrimSpace (scanPath ))
332+ entries , err := os .ReadDir (fullPath )
333+ if err != nil {
334+ return nil , fmt .Errorf ("read image directory %q: %w" , scanPath , err )
335+ }
336+ for _ , entry := range entries {
337+ if entry .IsDir () || (! strings .HasSuffix (entry .Name (), ".yaml" ) && ! strings .HasSuffix (entry .Name (), ".yml" )) {
338+ continue
339+ }
340+ path := filepath .Join (fullPath , entry .Name ())
341+ if ! seen [path ] {
342+ files = append (files , path )
343+ seen [path ] = true
344+ }
345+ }
346+ }
347+ return files , nil
326348}
327349
328350// SetupWithManager sets up the controller with the Manager.
0 commit comments