github.com/konsorten/ktn-build-info@v1.0.11/ver/update_json.go (about)

     1  package ver
     2  
     3  import (
     4  	"bytes"
     5  	jsonImpl "encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  
     9  	"github.com/Jeffail/gabs"
    10  	log "github.com/sirupsen/logrus"
    11  )
    12  
    13  type UpdateActions map[string]string
    14  
    15  func UpdateJsonFile(filePath string, updates UpdateActions, vi *VersionInformation, indent string) error {
    16  	// parse the json file
    17  	json, err := gabs.ParseJSONFile(filePath)
    18  
    19  	if err != nil {
    20  		log.Errorf("Failed to parse %v file: %v", filePath, err)
    21  		return err
    22  	}
    23  
    24  	// apply updates
    25  	for _, u := range orderUpdates(updates) {
    26  		update := u.Update
    27  		path := u.Path
    28  
    29  		switch update {
    30  		case "$delete$":
    31  			if json.ExistsP(path) {
    32  				err = json.DeleteP(path)
    33  
    34  				if err != nil {
    35  					return err
    36  				}
    37  
    38  				log.Debugf("Deleted element: %v", path)
    39  			}
    40  		case "$null$":
    41  			log.Debugf("Updating element %v: null", path)
    42  
    43  			_, err = json.SetP(nil, path)
    44  
    45  			if err != nil {
    46  				return err
    47  			}
    48  		default:
    49  			// render value
    50  			newValue, err := RenderTemplate(update, path, vi)
    51  
    52  			if err != nil {
    53  				return err
    54  			}
    55  
    56  			// parse the value
    57  			log.Debugf("Updating element %v: %v", path, newValue)
    58  
    59  			var newValueObj interface{}
    60  
    61  			if true {
    62  				newValueBuf := bytes.NewBufferString(newValue)
    63  				decoder := jsonImpl.NewDecoder(newValueBuf)
    64  
    65  				token, err := decoder.Token()
    66  
    67  				if err != nil {
    68  					log.Errorf("Failed to parse JSON value '%v': %v", newValue, err)
    69  					return err
    70  				}
    71  
    72  				switch v := token.(type) {
    73  				case jsonImpl.Delim:
    74  					return fmt.Errorf("Failed to parse JSON value '%v': got delimiter", newValue)
    75  				default:
    76  					newValueObj = v
    77  				}
    78  			}
    79  
    80  			// update the value
    81  			_, err = json.SetP(newValueObj, path)
    82  
    83  			if err != nil {
    84  				return err
    85  			}
    86  		}
    87  	}
    88  
    89  	// write back the file
    90  	var newContent []byte
    91  
    92  	if indent == "" {
    93  		newContent = json.Bytes()
    94  	} else {
    95  		newContent = json.BytesIndent("", indent)
    96  	}
    97  
    98  	return ioutil.WriteFile(filePath, newContent, 0644)
    99  }