github.com/jenspinney/cli@v6.42.1-0.20190207184520-7450c600020e+incompatible/api/cloudcontroller/ccv3/resource.go (about)

     1  package ccv3
     2  
     3  import (
     4  	"encoding/json"
     5  	"os"
     6  	"strconv"
     7  
     8  	"code.cloudfoundry.org/cli/api/cloudcontroller"
     9  )
    10  
    11  // Resource represents a Cloud Controller Resource.
    12  type Resource struct {
    13  
    14  	// Filename is the name of the resource.
    15  	Filename string `json:"fn"`
    16  
    17  	// Mode is the operating system file mode (aka file permissions) of the
    18  	// resource.
    19  	Mode os.FileMode `json:"mode"`
    20  
    21  	// SHA1 represents the SHA-1 hash of the resource.
    22  	SHA1 string `json:"sha1"`
    23  
    24  	// Size represents the file size of the resource.
    25  	Size int64 `json:"size"`
    26  }
    27  
    28  // MarshalJSON converts a resource into a Cloud Controller Resource.
    29  func (r Resource) MarshalJSON() ([]byte, error) {
    30  	var ccResource struct {
    31  		Filename string `json:"fn,omitempty"`
    32  		Mode     string `json:"mode,omitempty"`
    33  		SHA1     string `json:"sha1"`
    34  		Size     int64  `json:"size"`
    35  	}
    36  
    37  	ccResource.Filename = r.Filename
    38  	ccResource.Size = r.Size
    39  	ccResource.SHA1 = r.SHA1
    40  	ccResource.Mode = strconv.FormatUint(uint64(r.Mode), 8)
    41  	return json.Marshal(ccResource)
    42  }
    43  
    44  // UnmarshalJSON helps unmarshal a Cloud Controller Resource response.
    45  func (r *Resource) UnmarshalJSON(data []byte) error {
    46  	var ccResource struct {
    47  		Filename string `json:"fn,omitempty"`
    48  		Mode     string `json:"mode,omitempty"`
    49  		SHA1     string `json:"sha1"`
    50  		Size     int64  `json:"size"`
    51  	}
    52  
    53  	err := cloudcontroller.DecodeJSON(data, &ccResource)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	r.Filename = ccResource.Filename
    59  	r.Size = ccResource.Size
    60  	r.SHA1 = ccResource.SHA1
    61  	mode, err := strconv.ParseUint(ccResource.Mode, 8, 32)
    62  	if err != nil {
    63  		return err
    64  	}
    65  
    66  	r.Mode = os.FileMode(mode)
    67  	return nil
    68  }