github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/cmd/juju/user/common.go (about) 1 // Copyright 2012-2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package user 5 6 import ( 7 "io/ioutil" 8 9 "github.com/juju/cmd" 10 "github.com/juju/errors" 11 "github.com/juju/names" 12 13 "github.com/juju/juju/cmd/envcmd" 14 "github.com/juju/juju/environs/configstore" 15 ) 16 17 // serverFileNotify is called with the absolute path of the written server 18 // file. 19 var serverFileNotify = func(string) {} 20 21 // EndpointProvider defines the method used by the writeServerFile 22 // in order to get the addresses and ca-cert of the juju server. 23 type EndpointProvider interface { 24 ConnectionEndpoint() (configstore.APIEndpoint, error) 25 } 26 27 func writeServerFile(endpointProvider EndpointProvider, ctx *cmd.Context, username, password, outPath string) error { 28 outPath = ctx.AbsPath(outPath) 29 endpoint, err := endpointProvider.ConnectionEndpoint() 30 if err != nil { 31 return errors.Trace(err) 32 } 33 if !names.IsValidUser(username) { 34 return errors.Errorf("%q is not a valid username", username) 35 } 36 outputInfo := envcmd.ServerFile{ 37 Username: username, 38 Password: password, 39 Addresses: endpoint.Addresses, 40 CACert: endpoint.CACert, 41 } 42 yaml, err := cmd.FormatYaml(outputInfo) 43 if err != nil { 44 return errors.Trace(err) 45 } 46 if err := ioutil.WriteFile(outPath, yaml, 0644); err != nil { 47 return errors.Trace(err) 48 } 49 serverFileNotify(outPath) 50 ctx.Infof("server file written to %s", outPath) 51 return nil 52 }