github.com/hashicorp/packer@v1.14.3/command/flag-kv/flag_json.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package kvflag
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"os"
    10  )
    11  
    12  // FlagJSON is a flag.Value implementation for parsing user variables
    13  // from the command-line using JSON files.
    14  type FlagJSON map[string]string
    15  
    16  func (v *FlagJSON) String() string {
    17  	return ""
    18  }
    19  
    20  func (v *FlagJSON) Set(raw string) error {
    21  	f, err := os.Open(raw)
    22  	if err != nil {
    23  		return err
    24  	}
    25  	defer f.Close()
    26  
    27  	if *v == nil {
    28  		*v = make(map[string]string)
    29  	}
    30  
    31  	if err := json.NewDecoder(f).Decode(v); err != nil {
    32  		return fmt.Errorf(
    33  			"Error reading variables in '%s': %s", raw, err)
    34  	}
    35  
    36  	return nil
    37  }