github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/payload/api/helpers.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package api
     5  
     6  import (
     7  	"github.com/juju/errors"
     8  	"gopkg.in/juju/charm.v6-unstable"
     9  	"gopkg.in/juju/names.v2"
    10  
    11  	"github.com/juju/juju/payload"
    12  )
    13  
    14  // Payload2api converts a payload.FullPayloadInfo struct into
    15  // a Payload struct.
    16  func Payload2api(p payload.FullPayloadInfo) Payload {
    17  	labels := make([]string, len(p.Labels))
    18  	copy(labels, p.Labels)
    19  
    20  	var unitTag string
    21  	if p.Unit != "" {
    22  		unitTag = names.NewUnitTag(p.Unit).String()
    23  	}
    24  	var machineTag string
    25  	if p.Machine != "" {
    26  		machineTag = names.NewMachineTag(p.Machine).String()
    27  	}
    28  
    29  	return Payload{
    30  		Class:   p.Name,
    31  		Type:    p.Type,
    32  		ID:      p.ID,
    33  		Status:  p.Status,
    34  		Labels:  labels,
    35  		Unit:    unitTag,
    36  		Machine: machineTag,
    37  	}
    38  }
    39  
    40  // API2Payload converts an API Payload info struct into
    41  // a payload.FullPayloadInfo struct.
    42  func API2Payload(apiInfo Payload) (payload.FullPayloadInfo, error) {
    43  	labels := make([]string, len(apiInfo.Labels))
    44  	copy(labels, apiInfo.Labels)
    45  
    46  	var unit, machine string
    47  	var empty payload.FullPayloadInfo
    48  	if apiInfo.Unit != "" {
    49  		tag, err := names.ParseUnitTag(apiInfo.Unit)
    50  		if err != nil {
    51  			return empty, errors.Trace(err)
    52  		}
    53  		unit = tag.Id()
    54  	}
    55  	if apiInfo.Machine != "" {
    56  		tag, err := names.ParseMachineTag(apiInfo.Machine)
    57  		if err != nil {
    58  			return empty, errors.Trace(err)
    59  		}
    60  		machine = tag.Id()
    61  	}
    62  
    63  	return payload.FullPayloadInfo{
    64  		Payload: payload.Payload{
    65  			PayloadClass: charm.PayloadClass{
    66  				Name: apiInfo.Class,
    67  				Type: apiInfo.Type,
    68  			},
    69  			ID:     apiInfo.ID,
    70  			Status: apiInfo.Status,
    71  			Labels: labels,
    72  			Unit:   unit,
    73  		},
    74  		Machine: machine,
    75  	}, nil
    76  }