github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/cmd/juju/romulus/createbudget/createbudget.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package createbudget
     5  
     6  import (
     7  	"fmt"
     8  	"strconv"
     9  
    10  	"github.com/juju/cmd"
    11  	"github.com/juju/errors"
    12  	"github.com/juju/juju/cmd/modelcmd"
    13  	"gopkg.in/macaroon-bakery.v1/httpbakery"
    14  
    15  	api "github.com/juju/romulus/api/budget"
    16  )
    17  
    18  type createBudgetCommand struct {
    19  	modelcmd.JujuCommandBase
    20  	Name  string
    21  	Value string
    22  }
    23  
    24  // NewCreateBudgetCommand returns a new createBudgetCommand
    25  func NewCreateBudgetCommand() cmd.Command {
    26  	return &createBudgetCommand{}
    27  }
    28  
    29  const doc = `
    30  Create a new budget with monthly limit.
    31  
    32  Examples:
    33      # Creates a budget named 'qa' with a limit of 42.
    34      juju create-budget qa 42
    35  `
    36  
    37  // Info implements cmd.Command.Info.
    38  func (c *createBudgetCommand) Info() *cmd.Info {
    39  	return &cmd.Info{
    40  		Name:    "create-budget",
    41  		Purpose: "Create a new budget.",
    42  		Doc:     doc,
    43  	}
    44  }
    45  
    46  // Init implements cmd.Command.Init.
    47  func (c *createBudgetCommand) Init(args []string) error {
    48  	if len(args) < 2 {
    49  		return errors.New("name and value required")
    50  	}
    51  	c.Name, c.Value = args[0], args[1]
    52  	if _, err := strconv.ParseInt(c.Value, 10, 32); err != nil {
    53  		return errors.New("budget value needs to be a whole number")
    54  	}
    55  	return cmd.CheckEmpty(args[2:])
    56  }
    57  
    58  // Run implements cmd.Command.Run and has most of the logic for the run command.
    59  func (c *createBudgetCommand) Run(ctx *cmd.Context) error {
    60  	client, err := c.BakeryClient()
    61  	if err != nil {
    62  		return errors.Annotate(err, "failed to create an http client")
    63  	}
    64  	api, err := newAPIClient(client)
    65  	if err != nil {
    66  		return errors.Annotate(err, "failed to create an api client")
    67  	}
    68  	resp, err := api.CreateBudget(c.Name, c.Value)
    69  	if err != nil {
    70  		return errors.Annotate(err, "failed to create the budget")
    71  	}
    72  	fmt.Fprintln(ctx.Stdout, resp)
    73  	return nil
    74  }
    75  
    76  var newAPIClient = newAPIClientImpl
    77  
    78  func newAPIClientImpl(c *httpbakery.Client) (apiClient, error) {
    79  	client := api.NewClient(c)
    80  	return client, nil
    81  }
    82  
    83  type apiClient interface {
    84  	CreateBudget(name string, limit string) (string, error)
    85  }