github.com/kubeshop/testkube@v1.17.23/cmd/tcl/testworkflow-toolkit/artifacts/tar_processor.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"
    15  
    16  	"github.com/kubeshop/testkube/pkg/ui"
    17  )
    18  
    19  func NewTarProcessor(name string) Processor {
    20  	return &tarProcessor{
    21  		name: name,
    22  	}
    23  }
    24  
    25  type tarProcessor struct {
    26  	name  string
    27  	mu    *sync.Mutex
    28  	errCh chan error
    29  	ts    *tarStream
    30  }
    31  
    32  func (d *tarProcessor) Start() (err error) {
    33  	d.errCh = make(chan error)
    34  	d.mu = &sync.Mutex{}
    35  
    36  	return err
    37  }
    38  
    39  func (d *tarProcessor) init(uploader Uploader) {
    40  	if d.ts != nil {
    41  		return
    42  	}
    43  	d.ts = NewTarStream()
    44  
    45  	// Start uploading the file
    46  	go func() {
    47  		err := uploader.Add(d.name, d.ts, -1)
    48  		if err != nil {
    49  			_ = d.ts.Close()
    50  		}
    51  		d.errCh <- err
    52  	}()
    53  }
    54  
    55  func (d *tarProcessor) upload(path string, file fs.File, stat fs.FileInfo) error {
    56  	defer file.Close()
    57  	return d.ts.Add(path, file, stat)
    58  }
    59  
    60  func (d *tarProcessor) Add(uploader Uploader, path string, file fs.File, stat fs.FileInfo) error {
    61  	d.mu.Lock()
    62  	d.init(uploader)
    63  	defer d.mu.Unlock()
    64  	return d.upload(path, file, stat)
    65  }
    66  
    67  func (d *tarProcessor) End() (err error) {
    68  	if d.ts != nil {
    69  		<-d.ts.Done()
    70  	}
    71  	err = d.ts.Close()
    72  	if err != nil {
    73  		return fmt.Errorf("problem closing writer: %w", err)
    74  	}
    75  
    76  	fmt.Printf("Archived everything in %s archive.\n", ui.LightCyan(d.name))
    77  	return <-d.errCh
    78  }