github.com/kubeshop/testkube@v1.17.23/cmd/tcl/testworkflow-toolkit/artifacts/handler.go (about)

     1  // Copyright 2024 Testkube.
     2  //
     3  // Licensed as a Testkube Pro file under the Testkube Community
     4  // License (the "License"); you may not use this file except in compliance with
     5  // the License. You may obtain a copy of the License at
     6  //
     7  //	https://github.com/kubeshop/testkube/blob/main/licenses/TCL.txt
     8  
     9  package artifacts
    10  
    11  import (
    12  	"fmt"
    13  	"io/fs"
    14  	"sync/atomic"
    15  
    16  	"github.com/dustin/go-humanize"
    17  
    18  	"github.com/kubeshop/testkube/pkg/ui"
    19  )
    20  
    21  type handler struct {
    22  	uploader  Uploader
    23  	processor Processor
    24  
    25  	success   atomic.Uint32
    26  	errors    atomic.Uint32
    27  	totalSize atomic.Uint64
    28  }
    29  
    30  type Handler interface {
    31  	Start() error
    32  	Add(path string, file fs.File, stat fs.FileInfo) error
    33  	End() error
    34  }
    35  
    36  func NewHandler(uploader Uploader, processor Processor) Handler {
    37  	return &handler{
    38  		uploader:  uploader,
    39  		processor: processor,
    40  	}
    41  }
    42  
    43  func (h *handler) Start() (err error) {
    44  	err = h.processor.Start()
    45  	if err != nil {
    46  		return err
    47  	}
    48  	return h.uploader.Start()
    49  }
    50  
    51  func (h *handler) Add(path string, file fs.File, stat fs.FileInfo) (err error) {
    52  	size := uint64(stat.Size())
    53  	h.totalSize.Add(size)
    54  
    55  	fmt.Printf(ui.LightGray("%s (%s)\n"), path, humanize.Bytes(uint64(stat.Size())))
    56  
    57  	err = h.processor.Add(h.uploader, path, file, stat)
    58  	if err == nil {
    59  		h.success.Add(1)
    60  	} else {
    61  		h.errors.Add(1)
    62  		fmt.Printf(ui.Red("%s: failed: %s"), path, err.Error())
    63  	}
    64  	return err
    65  }
    66  
    67  func (h *handler) End() (err error) {
    68  	fmt.Printf("\n")
    69  
    70  	err = h.processor.End()
    71  	if err != nil {
    72  		go h.uploader.End()
    73  		return err
    74  	}
    75  	err = h.uploader.End()
    76  	if err != nil {
    77  		return err
    78  	}
    79  
    80  	errs := h.errors.Load()
    81  	success := h.success.Load()
    82  	totalSize := h.totalSize.Load()
    83  	if errs == 0 && success == 0 {
    84  		fmt.Printf("No artifacts found.\n")
    85  	} else {
    86  		fmt.Printf("Found and uploaded %s files (%s).\n", ui.LightCyan(success), ui.LightCyan(humanize.Bytes(totalSize)))
    87  	}
    88  	if errs > 0 {
    89  		return fmt.Errorf("  %d problems while uploading files", errs)
    90  	}
    91  	return nil
    92  }