github.com/Benchkram/bob@v0.0.0-20220321080157-7c8f3876e225/bob/artifact.go (about)

     1  package bob
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"fmt"
     7  	"io/fs"
     8  
     9  	"github.com/Benchkram/bob/bobtask"
    10  	"github.com/Benchkram/bob/pkg/usererror"
    11  	"github.com/Benchkram/errz"
    12  )
    13  
    14  // ArtifactList list artifacts belonging to each tasks.
    15  // Artifacts are matched by project & taskname as well as their input hash stored
    16  // in the artifacts metadata if required.
    17  func (b *B) ArtifactList(ctx context.Context) (description string, err error) {
    18  	defer errz.Recover(&err)
    19  
    20  	bobfile, err := b.Aggregate()
    21  	errz.Fatal(err)
    22  
    23  	items, err := b.Localstore().List(ctx)
    24  	errz.Fatal(err)
    25  
    26  	metadataAll := []*bobtask.ArtifactMetadata{}
    27  	// prepare projectTasknameMap once from artifact store
    28  	for _, item := range items {
    29  		artifact, err := b.Localstore().GetArtifact(ctx, item)
    30  		errz.Fatal(err)
    31  		defer artifact.Close()
    32  
    33  		artifactInfo, err := bobtask.ArtifactInspectFromReader(artifact)
    34  		errz.Fatal(err)
    35  
    36  		m := artifactInfo.Metadata()
    37  		if m == nil {
    38  			continue
    39  		}
    40  		metadataAll = append(metadataAll, m)
    41  	}
    42  
    43  	// List artifacts in relation to tasknames in alphabetical order
    44  	buf := bytes.NewBufferString("")
    45  	sortedKeys := bobfile.BTasks.KeysSortedAlpabethically()
    46  	for _, key := range sortedKeys {
    47  		task := bobfile.BTasks[key]
    48  
    49  		fmt.Fprintln(buf, task.Name())
    50  
    51  		// additionaly check if there is a artifact match by inputHash
    52  		for _, m := range metadataAll {
    53  			var match bool
    54  
    55  			if m.Project == task.Dir() && m.Taskname == task.Name() {
    56  				match = true
    57  			}
    58  
    59  			// check input hash match in case we have no match yet.
    60  			if !match {
    61  				inputHash, err := task.HashIn()
    62  				errz.Fatal(err)
    63  				if m.InputHash == inputHash.String() {
    64  					match = true
    65  				}
    66  			}
    67  
    68  			if match {
    69  				fmt.Fprintln(buf, "  "+m.InputHash)
    70  			}
    71  		}
    72  	}
    73  
    74  	return buf.String(), nil
    75  }
    76  
    77  func (b *B) ArtifactInspect(artifactID string) (ai bobtask.ArtifactInfo, err error) {
    78  
    79  	artifact, err := b.local.GetArtifact(context.TODO(), artifactID)
    80  	if err != nil {
    81  		_, ok := err.(*fs.PathError)
    82  		if ok {
    83  			return ai, usererror.Wrap(bobtask.ErrArtifactDoesNotExist)
    84  		}
    85  		errz.Fatal(err)
    86  	}
    87  	defer artifact.Close()
    88  
    89  	return bobtask.ArtifactInspectFromReader(artifact)
    90  }