github.com/winebarrel/terraform-provider-lambdazip@v0.6.1-0.20240313233639-361839f8c5c5/lambdazip/data_source_files_sha256.go (about)

     1  package lambdazip
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/bmatcuk/doublestar/v4"
     7  	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
     8  	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/id"
     9  	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
    10  	"github.com/winebarrel/terraform-provider-lambdazip/internal/glob"
    11  	"github.com/winebarrel/terraform-provider-lambdazip/internal/hash"
    12  )
    13  
    14  func dataSourceFilesSha256() *schema.Resource {
    15  	return &schema.Resource{
    16  		ReadContext: readExpr,
    17  		Schema: map[string]*schema.Schema{
    18  			"files": {
    19  				Type:     schema.TypeList,
    20  				Required: true,
    21  				Elem: &schema.Schema{
    22  					Type: schema.TypeString,
    23  				},
    24  			},
    25  			"excludes": {
    26  				Type: schema.TypeList,
    27  				Elem: &schema.Schema{
    28  					Type: schema.TypeString,
    29  				},
    30  				Optional: true,
    31  			},
    32  			"map": {
    33  				Type:     schema.TypeMap,
    34  				Computed: true,
    35  				Elem: &schema.Schema{
    36  					Type: schema.TypeString,
    37  				},
    38  			},
    39  			"allow_not_exist": {
    40  				Type:     schema.TypeBool,
    41  				Optional: true,
    42  				Default:  false,
    43  			},
    44  		},
    45  	}
    46  }
    47  
    48  func readExpr(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
    49  	files := []string{}
    50  
    51  	if patterns, ok := d.GetOk("files"); ok {
    52  		for _, pat := range patterns.([]any) {
    53  			files = append(files, pat.(string))
    54  		}
    55  	}
    56  
    57  	if len(files) == 0 {
    58  		return diag.Errorf(`The attribute "files" is required, but the list was empty.`)
    59  	}
    60  
    61  	excludes := []string{}
    62  
    63  	if patterns, ok := d.GetOk("excludes"); ok {
    64  		for _, pat := range patterns.([]any) {
    65  			excludes = append(excludes, pat.(string))
    66  		}
    67  	}
    68  
    69  	globOpts := []doublestar.GlobOption{}
    70  
    71  	if !d.Get("allow_not_exist").(bool) {
    72  		globOpts = append(globOpts, doublestar.WithFailOnPatternNotExist())
    73  	}
    74  
    75  	files, err := glob.Glob(files, excludes, globOpts...)
    76  
    77  	if err != nil {
    78  		return diag.FromErr(err)
    79  	}
    80  
    81  	m, err := hash.Sha256Map(files)
    82  
    83  	if err != nil {
    84  		return diag.FromErr(err)
    85  	}
    86  
    87  	d.Set("map", m) //nolint:errcheck
    88  	d.SetId(id.UniqueId())
    89  
    90  	return nil
    91  }