func serverArray(client *cm15.API, name string) []*cm15.Instance {
	serverArrayLocator := client.ServerArrayLocator("/api/server_arrays")
	serverArrays, err := serverArrayLocator.Index(rsapi.APIParams{"view": "default", "filter": []string{"name==" + name}})
	if err != nil {
		fail("Failed to retrieve server array: %v\n", err.Error())
	}
	if len(serverArrays) == 0 {
		fail("Could not find server array with name: %v\n", name)
	} else if len(serverArrays) != 1 {
		fail("More than one server array found with name: %v\n", name)
	}
	array := serverArrays[0]
	var instancesHref string
	for _, l := range array.Links {
		if l["rel"] == "current_instances" {
			instancesHref = l["href"]
			break
		}
	}
	instanceLocator := client.InstanceLocator(instancesHref)
	instances, err := instanceLocator.Index(rsapi.APIParams{})
	if err != nil {
		fail("Failed to retrieve current instances of the server array: %v\n", err.Error())
	}
	if len(instances) == 0 {
		fail("No instances found in server array: %v\n", name)
	}
	return instances
}

func serverArray ( client * cm15 . API , name string ) [ ] * cm15 . Instance { serverArrayLocator := client . ServerArrayLocator ( " " ) serverArrays , err := serverArrayLocator . Index ( rsapi . APIParams { " " : " " , " " : [ ] string { " " + name } } ) if err != nil { fail ( " \n " , err . Error ( ) ) } if len ( serverArrays ) == 0 { fail ( " \n " , name ) } else if len ( serverArrays ) != 1 { fail ( " \n " , name ) } array := serverArrays [ 0 ] var instancesHref string for _ , l := range array . Links { if l [ " " ] == " " { instancesHref = l [ " " ] break } } instanceLocator := client . InstanceLocator ( instancesHref ) instances , err := instanceLocator . Index ( rsapi . APIParams { } ) if err != nil { fail ( " \n " , err . Error ( ) ) } if len ( instances ) == 0 { fail ( " \n " , name ) } return instances }

// Makes a GET call on the given server array and returns all its current instances.

Makes a GET call on the given server array and returns all its current instances .


func server(client *cm15.API, name string) *cm15.Instance {
	serverLocator := client.ServerLocator("/api/servers")
	servers, err := serverLocator.Index(rsapi.APIParams{"view": "instance_detail", "filter": []string{"name==" + name}})
	if err != nil {
		fail("Failed to retrieve server: %v\n", err.Error())
	}
	if len(servers) == 0 {
		fail("Could not find server with name: %v\n", name)
	} else if len(servers) != 1 {
		fail("More than one server found with name: %v\n", name)
	}
	return servers[0].CurrentInstance
}

func server ( client * cm15 . API , name string ) * cm15 . Instance { serverLocator := client . ServerLocator ( " " ) servers , err := serverLocator . Index ( rsapi . APIParams { " " : " " , " " : [ ] string { " " + name } } ) if err != nil { fail ( " \n " , err . Error ( ) ) } if len ( servers ) == 0 { fail ( " \n " , name ) } else if len ( servers ) != 1 { fail ( " \n " , name ) } return servers [ 0 ] . CurrentInstance }

// Makes a GET call on the given server and returns the current instance of the server.

Makes a GET call on the given server and returns the current instance of the server .


func toPackageName(version string) string {
	if version == "unversioned" {
		return "v0"
	}
	parts := strings.Split(version, ".")
	i := 1
	p := parts[len(parts)-i]
	for p == "0" && i <= len(parts) {
		i++
		p = parts[len(parts)-i]
	}
	version = strings.Join(parts, "_")
	return fmt.Sprintf("v%s", version)
}

func toPackageName ( version string ) string { if version == " " { return " " } parts := strings . Split ( version , " " ) i := 1 p := parts [ len ( parts ) - i ] for p == " " && i <= len ( parts ) { i ++ p = parts [ len ( parts ) - i ] } version = strings . Join ( parts , " " ) return fmt . Sprintf ( " " , version ) }

// Convert version number in index.json to go package name
// "1.6" => "v1_6"

Convert version number in index . json to go package name 1 . 6 = > v1_6


func loadFile(file string) ([]byte, error) {
	if _, err := os.Stat(file); err != nil {
		return nil, fmt.Errorf("Cannot find '%s'", file)
	}
	js, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, fmt.Errorf("Cannot read '%s': %s", file, err)
	}
	return js, nil
}

func loadFile ( file string ) ( [ ] byte , error ) { if _ , err := os . Stat ( file ) ; err != nil { return nil , fmt . Errorf ( " " , file ) } js , err := ioutil . ReadFile ( file ) if err != nil { return nil , fmt . Errorf ( " " , file , err ) } return js , nil }

// Helper function that reads content from given file


func main() {
	app := kingpin.New("rsc", "A RightScale API client")
	app.Writer(os.Stdout)
	app.Version(VV)

	cmdLine, err := ParseCommandLine(app)
	if err != nil {
		line := strings.Join(os.Args, " ")
		PrintFatal("%s: %s", line, err.Error())
	}

	resp, err := ExecuteCommand(app, cmdLine)
	if err != nil {
		PrintFatal("%s", err.Error())
	}
	if resp == nil {
		return // No results, just exit (e.g. setup, printed help...)
	}

	var notExactlyOneError bool
	displayer, err := NewDisplayer(resp)
	if err != nil {
		PrintFatal("%s", err.Error())
	}
	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		// Let user know if something went wrong
		fmt.Fprintln(errOut, resp.Status)
		if len(displayer.body) > 0 {
			fmt.Fprintln(errOut, displayer.body)
		}
	} else if cmdLine.ExtractOneSelect != "" {
		err = displayer.ApplySingleExtract(cmdLine.ExtractOneSelect)
		if err != nil {
			notExactlyOneError = strings.Contains(err.Error(),
				"instead of one value") // Ugh, there has to be a better way
			PrintError(err.Error())
		}
		fmt.Fprint(out, displayer.Output())
	} else {
		if cmdLine.ExtractSelector != "" {
			err = displayer.ApplyExtract(cmdLine.ExtractSelector, false)
		} else if cmdLine.ExtractSelectorJSON != "" {
			err = displayer.ApplyExtract(cmdLine.ExtractSelectorJSON, true)
		} else if cmdLine.ExtractHeader != "" {
			err = displayer.ApplyHeaderExtract(cmdLine.ExtractHeader)
		}
		if err != nil {
			PrintFatal("%s", err.Error())
		} else if cmdLine.Pretty {
			displayer.Pretty()
		}
		fmt.Fprint(out, displayer.Output())
	}
	// Figure out exit code
	exitStatus := 0
	switch {
	case notExactlyOneError:
		exitStatus = 6
	case resp.StatusCode == 401:
		exitStatus = 1
	case resp.StatusCode == 403:
		exitStatus = 3
	case resp.StatusCode == 404:
		exitStatus = 4
	case resp.StatusCode > 399 && resp.StatusCode < 500:
		exitStatus = 2
	case resp.StatusCode > 499:
		exitStatus = 5
	}
	//fmt.Fprintf(os.Stderr, "exitStatus=%d\n", exitStatus)
	osExit(exitStatus)
}


func runCommand(client cmd.CommandClient, cmdLine *cmd.CommandLine) (resp *http.Response, err error) {
	cmds := strings.Split(cmdLine.Command, " ")
	if cmdLine.ShowHelp {
		err = client.ShowCommandHelp(cmdLine.Command)
	} else if len(cmds) > 1 && cmds[1] == "actions" {
		err = client.ShowAPIActions(cmdLine.Command)
	} else {
		resp, err = client.RunCommand(cmdLine.Command)
	}
	return
}

func runCommand ( client cmd . CommandClient , cmdLine * cmd . CommandLine ) ( resp * http . Response , err error ) { cmds := strings . Split ( cmdLine . Command , " " ) if cmdLine . ShowHelp { err = client . ShowCommandHelp ( cmdLine . Command ) } else if len ( cmds ) > 1 && cmds [ 1 ] == " " { err = client . ShowAPIActions ( cmdLine . Command ) } else { resp , err = client . RunCommand ( cmdLine . Command ) } return }

// Helper that runs command line with give command client


func CreateJSONResponse(b []byte) (resp *http.Response) {
	// Remove UTF-8 Byte Order Mark if it exists
	b = bytes.TrimPrefix(b, []byte{0xef, 0xbb, 0xbf})
	resp = &http.Response{
		StatusCode: 200,
		Body:       ioutil.NopCloser(bytes.NewBuffer(b)),
	}
	return resp
}

// Constructs an http response from JSON input from Stdin


func (api *API) AccountLocator(href string) *AccountLocator {
	return &AccountLocator{Href(href), api}
}

func ( api * API ) AccountLocator ( href string ) * AccountLocator { return & AccountLocator { Href ( href ) , api } }

// AccountLocator builds a locator from the given href.

AccountLocator builds a locator from the given href .


func (api *API) AccountGroupLocator(href string) *AccountGroupLocator {
	return &AccountGroupLocator{Href(href), api}
}

func ( api * API ) AccountGroupLocator ( href string ) * AccountGroupLocator { return & AccountGroupLocator { Href ( href ) , api } }

// AccountGroupLocator builds a locator from the given href.

AccountGroupLocator builds a locator from the given href .


func (api *API) AlertLocator(href string) *AlertLocator {
	return &AlertLocator{Href(href), api}
}

func ( api * API ) AlertLocator ( href string ) * AlertLocator { return & AlertLocator { Href ( href ) , api } }

// AlertLocator builds a locator from the given href.

AlertLocator builds a locator from the given href .


func (api *API) AlertSpecLocator(href string) *AlertSpecLocator {
	return &AlertSpecLocator{Href(href), api}
}

func ( api * API ) AlertSpecLocator ( href string ) * AlertSpecLocator { return & AlertSpecLocator { Href ( href ) , api } }

// AlertSpecLocator builds a locator from the given href.

AlertSpecLocator builds a locator from the given href .


func (api *API) AuditEntryLocator(href string) *AuditEntryLocator {
	return &AuditEntryLocator{Href(href), api}
}

func ( api * API ) AuditEntryLocator ( href string ) * AuditEntryLocator { return & AuditEntryLocator { Href ( href ) , api } }

// AuditEntryLocator builds a locator from the given href.

AuditEntryLocator builds a locator from the given href .


func (api *API) BackupLocator(href string) *BackupLocator {
	return &BackupLocator{Href(href), api}
}

func ( api * API ) BackupLocator ( href string ) * BackupLocator { return & BackupLocator { Href ( href ) , api } }

// BackupLocator builds a locator from the given href.

BackupLocator builds a locator from the given href .


func (api *API) ChildAccountLocator(href string) *ChildAccountLocator {
	return &ChildAccountLocator{Href(href), api}
}

func ( api * API ) ChildAccountLocator ( href string ) * ChildAccountLocator { return & ChildAccountLocator { Href ( href ) , api } }

// ChildAccountLocator builds a locator from the given href.

ChildAccountLocator builds a locator from the given href .


func (api *API) CloudLocator(href string) *CloudLocator {
	return &CloudLocator{Href(href), api}
}

func ( api * API ) CloudLocator ( href string ) * CloudLocator { return & CloudLocator { Href ( href ) , api } }

// CloudLocator builds a locator from the given href.

CloudLocator builds a locator from the given href .


func (api *API) CloudAccountLocator(href string) *CloudAccountLocator {
	return &CloudAccountLocator{Href(href), api}
}

func ( api * API ) CloudAccountLocator ( href string ) * CloudAccountLocator { return & CloudAccountLocator { Href ( href ) , api } }

// CloudAccountLocator builds a locator from the given href.

CloudAccountLocator builds a locator from the given href .


func (api *API) CookbookLocator(href string) *CookbookLocator {
	return &CookbookLocator{Href(href), api}
}

func ( api * API ) CookbookLocator ( href string ) * CookbookLocator { return & CookbookLocator { Href ( href ) , api } }

// CookbookLocator builds a locator from the given href.

CookbookLocator builds a locator from the given href .


func (api *API) CookbookAttachmentLocator(href string) *CookbookAttachmentLocator {
	return &CookbookAttachmentLocator{Href(href), api}
}

func ( api * API ) CookbookAttachmentLocator ( href string ) * CookbookAttachmentLocator { return & CookbookAttachmentLocator { Href ( href ) , api } }

// CookbookAttachmentLocator builds a locator from the given href.

CookbookAttachmentLocator builds a locator from the given href .


func (api *API) CredentialLocator(href string) *CredentialLocator {
	return &CredentialLocator{Href(href), api}
}

func ( api * API ) CredentialLocator ( href string ) * CredentialLocator { return & CredentialLocator { Href ( href ) , api } }

// CredentialLocator builds a locator from the given href.

CredentialLocator builds a locator from the given href .


func (api *API) DatacenterLocator(href string) *DatacenterLocator {
	return &DatacenterLocator{Href(href), api}
}

func ( api * API ) DatacenterLocator ( href string ) * DatacenterLocator { return & DatacenterLocator { Href ( href ) , api } }

// DatacenterLocator builds a locator from the given href.

DatacenterLocator builds a locator from the given href .


func (api *API) DeploymentLocator(href string) *DeploymentLocator {
	return &DeploymentLocator{Href(href), api}
}

func ( api * API ) DeploymentLocator ( href string ) * DeploymentLocator { return & DeploymentLocator { Href ( href ) , api } }

// DeploymentLocator builds a locator from the given href.

DeploymentLocator builds a locator from the given href .


func (api *API) HealthCheckLocator(href string) *HealthCheckLocator {
	return &HealthCheckLocator{Href(href), api}
}

func ( api * API ) HealthCheckLocator ( href string ) * HealthCheckLocator { return & HealthCheckLocator { Href ( href ) , api } }

// HealthCheckLocator builds a locator from the given href.

HealthCheckLocator builds a locator from the given href .


func (api *API) IdentityProviderLocator(href string) *IdentityProviderLocator {
	return &IdentityProviderLocator{Href(href), api}
}

func ( api * API ) IdentityProviderLocator ( href string ) * IdentityProviderLocator { return & IdentityProviderLocator { Href ( href ) , api } }

// IdentityProviderLocator builds a locator from the given href.

IdentityProviderLocator builds a locator from the given href .


func (api *API) ImageLocator(href string) *ImageLocator {
	return &ImageLocator{Href(href), api}
}

func ( api * API ) ImageLocator ( href string ) * ImageLocator { return & ImageLocator { Href ( href ) , api } }

// ImageLocator builds a locator from the given href.

ImageLocator builds a locator from the given href .


func (api *API) InputLocator(href string) *InputLocator {
	return &InputLocator{Href(href), api}
}

func ( api * API ) InputLocator ( href string ) * InputLocator { return & InputLocator { Href ( href ) , api } }

// InputLocator builds a locator from the given href.

InputLocator builds a locator from the given href .


func (api *API) InstanceLocator(href string) *InstanceLocator {
	return &InstanceLocator{Href(href), api}
}

func ( api * API ) InstanceLocator ( href string ) * InstanceLocator { return & InstanceLocator { Href ( href ) , api } }

// InstanceLocator builds a locator from the given href.

InstanceLocator builds a locator from the given href .


func (api *API) InstanceTypeLocator(href string) *InstanceTypeLocator {
	return &InstanceTypeLocator{Href(href), api}
}

func ( api * API ) InstanceTypeLocator ( href string ) * InstanceTypeLocator { return & InstanceTypeLocator { Href ( href ) , api } }

// InstanceTypeLocator builds a locator from the given href.

InstanceTypeLocator builds a locator from the given href .


func (api *API) IpAddressLocator(href string) *IpAddressLocator {
	return &IpAddressLocator{Href(href), api}
}

func ( api * API ) IpAddressLocator ( href string ) * IpAddressLocator { return & IpAddressLocator { Href ( href ) , api } }

// IpAddressLocator builds a locator from the given href.

IpAddressLocator builds a locator from the given href .


func (api *API) IpAddressBindingLocator(href string) *IpAddressBindingLocator {
	return &IpAddressBindingLocator{Href(href), api}
}

func ( api * API ) IpAddressBindingLocator ( href string ) * IpAddressBindingLocator { return & IpAddressBindingLocator { Href ( href ) , api } }

// IpAddressBindingLocator builds a locator from the given href.

IpAddressBindingLocator builds a locator from the given href .


func (api *API) MonitoringMetricLocator(href string) *MonitoringMetricLocator {
	return &MonitoringMetricLocator{Href(href), api}
}

func ( api * API ) MonitoringMetricLocator ( href string ) * MonitoringMetricLocator { return & MonitoringMetricLocator { Href ( href ) , api } }

// MonitoringMetricLocator builds a locator from the given href.

MonitoringMetricLocator builds a locator from the given href .


func (api *API) MultiCloudImageLocator(href string) *MultiCloudImageLocator {
	return &MultiCloudImageLocator{Href(href), api}
}

func ( api * API ) MultiCloudImageLocator ( href string ) * MultiCloudImageLocator { return & MultiCloudImageLocator { Href ( href ) , api } }

// MultiCloudImageLocator builds a locator from the given href.

MultiCloudImageLocator builds a locator from the given href .


func (api *API) MultiCloudImageMatcherLocator(href string) *MultiCloudImageMatcherLocator {
	return &MultiCloudImageMatcherLocator{Href(href), api}
}

func ( api * API ) MultiCloudImageMatcherLocator ( href string ) * MultiCloudImageMatcherLocator { return & MultiCloudImageMatcherLocator { Href ( href ) , api } }

// MultiCloudImageMatcherLocator builds a locator from the given href.

MultiCloudImageMatcherLocator builds a locator from the given href .


func (api *API) MultiCloudImageSettingLocator(href string) *MultiCloudImageSettingLocator {
	return &MultiCloudImageSettingLocator{Href(href), api}
}

func ( api * API ) MultiCloudImageSettingLocator ( href string ) * MultiCloudImageSettingLocator { return & MultiCloudImageSettingLocator { Href ( href ) , api } }

// MultiCloudImageSettingLocator builds a locator from the given href.

MultiCloudImageSettingLocator builds a locator from the given href .


func (api *API) NetworkLocator(href string) *NetworkLocator {
	return &NetworkLocator{Href(href), api}
}

func ( api * API ) NetworkLocator ( href string ) * NetworkLocator { return & NetworkLocator { Href ( href ) , api } }

// NetworkLocator builds a locator from the given href.

NetworkLocator builds a locator from the given href .


func (api *API) NetworkGatewayLocator(href string) *NetworkGatewayLocator {
	return &NetworkGatewayLocator{Href(href), api}
}

func ( api * API ) NetworkGatewayLocator ( href string ) * NetworkGatewayLocator { return & NetworkGatewayLocator { Href ( href ) , api } }

// NetworkGatewayLocator builds a locator from the given href.

NetworkGatewayLocator builds a locator from the given href .


func (api *API) NetworkOptionGroupLocator(href string) *NetworkOptionGroupLocator {
	return &NetworkOptionGroupLocator{Href(href), api}
}

func ( api * API ) NetworkOptionGroupLocator ( href string ) * NetworkOptionGroupLocator { return & NetworkOptionGroupLocator { Href ( href ) , api } }

// NetworkOptionGroupLocator builds a locator from the given href.

NetworkOptionGroupLocator builds a locator from the given href .


func (api *API) NetworkOptionGroupAttachmentLocator(href string) *NetworkOptionGroupAttachmentLocator {
	return &NetworkOptionGroupAttachmentLocator{Href(href), api}
}

func ( api * API ) NetworkOptionGroupAttachmentLocator ( href string ) * NetworkOptionGroupAttachmentLocator { return & NetworkOptionGroupAttachmentLocator { Href ( href ) , api } }

// NetworkOptionGroupAttachmentLocator builds a locator from the given href.

NetworkOptionGroupAttachmentLocator builds a locator from the given href .


func (api *API) Oauth2Locator(href string) *Oauth2Locator {
	return &Oauth2Locator{Href(href), api}
}

func ( api * API ) Oauth2Locator ( href string ) * Oauth2Locator { return & Oauth2Locator { Href ( href ) , api } }

// Oauth2Locator builds a locator from the given href.

Oauth2Locator builds a locator from the given href .


func (api *API) PermissionLocator(href string) *PermissionLocator {
	return &PermissionLocator{Href(href), api}
}

func ( api * API ) PermissionLocator ( href string ) * PermissionLocator { return & PermissionLocator { Href ( href ) , api } }

// PermissionLocator builds a locator from the given href.

PermissionLocator builds a locator from the given href .


func (api *API) PlacementGroupLocator(href string) *PlacementGroupLocator {
	return &PlacementGroupLocator{Href(href), api}
}

func ( api * API ) PlacementGroupLocator ( href string ) * PlacementGroupLocator { return & PlacementGroupLocator { Href ( href ) , api } }

// PlacementGroupLocator builds a locator from the given href.

PlacementGroupLocator builds a locator from the given href .


func (api *API) PreferenceLocator(href string) *PreferenceLocator {
	return &PreferenceLocator{Href(href), api}
}

func ( api * API ) PreferenceLocator ( href string ) * PreferenceLocator { return & PreferenceLocator { Href ( href ) , api } }

// PreferenceLocator builds a locator from the given href.

PreferenceLocator builds a locator from the given href .


func (api *API) PublicationLocator(href string) *PublicationLocator {
	return &PublicationLocator{Href(href), api}
}

func ( api * API ) PublicationLocator ( href string ) * PublicationLocator { return & PublicationLocator { Href ( href ) , api } }

// PublicationLocator builds a locator from the given href.

PublicationLocator builds a locator from the given href .


func (api *API) PublicationLineageLocator(href string) *PublicationLineageLocator {
	return &PublicationLineageLocator{Href(href), api}
}

func ( api * API ) PublicationLineageLocator ( href string ) * PublicationLineageLocator { return & PublicationLineageLocator { Href ( href ) , api } }

// PublicationLineageLocator builds a locator from the given href.

PublicationLineageLocator builds a locator from the given href .


func (api *API) RecurringVolumeAttachmentLocator(href string) *RecurringVolumeAttachmentLocator {
	return &RecurringVolumeAttachmentLocator{Href(href), api}
}

func ( api * API ) RecurringVolumeAttachmentLocator ( href string ) * RecurringVolumeAttachmentLocator { return & RecurringVolumeAttachmentLocator { Href ( href ) , api } }

// RecurringVolumeAttachmentLocator builds a locator from the given href.

RecurringVolumeAttachmentLocator builds a locator from the given href .


func (api *API) RepositoryLocator(href string) *RepositoryLocator {
	return &RepositoryLocator{Href(href), api}
}

func ( api * API ) RepositoryLocator ( href string ) * RepositoryLocator { return & RepositoryLocator { Href ( href ) , api } }

// RepositoryLocator builds a locator from the given href.

RepositoryLocator builds a locator from the given href .


func (api *API) RepositoryAssetLocator(href string) *RepositoryAssetLocator {
	return &RepositoryAssetLocator{Href(href), api}
}

func ( api * API ) RepositoryAssetLocator ( href string ) * RepositoryAssetLocator { return & RepositoryAssetLocator { Href ( href ) , api } }

// RepositoryAssetLocator builds a locator from the given href.

RepositoryAssetLocator builds a locator from the given href .


func (api *API) ResourceGroupLocator(href string) *ResourceGroupLocator {
	return &ResourceGroupLocator{Href(href), api}
}

func ( api * API ) ResourceGroupLocator ( href string ) * ResourceGroupLocator { return & ResourceGroupLocator { Href ( href ) , api } }

// ResourceGroupLocator builds a locator from the given href.

ResourceGroupLocator builds a locator from the given href .


func (api *API) RightScriptLocator(href string) *RightScriptLocator {
	return &RightScriptLocator{Href(href), api}
}

func ( api * API ) RightScriptLocator ( href string ) * RightScriptLocator { return & RightScriptLocator { Href ( href ) , api } }

// RightScriptLocator builds a locator from the given href.

RightScriptLocator builds a locator from the given href .


func (api *API) RightScriptAttachmentLocator(href string) *RightScriptAttachmentLocator {
	return &RightScriptAttachmentLocator{Href(href), api}
}

func ( api * API ) RightScriptAttachmentLocator ( href string ) * RightScriptAttachmentLocator { return & RightScriptAttachmentLocator { Href ( href ) , api } }

// RightScriptAttachmentLocator builds a locator from the given href.

RightScriptAttachmentLocator builds a locator from the given href .


func (api *API) RouteLocator(href string) *RouteLocator {
	return &RouteLocator{Href(href), api}
}

func ( api * API ) RouteLocator ( href string ) * RouteLocator { return & RouteLocator { Href ( href ) , api } }

// RouteLocator builds a locator from the given href.

RouteLocator builds a locator from the given href .


func (api *API) RouteTableLocator(href string) *RouteTableLocator {
	return &RouteTableLocator{Href(href), api}
}

func ( api * API ) RouteTableLocator ( href string ) * RouteTableLocator { return & RouteTableLocator { Href ( href ) , api } }

// RouteTableLocator builds a locator from the given href.

RouteTableLocator builds a locator from the given href .


func (api *API) RunnableBindingLocator(href string) *RunnableBindingLocator {
	return &RunnableBindingLocator{Href(href), api}
}

func ( api * API ) RunnableBindingLocator ( href string ) * RunnableBindingLocator { return & RunnableBindingLocator { Href ( href ) , api } }

// RunnableBindingLocator builds a locator from the given href.

RunnableBindingLocator builds a locator from the given href .


func (api *API) SchedulerLocator(href string) *SchedulerLocator {
	return &SchedulerLocator{Href(href), api}
}

func ( api * API ) SchedulerLocator ( href string ) * SchedulerLocator { return & SchedulerLocator { Href ( href ) , api } }

// SchedulerLocator builds a locator from the given href.

SchedulerLocator builds a locator from the given href .


func (api *API) SecurityGroupLocator(href string) *SecurityGroupLocator {
	return &SecurityGroupLocator{Href(href), api}
}

func ( api * API ) SecurityGroupLocator ( href string ) * SecurityGroupLocator { return & SecurityGroupLocator { Href ( href ) , api } }

// SecurityGroupLocator builds a locator from the given href.

SecurityGroupLocator builds a locator from the given href .


func (api *API) SecurityGroupRuleLocator(href string) *SecurityGroupRuleLocator {
	return &SecurityGroupRuleLocator{Href(href), api}
}

func ( api * API ) SecurityGroupRuleLocator ( href string ) * SecurityGroupRuleLocator { return & SecurityGroupRuleLocator { Href ( href ) , api } }

// SecurityGroupRuleLocator builds a locator from the given href.

SecurityGroupRuleLocator builds a locator from the given href .


func (api *API) ServerLocator(href string) *ServerLocator {
	return &ServerLocator{Href(href), api}
}

func ( api * API ) ServerLocator ( href string ) * ServerLocator { return & ServerLocator { Href ( href ) , api } }

// ServerLocator builds a locator from the given href.

ServerLocator builds a locator from the given href .


func (api *API) ServerArrayLocator(href string) *ServerArrayLocator {
	return &ServerArrayLocator{Href(href), api}
}

func ( api * API ) ServerArrayLocator ( href string ) * ServerArrayLocator { return & ServerArrayLocator { Href ( href ) , api } }

// ServerArrayLocator builds a locator from the given href.

ServerArrayLocator builds a locator from the given href .


func (api *API) ServerTemplateLocator(href string) *ServerTemplateLocator {
	return &ServerTemplateLocator{Href(href), api}
}

func ( api * API ) ServerTemplateLocator ( href string ) * ServerTemplateLocator { return & ServerTemplateLocator { Href ( href ) , api } }

// ServerTemplateLocator builds a locator from the given href.

ServerTemplateLocator builds a locator from the given href .


func (api *API) ServerTemplateMultiCloudImageLocator(href string) *ServerTemplateMultiCloudImageLocator {
	return &ServerTemplateMultiCloudImageLocator{Href(href), api}
}

func ( api * API ) ServerTemplateMultiCloudImageLocator ( href string ) * ServerTemplateMultiCloudImageLocator { return & ServerTemplateMultiCloudImageLocator { Href ( href ) , api } }

// ServerTemplateMultiCloudImageLocator builds a locator from the given href.

ServerTemplateMultiCloudImageLocator builds a locator from the given href .


func (api *API) SessionLocator(href string) *SessionLocator {
	return &SessionLocator{Href(href), api}
}

func ( api * API ) SessionLocator ( href string ) * SessionLocator { return & SessionLocator { Href ( href ) , api } }

// SessionLocator builds a locator from the given href.

SessionLocator builds a locator from the given href .


func (api *API) SshKeyLocator(href string) *SshKeyLocator {
	return &SshKeyLocator{Href(href), api}
}

func ( api * API ) SshKeyLocator ( href string ) * SshKeyLocator { return & SshKeyLocator { Href ( href ) , api } }

// SshKeyLocator builds a locator from the given href.

SshKeyLocator builds a locator from the given href .


func (api *API) SubnetLocator(href string) *SubnetLocator {
	return &SubnetLocator{Href(href), api}
}

func ( api * API ) SubnetLocator ( href string ) * SubnetLocator { return & SubnetLocator { Href ( href ) , api } }

// SubnetLocator builds a locator from the given href.

SubnetLocator builds a locator from the given href .


func (api *API) TagLocator(href string) *TagLocator {
	return &TagLocator{Href(href), api}
}

func ( api * API ) TagLocator ( href string ) * TagLocator { return & TagLocator { Href ( href ) , api } }

// TagLocator builds a locator from the given href.

TagLocator builds a locator from the given href .


func (api *API) TaskLocator(href string) *TaskLocator {
	return &TaskLocator{Href(href), api}
}

func ( api * API ) TaskLocator ( href string ) * TaskLocator { return & TaskLocator { Href ( href ) , api } }

// TaskLocator builds a locator from the given href.

TaskLocator builds a locator from the given href .


func (api *API) UserLocator(href string) *UserLocator {
	return &UserLocator{Href(href), api}
}

func ( api * API ) UserLocator ( href string ) * UserLocator { return & UserLocator { Href ( href ) , api } }

// UserLocator builds a locator from the given href.

UserLocator builds a locator from the given href .


func (api *API) UserDataLocator(href string) *UserDataLocator {
	return &UserDataLocator{Href(href), api}
}

func ( api * API ) UserDataLocator ( href string ) * UserDataLocator { return & UserDataLocator { Href ( href ) , api } }

// UserDataLocator builds a locator from the given href.

UserDataLocator builds a locator from the given href .


func (api *API) VolumeLocator(href string) *VolumeLocator {
	return &VolumeLocator{Href(href), api}
}

func ( api * API ) VolumeLocator ( href string ) * VolumeLocator { return & VolumeLocator { Href ( href ) , api } }

// VolumeLocator builds a locator from the given href.

VolumeLocator builds a locator from the given href .


func (api *API) VolumeAttachmentLocator(href string) *VolumeAttachmentLocator {
	return &VolumeAttachmentLocator{Href(href), api}
}

func ( api * API ) VolumeAttachmentLocator ( href string ) * VolumeAttachmentLocator { return & VolumeAttachmentLocator { Href ( href ) , api } }

// VolumeAttachmentLocator builds a locator from the given href.

VolumeAttachmentLocator builds a locator from the given href .


func (api *API) VolumeSnapshotLocator(href string) *VolumeSnapshotLocator {
	return &VolumeSnapshotLocator{Href(href), api}
}

func ( api * API ) VolumeSnapshotLocator ( href string ) * VolumeSnapshotLocator { return & VolumeSnapshotLocator { Href ( href ) , api } }

// VolumeSnapshotLocator builds a locator from the given href.

VolumeSnapshotLocator builds a locator from the given href .


func (api *API) VolumeTypeLocator(href string) *VolumeTypeLocator {
	return &VolumeTypeLocator{Href(href), api}
}

func ( api * API ) VolumeTypeLocator ( href string ) * VolumeTypeLocator { return & VolumeTypeLocator { Href ( href ) , api } }

// VolumeTypeLocator builds a locator from the given href.

VolumeTypeLocator builds a locator from the given href .


func RegisterCommands(registrar rsapi.APICommandRegistrar) {
	commandValues = rsapi.ActionCommands{}
	registrar.RegisterActionCommands(APIName, GenMetadata, commandValues)
}

func RegisterCommands ( registrar rsapi . APICommandRegistrar ) { commandValues = rsapi . ActionCommands { } registrar . RegisterActionCommands ( APIName , GenMetadata , commandValues ) }

// RegisterCommands registers all the commands with the kinpin application.

RegisterCommands registers all the commands with the kinpin application .


func (a *API) ShowCommandHelp(cmd string) error {
	return a.ShowHelp(cmd, "/rll", commandValues)
}

func ( a * API ) ShowCommandHelp ( cmd string ) error { return a . ShowHelp ( cmd , " " , commandValues ) }

// ShowCommandHelp displays the command help.

ShowCommandHelp displays the command help .


func (a *API) ShowAPIActions(cmd string) error {
	return a.ShowActions(cmd, "/rll", commandValues)
}

func ( a * API ) ShowAPIActions ( cmd string ) error { return a . ShowActions ( cmd , " " , commandValues ) }

// ShowAPIActions displays the command hrefs.

ShowAPIActions displays the command hrefs .


func (a *API) ShowHelp(cmd, hrefPrefix string, values ActionCommands) error {
	target, _, err := a.ParseCommandAndFlags(cmd, hrefPrefix, values)
	if err != nil {
		return err
	}
	_, action, href := target.Resource, target.Action, target.Href
	if len(action.CommandFlags) == 0 {
		fmt.Printf("usage: rsc [<FLAGS>] %s %s %s\n\n%s\n", strings.Split(cmd, " ")[0],
			action.Name, href, action.Description)
		return nil
	}
	flagHelp := make([]string, len(action.CommandFlags))
	for i, f := range action.CommandFlags {
		var attrs string
		if f.Mandatory {
			attrs = "required"
		} else {
			attrs = "optional"
		}
		if len(f.ValidValues) > 0 {
			attrs += ", [" + strings.Join(f.ValidValues, "|") + "]"
		}
		if f.Regexp != nil {
			attrs += ", /" + f.Regexp.String() + "/"
		}
		flagHelp[i] = fmt.Sprintf("%s=%s\n    <%s> %s", f.Name, f.Type, attrs, f.Description)
	}
	fmt.Printf("usage: rsc [<FLAGS>] %s %s %s [<PARAMS>]\n\n%s\n\n", strings.Split(cmd, " ")[0],
		action.Name, href, action.Description)
	fmt.Printf("PARAMS:\n%s\n", strings.Join(flagHelp, "\n\n"))
	return nil
}

func ( a * API ) ShowHelp ( cmd , hrefPrefix string , values ActionCommands ) error { target , _ , err := a . ParseCommandAndFlags ( cmd , hrefPrefix , values ) if err != nil { return err } _ , action , href := target . Resource , target . Action , target . Href if len ( action . CommandFlags ) == 0 { fmt . Printf ( " \n \n \n " , strings . Split ( cmd , " " ) [ 0 ] , action . Name , href , action . Description ) return nil } flagHelp := make ( [ ] string , len ( action . CommandFlags ) ) for i , f := range action . CommandFlags { var attrs string if f . Mandatory { attrs = " " } else { attrs = " " } if len ( f . ValidValues ) > 0 { attrs += " " + strings . Join ( f . ValidValues , " " ) + " " } if f . Regexp != nil { attrs += " " + f . Regexp . String ( ) + " " } flagHelp [ i ] = fmt . Sprintf ( " \n " , f . Name , f . Type , attrs , f . Description ) } fmt . Printf ( " \n \n \n \n " , strings . Split ( cmd , " " ) [ 0 ] , action . Name , href , action . Description ) fmt . Printf ( " \n \n " , strings . Join ( flagHelp , " \n \n " ) ) return nil }

// ShowHelp displays help for the given command and flags.

ShowHelp displays help for the given command and flags .


func (a *API) ParseCommandAndFlags(cmd, hrefPrefix string, values ActionCommands) (*CommandTarget, []string, error) {
	resource, vars, err := a.parseResource(cmd, hrefPrefix, values)
	if err != nil {
		return nil, nil, err
	}
	var action *metadata.Action
	elems := strings.Split(cmd, " ")
	actionName := elems[len(elems)-1]
	for _, a := range resource.Actions {
		if a.Name == actionName {
			action = a
			break
		}
	}
	if action == nil {
		supported := make([]string, len(resource.Actions))
		for i, a := range resource.Actions {
			supported[i] = a.Name
		}
		return nil, nil, fmt.Errorf("Unknown %s action '%s'. Supported actions are: %s",
			resource.Name, actionName, strings.Join(supported, ", "))
	}

	path, err := action.URL(vars)
	if err != nil {
		return nil, nil, err
	}
	flags := values[cmd]

	return &CommandTarget{resource, action, path, flags.Href}, flags.Params, nil
}

func ( a * API ) ParseCommandAndFlags ( cmd , hrefPrefix string , values ActionCommands ) ( * CommandTarget , [ ] string , error ) { resource , vars , err := a . parseResource ( cmd , hrefPrefix , values ) if err != nil { return nil , nil , err } var action * metadata . Action elems := strings . Split ( cmd , " " ) actionName := elems [ len ( elems ) - 1 ] for _ , a := range resource . Actions { if a . Name == actionName { action = a break } } if action == nil { supported := make ( [ ] string , len ( resource . Actions ) ) for i , a := range resource . Actions { supported [ i ] = a . Name } return nil , nil , fmt . Errorf ( " " , resource . Name , actionName , strings . Join ( supported , " " ) ) } path , err := action . URL ( vars ) if err != nil { return nil , nil , err } flags := values [ cmd ] return & CommandTarget { resource , action , path , flags . Href } , flags . Params , nil }

// ParseCommandAndFlags parses a command flag and infers the resource, action, href and params.

ParseCommandAndFlags parses a command flag and infers the resource action href and params .


func validateFlagValue(value string, param *metadata.ActionParam) error {
	if param.Regexp != nil {
		if !param.Regexp.MatchString(value) {
			return fmt.Errorf("Invalid value '%s' for '%s', value must validate /%s/",
				value, param.Name, param.Regexp.String())
		}
	}
	if param.NonBlank && value == "" {
		return fmt.Errorf("Invalid value for '%s', value must not be blank",
			param.Name)
	}
	if len(param.ValidValues) > 0 && param.Name != "filter[]" { // filter[] is special: it has values just so --help can list them
		found := false
		for _, v := range param.ValidValues {
			if v == value {
				found = true
				break
			}
		}
		if !found {
			return fmt.Errorf("Invalid value for '%s', value must be one of %s, value provided was '%s'",
				param.Name, strings.Join(param.ValidValues, ", "), value)
		}
	}

	return nil
}

// Validate flag value using validation criteria provided in metadata


func buildQuery(values []APIParams) (APIParams, error) {
	query := APIParams{}
	for _, value := range values {
		// Only one iteration below, flatten params only have one element each
		for name, param := range value {
			if q, ok := query[name]; ok {
				if a, ok := q.([]interface{}); ok {
					query[name] = append(a, param)
				} else {
					query[name] = []interface{}{q, param}
				}
			} else {
				query[name] = param
			}
		}
	}
	return query, nil
}

// Reconstruct query from flatten values


func buildPayload(values []APIParams) (APIParams, error) {
	payload := APIParams{}
	for _, value := range values {
		// Only one iteration below, flatten params only have one element each
		for name, param := range value {
			if _, err := Normalize(payload, name, param); err != nil {
				return nil, err
			}
		}
	}
	return payload, nil
}

// Reconstruct payload map from flatten values


func shortenPattern(res *metadata.Resource, pattern, suffix string) (string, bool) {
	if strings.HasSuffix(pattern, suffix) {
		pat := strings.TrimSuffix(pattern, suffix)
		for _, action := range res.Actions {
			for _, pattern2 := range action.PathPatterns {
				vars := pattern2.Variables
				ivars := make([]interface{}, len(vars))
				for i, v := range vars {
					ivars[i] = interface{}(":" + v)
				}
				subPattern := pattern2.Pattern
				pat2 := fmt.Sprintf(subPattern, ivars...)
				if pat == pat2 {
					return pat, true
				}
			}
		}
	}
	return pattern, false
}

func shortenPattern ( res * metadata . Resource , pattern , suffix string ) ( string , bool ) { if strings . HasSuffix ( pattern , suffix ) { pat := strings . TrimSuffix ( pattern , suffix ) for _ , action := range res . Actions { for _ , pattern2 := range action . PathPatterns { vars := pattern2 . Variables ivars := make ( [ ] interface { } , len ( vars ) ) for i , v := range vars { ivars [ i ] = interface { } ( " " + v ) } subPattern := pattern2 . Pattern pat2 := fmt . Sprintf ( subPattern , ivars ... ) if pat == pat2 { return pat , true } } } } return pattern , false }

// Attempt to shorten action pattern for display by looking at other action hrefs
// and picking one that doesn't have the suffix if there is one.

Attempt to shorten action pattern for display by looking at other action hrefs and picking one that doesn t have the suffix if there is one .


func cleanDescription(doc string) string {
	docBits := strings.Split(doc, "Required security scope")
	doc = docBits[0]

	lines := strings.Split(doc, "\n")
	fullLines := make([]string, len(lines))
	i := 0
	for _, line := range lines {
		if len(line) > 0 && !blankRegexp.MatchString(line) {
			fullLines[i] = line
			i++
		}
	}
	return strings.Join(fullLines[:i], "\n")
}

func cleanDescription ( doc string ) string { docBits := strings . Split ( doc , " " ) doc = docBits [ 0 ] lines := strings . Split ( doc , " \n " ) fullLines := make ( [ ] string , len ( lines ) ) i := 0 for _ , line := range lines { if len ( line ) > 0 && ! blankRegexp . MatchString ( line ) { fullLines [ i ] = line i ++ } } return strings . Join ( fullLines [ : i ] , " \n " ) }

// cleans up description, removing blank lines and extraneous info

cleans up description removing blank lines and extraneous info


func fileExists(file string) bool {
	_, err := os.Stat(file)
	return err == nil
}

func fileExists ( file string ) bool { _ , err := os . Stat ( file ) return err == nil }

// fileExists reads content from existing file and returns a byte array


func (api *API) AnalysisSnapshotLocator(href string) *AnalysisSnapshotLocator {
	return &AnalysisSnapshotLocator{Href(href), api}
}

func ( api * API ) AnalysisSnapshotLocator ( href string ) * AnalysisSnapshotLocator { return & AnalysisSnapshotLocator { Href ( href ) , api } }

// AnalysisSnapshotLocator builds a locator from the given href.

AnalysisSnapshotLocator builds a locator from the given href .


func (api *API) BudgetAlertLocator(href string) *BudgetAlertLocator {
	return &BudgetAlertLocator{Href(href), api}
}

func ( api * API ) BudgetAlertLocator ( href string ) * BudgetAlertLocator { return & BudgetAlertLocator { Href ( href ) , api } }

// BudgetAlertLocator builds a locator from the given href.

BudgetAlertLocator builds a locator from the given href .


func (api *API) CloudBillLocator(href string) *CloudBillLocator {
	return &CloudBillLocator{Href(href), api}
}

func ( api * API ) CloudBillLocator ( href string ) * CloudBillLocator { return & CloudBillLocator { Href ( href ) , api } }

// CloudBillLocator builds a locator from the given href.

CloudBillLocator builds a locator from the given href .


func (api *API) CloudBillMetricLocator(href string) *CloudBillMetricLocator {
	return &CloudBillMetricLocator{Href(href), api}
}

func ( api * API ) CloudBillMetricLocator ( href string ) * CloudBillMetricLocator { return & CloudBillMetricLocator { Href ( href ) , api } }

// CloudBillMetricLocator builds a locator from the given href.

CloudBillMetricLocator builds a locator from the given href .


func (api *API) CurrentUserLocator(href string) *CurrentUserLocator {
	return &CurrentUserLocator{Href(href), api}
}

func ( api * API ) CurrentUserLocator ( href string ) * CurrentUserLocator { return & CurrentUserLocator { Href ( href ) , api } }

// CurrentUserLocator builds a locator from the given href.

CurrentUserLocator builds a locator from the given href .


func (api *API) InstanceCombinationLocator(href string) *InstanceCombinationLocator {
	return &InstanceCombinationLocator{Href(href), api}
}

func ( api * API ) InstanceCombinationLocator ( href string ) * InstanceCombinationLocator { return & InstanceCombinationLocator { Href ( href ) , api } }

// InstanceCombinationLocator builds a locator from the given href.

InstanceCombinationLocator builds a locator from the given href .


func (api *API) InstanceMetricLocator(href string) *InstanceMetricLocator {
	return &InstanceMetricLocator{Href(href), api}
}

func ( api * API ) InstanceMetricLocator ( href string ) * InstanceMetricLocator { return & InstanceMetricLocator { Href ( href ) , api } }

// InstanceMetricLocator builds a locator from the given href.

InstanceMetricLocator builds a locator from the given href .


func (api *API) InstanceUsagePeriodLocator(href string) *InstanceUsagePeriodLocator {
	return &InstanceUsagePeriodLocator{Href(href), api}
}

func ( api * API ) InstanceUsagePeriodLocator ( href string ) * InstanceUsagePeriodLocator { return & InstanceUsagePeriodLocator { Href ( href ) , api } }

// InstanceUsagePeriodLocator builds a locator from the given href.

InstanceUsagePeriodLocator builds a locator from the given href .


func (api *API) PatternLocator(href string) *PatternLocator {
	return &PatternLocator{Href(href), api}
}

func ( api * API ) PatternLocator ( href string ) * PatternLocator { return & PatternLocator { Href ( href ) , api } }

// PatternLocator builds a locator from the given href.

PatternLocator builds a locator from the given href .


func (api *API) ReservedInstanceLocator(href string) *ReservedInstanceLocator {
	return &ReservedInstanceLocator{Href(href), api}
}

func ( api * API ) ReservedInstanceLocator ( href string ) * ReservedInstanceLocator { return & ReservedInstanceLocator { Href ( href ) , api } }

// ReservedInstanceLocator builds a locator from the given href.

ReservedInstanceLocator builds a locator from the given href .


func (api *API) ReservedInstancePurchaseLocator(href string) *ReservedInstancePurchaseLocator {
	return &ReservedInstancePurchaseLocator{Href(href), api}
}

func ( api * API ) ReservedInstancePurchaseLocator ( href string ) * ReservedInstancePurchaseLocator { return & ReservedInstancePurchaseLocator { Href ( href ) , api } }

// ReservedInstancePurchaseLocator builds a locator from the given href.

ReservedInstancePurchaseLocator builds a locator from the given href .


func (api *API) ScenarioLocator(href string) *ScenarioLocator {
	return &ScenarioLocator{Href(href), api}
}

func ( api * API ) ScenarioLocator ( href string ) * ScenarioLocator { return & ScenarioLocator { Href ( href ) , api } }

// ScenarioLocator builds a locator from the given href.

ScenarioLocator builds a locator from the given href .


func (api *API) ScheduledReportLocator(href string) *ScheduledReportLocator {
	return &ScheduledReportLocator{Href(href), api}
}

func ( api * API ) ScheduledReportLocator ( href string ) * ScheduledReportLocator { return & ScheduledReportLocator { Href ( href ) , api } }

// ScheduledReportLocator builds a locator from the given href.

ScheduledReportLocator builds a locator from the given href .


func (api *API) TempInstancePriceLocator(href string) *TempInstancePriceLocator {
	return &TempInstancePriceLocator{Href(href), api}
}

func ( api * API ) TempInstancePriceLocator ( href string ) * TempInstancePriceLocator { return & TempInstancePriceLocator { Href ( href ) , api } }

// TempInstancePriceLocator builds a locator from the given href.

TempInstancePriceLocator builds a locator from the given href .


func (api *API) UserSettingLocator(href string) *UserSettingLocator {
	return &UserSettingLocator{Href(href), api}
}

func ( api * API ) UserSettingLocator ( href string ) * UserSettingLocator { return & UserSettingLocator { Href ( href ) , api } }

// UserSettingLocator builds a locator from the given href.

UserSettingLocator builds a locator from the given href .


func readAllAsync(f io.ReadCloser) (*[]byte, chan struct{}) {
	done := make(chan struct{}, 1) // signal that the read is done
	var buf []byte                 // placeholder buffer for the result
	go func() {
		var err error
		buf, err = ioutil.ReadAll(f)
		if err != nil {
			buf = make([]byte, 0)
		}
		f.Close()
		done <- struct{}{}
	}()
	return &buf, done
}

func
readAllAsync
(
f
io
.
ReadCloser
)
(
*
[
]
byte
,
chan
struct
{
}
)
{
done
:=
make
(
chan
struct
{
}
,
1
)
// signal that the read is done
var
buf
[
]
byte
// placeholder buffer for the result
go
func
(
)
{
var
err
error
buf
,
err
=
ioutil
.
ReadAll
(
f
)
if
err
!=
{
buf
=
make
(
[
]
byte
,
0
)
}
f
.
Close
(
)
done
<-
struct
{
}
{
}
}
(
)
return
&
buf
,
done
}


func extractArg(name string, args []string) (string, []string) {
	var val string
	var newArgs []string
	var skip bool
	for i, a := range args {
		if skip {
			skip = false
			continue
		}
		if strings.Contains(a, "=") {
			elems := strings.SplitN(a, "=", 2)
			if elems[0] == name {
				val = elems[1]
			} else {
				newArgs = append(newArgs, a)
			}
		} else if a == name && len(args) > (i+1) {
			val = args[i+1]
			skip = true
		} else {
			newArgs = append(newArgs, a)
		}
	}
	return val, newArgs
}

func extractArg ( name string , args [ ] string ) ( string , [ ] string ) { var val string var newArgs [ ] string var skip bool for i , a := range args { if skip { skip = false continue } if strings . Contains ( a , " " ) { elems := strings . SplitN ( a , " " , 2 ) if elems [ 0 ] == name { val = elems [ 1 ] } else { newArgs = append ( newArgs , a ) } } else if a == name && len ( args ) > ( i + 1 ) { val = args [ i + 1 ] skip = true } else { newArgs = append ( newArgs , a ) } } return val , newArgs }

// Extract command line argument with given name and return remaining arguments


func write(b []byte) {
	f, err := os.OpenFile(output, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		fail("failed to open output file")
	}
	f.Write(b)
	f.WriteString("\n")
	f.Close()
}

func write ( b [ ] byte ) { f , err := os . OpenFile ( output , os . O_APPEND | os . O_WRONLY | os . O_CREATE , 0644 ) if err != nil { fail ( " " ) } f . Write ( b ) f . WriteString ( " \n " ) f . Close ( ) }

// Helper function that appends a string to output file


func (api *API) AppliedPolicyLocator(href string) *AppliedPolicyLocator {
	return &AppliedPolicyLocator{Href(href), api}
}

func ( api * API ) AppliedPolicyLocator ( href string ) * AppliedPolicyLocator { return & AppliedPolicyLocator { Href ( href ) , api } }

// AppliedPolicyLocator builds a locator from the given href.

AppliedPolicyLocator builds a locator from the given href .


func (api *API) ApprovalLocator(href string) *ApprovalLocator {
	return &ApprovalLocator{Href(href), api}
}

func ( api * API ) ApprovalLocator ( href string ) * ApprovalLocator { return & ApprovalLocator { Href ( href ) , api } }

// ApprovalLocator builds a locator from the given href.

ApprovalLocator builds a locator from the given href .


func (api *API) IncidentLocator(href string) *IncidentLocator {
	return &IncidentLocator{Href(href), api}
}

func ( api * API ) IncidentLocator ( href string ) * IncidentLocator { return & IncidentLocator { Href ( href ) , api } }

// IncidentLocator builds a locator from the given href.

IncidentLocator builds a locator from the given href .


func (api *API) PolicyTemplateLocator(href string) *PolicyTemplateLocator {
	return &PolicyTemplateLocator{Href(href), api}
}

func ( api * API ) PolicyTemplateLocator ( href string ) * PolicyTemplateLocator { return & PolicyTemplateLocator { Href ( href ) , api } }

// PolicyTemplateLocator builds a locator from the given href.

PolicyTemplateLocator builds a locator from the given href .


func (api *API) PublishedTemplateLocator(href string) *PublishedTemplateLocator {
	return &PublishedTemplateLocator{Href(href), api}
}

func ( api * API ) PublishedTemplateLocator ( href string ) * PublishedTemplateLocator { return & PublishedTemplateLocator { Href ( href ) , api } }

// PublishedTemplateLocator builds a locator from the given href.

PublishedTemplateLocator builds a locator from the given href .


func (api *API) DebugCookbookPathLocator(href string) *DebugCookbookPathLocator {
	return &DebugCookbookPathLocator{Href(href), api}
}

func ( api * API ) DebugCookbookPathLocator ( href string ) * DebugCookbookPathLocator { return & DebugCookbookPathLocator { Href ( href ) , api } }

// DebugCookbookPathLocator builds a locator from the given href.

DebugCookbookPathLocator builds a locator from the given href .


func (api *API) DockerControlLocator(href string) *DockerControlLocator {
	return &DockerControlLocator{Href(href), api}
}

func ( api * API ) DockerControlLocator ( href string ) * DockerControlLocator { return & DockerControlLocator { Href ( href ) , api } }

// DockerControlLocator builds a locator from the given href.

DockerControlLocator builds a locator from the given href .


func (api *API) EnvLocator(href string) *EnvLocator {
	return &EnvLocator{Href(href), api}
}

func ( api * API ) EnvLocator ( href string ) * EnvLocator { return & EnvLocator { Href ( href ) , api } }

// EnvLocator builds a locator from the given href.

EnvLocator builds a locator from the given href .


func (api *API) LoginControlLocator(href string) *LoginControlLocator {
	return &LoginControlLocator{Href(href), api}
}

func ( api * API ) LoginControlLocator ( href string ) * LoginControlLocator { return & LoginControlLocator { Href ( href ) , api } }

// LoginControlLocator builds a locator from the given href.

LoginControlLocator builds a locator from the given href .


func (api *API) ProcLocator(href string) *ProcLocator {
	return &ProcLocator{Href(href), api}
}

func ( api * API ) ProcLocator ( href string ) * ProcLocator { return & ProcLocator { Href ( href ) , api } }

// ProcLocator builds a locator from the given href.

ProcLocator builds a locator from the given href .


func (api *API) Rl10Locator(href string) *Rl10Locator {
	return &Rl10Locator{Href(href), api}
}

func ( api * API ) Rl10Locator ( href string ) * Rl10Locator { return & Rl10Locator { Href ( href ) , api } }

// Rl10Locator builds a locator from the given href.

Rl10Locator builds a locator from the given href .


func (api *API) TSSLocator(href string) *TSSLocator {
	return &TSSLocator{Href(href), api}
}

func ( api * API ) TSSLocator ( href string ) * TSSLocator { return & TSSLocator { Href ( href ) , api } }

// TSSLocator builds a locator from the given href.

TSSLocator builds a locator from the given href .


func (api *API) TSSControlLocator(href string) *TSSControlLocator {
	return &TSSControlLocator{Href(href), api}
}

func ( api * API ) TSSControlLocator ( href string ) * TSSControlLocator { return & TSSControlLocator { Href ( href ) , api } }

// TSSControlLocator builds a locator from the given href.

TSSControlLocator builds a locator from the given href .


func (api *API) TSSPluginLocator(href string) *TSSPluginLocator {
	return &TSSPluginLocator{Href(href), api}
}

func ( api * API ) TSSPluginLocator ( href string ) * TSSPluginLocator { return & TSSPluginLocator { Href ( href ) , api } }

// TSSPluginLocator builds a locator from the given href.

TSSPluginLocator builds a locator from the given href .


func NewAngularWriter() (*AngularWriter, error) {
	funcMap := template.FuncMap{
		"comment":     comment,
		"commandLine": commandLine,
		"path":        path,
		"mandatory":   mandatory,
	}
	resourceT, err := template.New("resource-client").Funcs(funcMap).Parse(angularTmpl)
	if err != nil {
		return nil, err
	}
	return &AngularWriter{
		angularTmpl: resourceT,
	}, nil
}

func NewAngularWriter ( ) ( * AngularWriter , error ) { funcMap := template . FuncMap { " " : comment , " " : commandLine , " " : path , " " : mandatory , } resourceT , err := template . New ( " " ) . Funcs ( funcMap ) . Parse ( angularTmpl ) if err != nil { return nil , err } return & AngularWriter { angularTmpl : resourceT , } , nil }

// NewAngularWriter creates a new code writer that generates angular.js types.

NewAngularWriter creates a new code writer that generates angular . js types .


func (c *AngularWriter) WriteResource(resource *gen.Resource, w io.Writer) error {
	return c.angularTmpl.Execute(w, resource)
}

func ( c * AngularWriter ) WriteResource ( resource * gen . Resource , w io . Writer ) error { return c . angularTmpl . Execute ( w , resource ) }

// WriteResource writes the code for a resource.

WriteResource writes the code for a resource .


func path(a *gen.Action) string {
	pattern := a.PathPatterns[0]
	vars := pattern.Variables
	ivars := make([]interface{}, len(vars))
	for i, v := range vars {
		ivars[i] = interface{}(":" + v)
	}
	return fmt.Sprintf(pattern.Pattern, ivars...)
}

func path ( a * gen . Action ) string { pattern := a . PathPatterns [ 0 ] vars := pattern . Variables ivars := make ( [ ] interface { } , len ( vars ) ) for i , v := range vars { ivars [ i ] = interface { } ( " " + v ) } return fmt . Sprintf ( pattern . Pattern , ivars ... ) }

// Path for given action, for now simplify and take first path in PathPatterns.
// In the future we may want to create one "action" in generated JS per path.

Path for given action for now simplify and take first path in PathPatterns . In the future we may want to create one action in generated JS per path .


func mandatory(a gen.Action, param string) bool {
	for _, p := range a.Params {
		if p.Name == param {
			return p.Mandatory
		}
	}
	panic("praxisgen bug: Unknown param " + param + " for action " + a.Name)
}

func mandatory ( a gen . Action , param string ) bool { for _ , p := range a . Params { if p . Name == param { return p . Mandatory } } panic ( " " + param + " " + a . Name ) }

// Returns true if parameter with given name is mandatory


func New(host string, auth Authenticator) *API {
	client := httpclient.New()
	if strings.HasPrefix(host, "http://") {
		host = host[7:]
	} else if strings.HasPrefix(host, "https://") {
		host = host[8:]
	}
	a := &API{
		Auth:   auth,
		Host:   host,
		Client: client,
	}
	if auth != nil {
		auth.SetHost(host)
	}
	return a
}

func New ( host string , auth Authenticator ) * API { client := httpclient . New ( ) if strings . HasPrefix ( host , " " ) { host = host [ 7 : ] } else if strings . HasPrefix ( host , " " ) { host = host [ 8 : ] } a := & API { Auth : auth , Host : host , Client : client , } if auth != nil { auth . SetHost ( host ) } return a }

// New returns a API client that uses the given authenticator.
// host may be blank in which case client attempts to resolve it using auth.

New returns a API client that uses the given authenticator . host may be blank in which case client attempts to resolve it using auth .


func FromCommandLine(cmdLine *cmd.CommandLine) (*API, error) {
	var client *API
	ss := strings.HasPrefix(cmdLine.Command, "ss")
	if cmdLine.RL10 {
		var err error
		if client, err = NewRL10(); err != nil {
			return nil, err
		}
	} else if cmdLine.OAuthToken != "" {
		auth := NewOAuthAuthenticator(cmdLine.OAuthToken, cmdLine.Account)
		if ss {
			auth = NewSSAuthenticator(auth, cmdLine.Account)
		}
		client = New(cmdLine.Host, auth)
	} else if cmdLine.OAuthAccessToken != "" {
		auth := NewTokenAuthenticator(cmdLine.OAuthAccessToken, cmdLine.Account)
		if ss {
			auth = NewSSAuthenticator(auth, cmdLine.Account)
		}
		client = New(cmdLine.Host, auth)
	} else if cmdLine.APIToken != "" {
		auth := NewInstanceAuthenticator(cmdLine.APIToken, cmdLine.Account)
		if ss {
			auth = NewSSAuthenticator(auth, cmdLine.Account)
		}
		client = New(cmdLine.Host, auth)
	} else if cmdLine.Username != "" && cmdLine.Password != "" {
		auth := NewBasicAuthenticator(cmdLine.Username, cmdLine.Password, cmdLine.Account)
		if ss {
			auth = NewSSAuthenticator(auth, cmdLine.Account)
		}
		client = New(cmdLine.Host, auth)
	} else {
		// No auth, used by tests
		client = New(cmdLine.Host, nil)
		httpclient.Insecure = true
	}
	if !cmdLine.ShowHelp && !cmdLine.NoAuth {
		if cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && cmdLine.Username == "" && !cmdLine.RL10 {
			return nil, fmt.Errorf("Missing authentication information, use '--email EMAIL --password PWD', '--token TOKEN' or 'setup'")
		}
		if cmdLine.Verbose || cmdLine.Dump == "debug" {
			httpclient.DumpFormat = httpclient.Debug
		}
		if cmdLine.Dump == "json" {
			httpclient.DumpFormat = httpclient.JSON
		}
		if cmdLine.Dump == "record" {
			httpclient.DumpFormat = httpclient.JSON | httpclient.Record
		}
		if cmdLine.Verbose {
			httpclient.DumpFormat |= httpclient.Verbose
		}
		client.FetchLocationResource = cmdLine.FetchResource
	}
	return client, nil
}

func
FromCommandLine
(
cmdLine
*
cmd
.
CommandLine
)
(
*
API
,
error
)
{
var
client
*
API
ss
:=
strings
.
HasPrefix
(
cmdLine
.
Command
,
"
"
)
if
cmdLine
.
RL10
{
var
err
error
if
client
,
err
=
NewRL10
(
)
;
err
!=
{
return
,
err
}
}
else
if
cmdLine
.
OAuthToken
!=
"
"
{
auth
:=
NewOAuthAuthenticator
(
cmdLine
.
OAuthToken
,
cmdLine
.
Account
)
if
ss
{
auth
=
NewSSAuthenticator
(
auth
,
cmdLine
.
Account
)
}
client
=
New
(
cmdLine
.
Host
,
auth
)
}
else
if
cmdLine
.
OAuthAccessToken
!=
"
"
{
auth
:=
NewTokenAuthenticator
(
cmdLine
.
OAuthAccessToken
,
cmdLine
.
Account
)
if
ss
{
auth
=
NewSSAuthenticator
(
auth
,
cmdLine
.
Account
)
}
client
=
New
(
cmdLine
.
Host
,
auth
)
}
else
if
cmdLine
.
APIToken
!=
"
"
{
auth
:=
NewInstanceAuthenticator
(
cmdLine
.
APIToken
,
cmdLine
.
Account
)
if
ss
{
auth
=
NewSSAuthenticator
(
auth
,
cmdLine
.
Account
)
}
client
=
New
(
cmdLine
.
Host
,
auth
)
}
else
if
cmdLine
.
Username
!=
"
"
&&
cmdLine
.
Password
!=
"
"
{
auth
:=
NewBasicAuthenticator
(
cmdLine
.
Username
,
cmdLine
.
Password
,
cmdLine
.
Account
)
if
ss
{
auth
=
NewSSAuthenticator
(
auth
,
cmdLine
.
Account
)
}
client
=
New
(
cmdLine
.
Host
,
auth
)
}
else
{
// No auth, used by tests
client
=
New
(
cmdLine
.
Host
,
)
httpclient
.
Insecure
=
true
}
if
!
cmdLine
.
ShowHelp
&&
!
cmdLine
.
NoAuth
{
if
cmdLine
.
OAuthToken
==
"
"
&&
cmdLine
.
OAuthAccessToken
==
"
"
&&
cmdLine
.
APIToken
==
"
"
&&
cmdLine
.
Username
==
"
"
&&
!
cmdLine
.
RL10
{
return
,
fmt
.
Errorf
(
"
"
)
}
if
cmdLine
.
Verbose
||
cmdLine
.
Dump
==
"
"
{
httpclient
.
DumpFormat
=
httpclient
.
Debug
}
if
cmdLine
.
Dump
==
"
"
{
httpclient
.
DumpFormat
=
httpclient
.
JSON
}
if
cmdLine
.
Dump
==
"
"
{
httpclient
.
DumpFormat
=
httpclient
.
JSON
|
httpclient
.
Record
}
if
cmdLine
.
Verbose
{
httpclient
.
DumpFormat
|=
httpclient
.
Verbose
}
client
.
FetchLocationResource
=
cmdLine
.
FetchResource
}
return
client
,
}

// FromCommandLine builds an API client from the command line.

FromCommandLine builds an API client from the command line .


func (a *API) CanAuthenticate() error {
	res := a.Auth.CanAuthenticate(a.Host)
	return res
}

func ( a * API ) CanAuthenticate ( ) error { res := a . Auth . CanAuthenticate ( a . Host ) return res }

// CanAuthenticate makes a test authenticated request to the RightScale API and returns an error
// if it fails.

CanAuthenticate makes a test authenticated request to the RightScale API and returns an error if it fails .


func Encrypt(text string) (string, error) {
	bytes := []byte(text)
	key := seekret()
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	b := encodeBase64(bytes)
	ciphertext := make([]byte, aes.BlockSize+len(b))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return "", err
	}
	cfb := cipher.NewCFBEncrypter(block, iv)
	cfb.XORKeyStream(ciphertext[aes.BlockSize:], b)
	return string(encodeBase64(ciphertext)), nil
}

func Encrypt ( text string ) ( string , error ) { bytes := [ ] byte ( text ) key := seekret ( ) block , err := aes . NewCipher ( key ) if err != nil { return " " , err } b := encodeBase64 ( bytes ) ciphertext := make ( [ ] byte , aes . BlockSize + len ( b ) ) iv := ciphertext [ : aes . BlockSize ] if _ , err := io . ReadFull ( rand . Reader , iv ) ; err != nil { return " " , err } cfb := cipher . NewCFBEncrypter ( block , iv ) cfb . XORKeyStream ( ciphertext [ aes . BlockSize : ] , b ) return string ( encodeBase64 ( ciphertext ) ) , nil }

// Encrypt encrypts the given text with a hard-coded secret. Not truly secure.

Encrypt encrypts the given text with a hard - coded secret . Not truly secure .


func Decrypt(text string) (string, error) {
	if text == "" {
		return "", nil
	}
	key := seekret()
	bytes := decodeBase64([]byte(text))
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", err
	}
	if len(bytes) < aes.BlockSize {
		return "", errors.New("ciphertext too short")
	}
	iv := bytes[:aes.BlockSize]
	bytes = bytes[aes.BlockSize:]
	cfb := cipher.NewCFBDecrypter(block, iv)
	cfb.XORKeyStream(bytes, bytes)
	return string(decodeBase64(bytes)), nil
}

func Decrypt ( text string ) ( string , error ) { if text == " " { return " " , nil } key := seekret ( ) bytes := decodeBase64 ( [ ] byte ( text ) ) block , err := aes . NewCipher ( key ) if err != nil { return " " , err } if len ( bytes ) < aes . BlockSize { return " " , errors . New ( " " ) } iv := bytes [ : aes . BlockSize ] bytes = bytes [ aes . BlockSize : ] cfb := cipher . NewCFBDecrypter ( block , iv ) cfb . XORKeyStream ( bytes , bytes ) return string ( decodeBase64 ( bytes ) ) , nil }

// Decrypt decrypts the given encrypted string using the hard-coded secret.

Decrypt decrypts the given encrypted string using the hard - coded secret .


func (a *APIAnalyzer) guessType(ec EvalCtx, d *Definition, refID string) string {
	// First get the type name and and view from the swagger reference definition
	// name -- are a few cases where that's the only place that has the view
	if t, ok := a.TypeOverrides[refID]; ok {
		return t
	}
	var name, view string
	if strings.Contains(refID, "RequestBody") {
		bits := strings.Split(refID, "RequestBody")
		name = bits[0]
		if len(bits) > 1 {
			view = strings.ToLower(bits[1])
		}
	} else if strings.Contains(refID, "ResponseBody") {
		bits := strings.Split(refID, "ResponseBody")
		name = bits[0]
		if len(bits) > 1 {
			view = strings.ToLower(bits[1])
		}
	} else {
		name = refID
	}

	// Now try and get it from the media type -- this is preferred if its set.
	if mt := mediaType(d.Title); mt != "" {
		if strings.Contains(mt, "application") {
			bits := strings.Split(mt, ".")
			name := bits[len(bits)-1]
			attrs := mediaTypeAttrs(d.Title)
			if attrs["type"] != "" {
				name += "_" + attrs["type"]
			}
			if attrs["view"] != "" && attrs["view"] != "default" {
				name += "_" + attrs["view"]
			} else if view != "" {
				name += "_" + view
			}
			dbg("DEBUG media type refID:%#v title:%#v name:%#v view:%#v -> type:%#v\n", refID, d.Title, name, view, name)
			return toTypeName(name)
		} else if strings.Contains(mt, "text/") {
			return "string"
		} else {
			fail("Don't know how to handle media type %s", mt)
		}
	}
	if view != "" {
		return name + "_" + view
	}

	return name
}

// guessType tries to guess the resource name based on the definition and service.
// This info is not stored in the swagger. TBD manual overrides if needed.

guessType tries to guess the resource name based on the definition and service . This info is not stored in the swagger . TBD manual overrides if needed .


func (a *APIAnalyzer) addType(ec EvalCtx, dt *gen.ObjectDataType, r Ref) {
	a.api.NeedJSON = true
	if a.refByType[dt.TypeName] == r.ID() {
		return
	}

	if other, ok := a.api.Types[dt.TypeName]; ok {
		if !ec.IsResult {
			// If its an input parameter, fix the collision by amending this types name
			dt.TypeName += "Param"
			if a.refByType[dt.TypeName] == r.ID() {
				return
			}
		}
		oldFields := []string{}
		newFields := []string{}
		for _, f := range other.Fields {
			oldFields = append(oldFields, f.Name)
		}
		for _, f := range dt.Fields {
			newFields = append(newFields, f.Name)
		}
		use := "Old"
		if len(newFields) > len(oldFields) {
			use = "New"
		}
		if strings.Join(oldFields, ",") != strings.Join(newFields, ",") {
			warn("Warning: Type collision when adding new type %s!\n  New: id %s fields %v\n  Old: id %s fields %v\n  Using %s, which has more fields\n",
				dt.TypeName, r.ID(), newFields, a.refByType[dt.TypeName], oldFields, use)
		}
		if use == "Old" {
			return
		}
	}
	dbg("DEBUG NEW TYPE %s\n", prettify(dt))
	a.refByType[dt.TypeName] = r.ID()
	a.api.Types[dt.TypeName] = dt
}

// addType conditionally adds a new type, trying its best to avoid type
// collisions. This is the downside of swagger 2 vs swagger 3. For swagger 2
// if you the same type like "User" returned in multiple places, each have to
// create their own definition in the swagger "definitions" section for goa
// v2. So they'll be X copies of identical definition for a User struct lets
// say. This tries to collapse those things down into one return type struct.

addType conditionally adds a new type trying its best to avoid type collisions . This is the downside of swagger 2 vs swagger 3 . For swagger 2 if you the same type like User returned in multiple places each have to create their own definition in the swagger definitions section for goa v2 . So they ll be X copies of identical definition for a User struct lets say . This tries to collapse those things down into one return type struct .


func extractCmdLineParams(a *gen.ActionParam, root string, seen map[string]*[]*gen.ActionParam, parentNotMandatory bool) []*gen.ActionParam {
	switch t := a.Type.(type) {
	case *gen.BasicDataType, *gen.EnumerableDataType, *gen.UploadDataType:
		dup := gen.ActionParam{
			Name:        a.Name,
			QueryName:   root,
			Description: a.Description,
			VarName:     a.VarName,
			Location:    a.Location,
			Type:        a.Type,
			Mandatory:   a.Mandatory && !parentNotMandatory, // yay for double negations!
			NonBlank:    a.NonBlank,
			Regexp:      a.Regexp,
			ValidValues: a.ValidValues,
			Min:         a.Min,
			Max:         a.Max,
		}
		return []*gen.ActionParam{&dup}
	case *gen.ArrayDataType:
		p := t.ElemType
		eq, ok := seen[p.Name]
		if !ok {
			eq = &[]*gen.ActionParam{}
			seen[p.Name] = eq
			*eq = extractCmdLineParams(p, root+"[]", seen, parentNotMandatory || !a.Mandatory)
		}
		return *eq
	case *gen.ObjectDataType:
		params := []*gen.ActionParam{}
		for _, f := range t.Fields {
			eq, ok := seen[f.Name]
			if !ok {
				eq = &[]*gen.ActionParam{}
				seen[f.Name] = eq
				*eq = extractCmdLineParams(f, fmt.Sprintf("%s[%s]", root, f.Name), seen, parentNotMandatory || !a.Mandatory)
			}
			params = append(params, *eq...)
		}
		return params
	}
	return nil
}

func
extractCmdLineParams
(
a
*
gen
.
ActionParam
,
root
string
,
seen
map
[
string
]
*
[
]
*
gen
.
ActionParam
,
parentNotMandatory
bool
)
[
]
*
gen
.
ActionParam
{
switch
t
:=
a
.
Type
.
(
type
)
{
case
*
gen
.
BasicDataType
,
*
gen
.
EnumerableDataType
,
*
gen
.
UploadDataType
:
dup
:=
gen
.
ActionParam
{
Name
:
a
.
Name
,
QueryName
:
root
,
Description
:
a
.
Description
,
VarName
:
a
.
VarName
,
Location
:
a
.
Location
,
Type
:
a
.
Type
,
Mandatory
:
a
.
Mandatory
&&
!
parentNotMandatory
,
// yay for double negations!
NonBlank
:
a
.
NonBlank
,
Regexp
:
a
.
Regexp
,
ValidValues
:
a
.
ValidValues
,
Min
:
a
.
Min
,
Max
:
a
.
Max
,
}
return
[
]
*
gen
.
ActionParam
{
&
dup
}
case
*
gen
.
ArrayDataType
:
p
:=
t
.
ElemType
eq
,
ok
:=
seen
[
p
.
Name
]
if
!
ok
{
eq
=
&
[
]
*
gen
.
ActionParam
{
}
seen
[
p
.
Name
]
=
eq
*
eq
=
extractCmdLineParams
(
p
,
root
+
"
"
,
seen
,
parentNotMandatory
||
!
a
.
Mandatory
)
}
return
*
eq
case
*
gen
.
ObjectDataType
:
params
:=
[
]
*
gen
.
ActionParam
{
}
for
_
,
f
:=
range
t
.
Fields
{
eq
,
ok
:=
seen
[
f
.
Name
]
if
!
ok
{
eq
=
&
[
]
*
gen
.
ActionParam
{
}
seen
[
f
.
Name
]
=
eq
*
eq
=
extractCmdLineParams
(
f
,
fmt
.
Sprintf
(
"
"
,
root
,
f
.
Name
)
,
seen
,
parentNotMandatory
||
!
a
.
Mandatory
)
}
params
=
append
(
params
,
*
eq
...
)
}
return
params
}
return
}

// extractCmdLineParams generates flags for the command line


func NewMetadataWriter() (*MetadataWriter, error) {
	funcMap := template.FuncMap{
		"comment":         comment,
		"join":            strings.Join,
		"commandLine":     commandLine,
		"toStringArray":   toStringArray,
		"flagType":        flagType,
		"location":        location,
		"escapeBackticks": escapeBackticks,
	}
	headerT, err := template.New("header-metadata").Funcs(funcMap).Parse(headerMetadataTmpl)
	if err != nil {
		return nil, err
	}
	resourceT, err := template.New("resource-metadata").Funcs(funcMap).Parse(resourceMetadataTmpl)
	if err != nil {
		return nil, err
	}
	return &MetadataWriter{
		headerTmpl:   headerT,
		resourceTmpl: resourceT,
	}, nil
}

func NewMetadataWriter ( ) ( * MetadataWriter , error ) { funcMap := template . FuncMap { " " : comment , " " : strings . Join , " " : commandLine , " " : toStringArray , " " : flagType , " " : location , " " : escapeBackticks , } headerT , err := template . New ( " " ) . Funcs ( funcMap ) . Parse ( headerMetadataTmpl ) if err != nil { return nil , err } resourceT , err := template . New ( " " ) . Funcs ( funcMap ) . Parse ( resourceMetadataTmpl ) if err != nil { return nil , err } return & MetadataWriter { headerTmpl : headerT , resourceTmpl : resourceT , } , nil }

// NewMetadataWriter creates a new writer that generates metadata data structures.

NewMetadataWriter creates a new writer that generates metadata data structures .


func (c *MetadataWriter) WriteHeader(pkg string, w io.Writer) error {
	return c.headerTmpl.Execute(w, pkg)
}

func ( c * MetadataWriter ) WriteHeader ( pkg string , w io . Writer ) error { return c . headerTmpl . Execute ( w , pkg ) }

// WriteHeader writes the generic header text.

WriteHeader writes the generic header text .


func (c *MetadataWriter) WriteMetadata(d *gen.APIDescriptor, w io.Writer) error {
	resources := make([]*gen.Resource, len(d.ResourceNames))
	for i, n := range d.ResourceNames {
		resources[i] = d.Resources[n]
	}
	return c.resourceTmpl.Execute(w, resources)
}

func ( c * MetadataWriter ) WriteMetadata ( d * gen . APIDescriptor , w io . Writer ) error { resources := make ( [ ] * gen . Resource , len ( d . ResourceNames ) ) for i , n := range d . ResourceNames { resources [ i ] = d . Resources [ n ] } return c . resourceTmpl . Execute ( w , resources ) }

// WriteMetadata writes the data structures that describe the API resources and actions.

WriteMetadata writes the data structures that describe the API resources and actions .


func location(p *gen.ActionParam) string {
	switch p.Location {
	case gen.PathParam:
		return "metadata.PathParam"
	case gen.QueryParam:
		return "metadata.QueryParam"
	case gen.PayloadParam:
		return "metadata.PayloadParam"
	default:
		return ""
	}
}

func location ( p * gen . ActionParam ) string { switch p . Location { case gen . PathParam : return " " case gen . QueryParam : return " " case gen . PayloadParam : return " " default : return " " } }

// Return code corresponding to param location


func New(host string, auth rsapi.Authenticator) *API {
	return fromAPI(rsapi.New(host, auth))
}

func New ( host string , auth rsapi . Authenticator ) * API { return fromAPI ( rsapi . New ( host , auth ) ) }

// New returns a client that uses RL10 authentication.
// accountId, host and auth arguments are not used.
// If no HTTP client is specified then the default client is used.

New returns a client that uses RL10 authentication . accountId host and auth arguments are not used . If no HTTP client is specified then the default client is used .


func fromAPI(api *rsapi.API) *API {
	api.Metadata = GenMetadata
	return &API{api}
}

func fromAPI ( api * rsapi . API ) * API { api . Metadata = GenMetadata return & API { api } }


func (a *API) BuildRequest(resource, action, href string, params rsapi.APIParams) (*http.Request, error) {
	// First lookup metadata
	res, ok := GenMetadata[resource]
	if !ok {
		return nil, fmt.Errorf("No resource with name '%s'", resource)
	}
	act := res.GetAction(action)
	if act == nil {
		return nil, fmt.Errorf("No action with name '%s' on %s", action, resource)
	}

	// Now lookup action request HTTP method, url, params and payload.
	vars, err := res.ExtractVariables(href)
	if err != nil {
		return nil, err
	}
	actionURL, err := act.URL(vars)
	if err != nil {
		return nil, err
	}
	_, queryParams := rsapi.IdentifyParams(act, params)
	return a.BuildHTTPRequest("GET", actionURL.Path, "1.6", queryParams, nil)
}

// BuildRequest builds a HTTP request from a resource name and href and an action name and
// parameters.
// It is intended for generic clients that need to consume APIs in a generic maner.
// The method builds an HTTP request that can be fed to PerformRequest.

BuildRequest builds a HTTP request from a resource name and href and an action name and parameters . It is intended for generic clients that need to consume APIs in a generic maner . The method builds an HTTP request that can be fed to PerformRequest .


func setupMetadata() (result map[string]*metadata.Resource) {
	result = make(map[string]*metadata.Resource)
	for n, r := range cac.GenMetadata {
		result[n] = r
	}
	return
}

func setupMetadata ( ) ( result map [ string ] * metadata . Resource ) { result = make ( map [ string ] * metadata . Resource ) for n , r := range cac . GenMetadata { result [ n ] = r } return }

// Initialize GenMetadata from each CA API generated metadata


func NewDisplayer(resp *http.Response) (*Displayer, error) {
	defer resp.Body.Close()
	js, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("Failed to read response (%s)", err)
	}
	disp := Displayer{response: resp, body: string(js)}
	if len(js) > 2 {
		err = json.Unmarshal(js, &disp.RawOutput)
		if err != nil {
			disp.RawOutput = string(js)
		}
	}
	return &disp, nil
}

func NewDisplayer ( resp * http . Response ) ( * Displayer , error ) { defer resp . Body . Close ( ) js , err := ioutil . ReadAll ( resp . Body ) if err != nil { return nil , fmt . Errorf ( " " , err ) } disp := Displayer { response : resp , body : string ( js ) } if len ( js ) > 2 { err = json . Unmarshal ( js , & disp . RawOutput ) if err != nil { disp . RawOutput = string ( js ) } } return & disp , nil }

// NewDisplayer creates a new displayer using the response body.

NewDisplayer creates a new displayer using the response body .


func (d *Displayer) ApplySingleExtract(extract string) error {
	if err := d.ApplyExtract(extract, true); err != nil {
		return err
	}
	outputs := d.RawOutput.([]interface{})
	if len(outputs) != 1 {
		d.RawOutput = nil
		return fmt.Errorf("JSON selector '%s' returned %d instead of one value",
			extract, len(outputs))
	}
	if len(outputs) == 0 {
		d.RawOutput = ""
	} else {
		switch v := outputs[0].(type) {
		case nil:
			d.RawOutput = ""
		case float64, bool:
			d.RawOutput = fmt.Sprint(v)
		case string:
			d.RawOutput = v
		default:
			d.RawOutput = v
		}
		d.RawOutput = outputs[0]
	}
	return nil
}

func ( d * Displayer ) ApplySingleExtract ( extract string ) error { if err := d . ApplyExtract ( extract , true ) ; err != nil { return err } outputs := d . RawOutput . ( [ ] interface { } ) if len ( outputs ) != 1 { d . RawOutput = nil return fmt . Errorf ( " " , extract , len ( outputs ) ) } if len ( outputs ) == 0 { d . RawOutput = " " } else { switch v := outputs [ 0 ] . ( type ) { case nil : d . RawOutput = " " case float64 , bool : d . RawOutput = fmt . Sprint ( v ) case string : d . RawOutput = v default : d . RawOutput = v } d . RawOutput = outputs [ 0 ] } return nil }

// ApplySingleExtract applies the given JSON selector and returns the results.
// It's an error if the selector yields more than one value.

ApplySingleExtract applies the given JSON selector and returns the results . It s an error if the selector yields more than one value .


func (d *Displayer) ApplyExtract(selector string, js bool) error {
	parser, err := jsonselect.CreateParserFromString(d.body)
	if err != nil {
		return fmt.Errorf("Failed to load response JSON: %s, JSON was:\n%s", err, d.body)
	}
	outputs, err := parser.GetValues(selector)
	if !js {
		out := ""
		for _, o := range outputs {
			b, _ := json.Marshal(o)
			out += string(b) + "\n"
		}
		d.RawOutput = out
	} else {
		d.RawOutput = outputs
	}
	if err != nil {
		return fmt.Errorf("Failed to apply JSON selector '%s' to response: %s, JSON was:\n%s",
			selector, err, d.body)
	}
	return nil
}

func ( d * Displayer ) ApplyExtract ( selector string , js bool ) error { parser , err := jsonselect . CreateParserFromString ( d . body ) if err != nil { return fmt . Errorf ( " \n " , err , d . body ) } outputs , err := parser . GetValues ( selector ) if ! js { out := " " for _ , o := range outputs { b , _ := json . Marshal ( o ) out += string ( b ) + " \n " } d . RawOutput = out } else { d . RawOutput = outputs } if err != nil { return fmt . Errorf ( " \n " , selector , err , d . body ) } return nil }


func (d *Displayer) ApplyHeaderExtract(header string) error {
	d.RawOutput = d.response.Header.Get(header)
	if d.RawOutput == "" {
		return fmt.Errorf("Response does not contain the '%s' header", header)
	}
	return nil
}

func ( d * Displayer ) ApplyHeaderExtract ( header string ) error { d . RawOutput = d . response . Header . Get ( header ) if d . RawOutput == " " { return fmt . Errorf ( " " , header ) } return nil }

// ApplyHeaderExtract reads the value of the given header.

ApplyHeaderExtract reads the value of the given header .


func (d *Displayer) Output() string {
	output := d.RawOutput
	if output == nil {
		return ""
	}
	if outputStr, ok := d.RawOutput.(string); ok {
		suffix := ""
		if d.prettify {
			suffix = "\n"
		}
		return outputStr + suffix
	}
	var out string
	var err error
	if d.prettify {
		var b []byte
		b, err = json.MarshalIndent(output, "", "    ")
		if err == nil {
			out = string(b) + "\n"
		}
	} else {
		var b []byte
		b, err = json.Marshal(output)
		out = string(b)
	}
	if err != nil {
		fm := "%v"
		if d.prettify {
			fm += "\n"
		}
		return fmt.Sprintf(fm, output)
	}
	return out
}

func ( d * Displayer ) Output ( ) string { output := d . RawOutput if output == nil { return " " } if outputStr , ok := d . RawOutput . ( string ) ; ok { suffix := " " if d . prettify { suffix = " \n " } return outputStr + suffix } var out string var err error if d . prettify { var b [ ] byte b , err = json . MarshalIndent ( output , " " , " " ) if err == nil { out = string ( b ) + " \n " } } else { var b [ ] byte b , err = json . Marshal ( output ) out = string ( b ) } if err != nil { fm := " " if d . prettify { fm += " \n " } return fmt . Sprintf ( fm , output ) } return out }


func NewAPIAnalyzer(resources map[string]interface{}, attributeTypes map[string]string) *APIAnalyzer {
	return &APIAnalyzer{
		rawResources:   resources,
		attributeTypes: attributeTypes,
		rawTypes:       make(map[string][]*gen.ObjectDataType),
	}
}

func NewAPIAnalyzer ( resources map [ string ] interface { } , attributeTypes map [ string ] string ) * APIAnalyzer { return & APIAnalyzer { rawResources : resources , attributeTypes : attributeTypes , rawTypes : make ( map [ string ] [ ] * gen . ObjectDataType ) , } }

// NewAPIAnalyzer is the factory method for the API analyzer


func (a *APIAnalyzer) Analyze() *gen.APIDescriptor {
	a.AnalyzeAliases()
	var descriptor = &gen.APIDescriptor{
		Resources: make(map[string]*gen.Resource),
		Types:     make(map[string]*gen.ObjectDataType),
	}
	var rawResourceNames = make([]string, len(a.rawResources))
	var idx = 0
	for n := range a.rawResources {
		rawResourceNames[idx] = n
		idx++
	}
	sort.Strings(rawResourceNames)
	for _, name := range rawResourceNames {
		var resource = a.rawResources[name]
		a.AnalyzeResource(name, resource, descriptor)
	}
	descriptor.FinalizeTypeNames(a.rawTypes)
	return descriptor
}

func ( a * APIAnalyzer ) Analyze ( ) * gen . APIDescriptor { a . AnalyzeAliases ( ) var descriptor = & gen . APIDescriptor { Resources : make ( map [ string ] * gen . Resource ) , Types : make ( map [ string ] * gen . ObjectDataType ) , } var rawResourceNames = make ( [ ] string , len ( a . rawResources ) ) var idx = 0 for n := range a . rawResources { rawResourceNames [ idx ] = n idx ++ } sort . Strings ( rawResourceNames ) for _ , name := range rawResourceNames { var resource = a . rawResources [ name ] a . AnalyzeResource ( name , resource , descriptor ) } descriptor . FinalizeTypeNames ( a . rawTypes ) return descriptor }

// Analyze iterate through all resources and initializes the Resources and ParamTypes fields of
// the APIAnalyzer struct accordingly.

Analyze iterate through all resources and initializes the Resources and ParamTypes fields of the APIAnalyzer struct accordingly .


func (a *APIAnalyzer) AnalyzeAliases() {
	for from, to := range aliases {
		splits := strings.SplitN(from, "#", 2)
		fromResName := splits[0]
		fromActionName := splits[1]
		splits = strings.SplitN(to, "#", 2)
		toResName := splits[0]
		toActionName := splits[1]

		fromRes := a.rawResources[fromResName]
		fromAct := fromRes.(map[string]interface{})["methods"].(map[string]interface{})[fromActionName].(map[string]interface{})

		toRes := a.rawResources[toResName]
		toAct := toRes.(map[string]interface{})["methods"].(map[string]interface{})[toActionName].(map[string]interface{})
		fromAct["parameters"] = toAct["parameters"]
		fromAct["status_code"] = toAct["status_code"]
		fromAct["access_rules"] = toAct["access_rules"]
	}
}

func ( a * APIAnalyzer ) AnalyzeAliases ( ) { for from , to := range aliases { splits := strings . SplitN ( from , " " , 2 ) fromResName := splits [ 0 ] fromActionName := splits [ 1 ] splits = strings . SplitN ( to , " " , 2 ) toResName := splits [ 0 ] toActionName := splits [ 1 ] fromRes := a . rawResources [ fromResName ] fromAct := fromRes . ( map [ string ] interface { } ) [ " " ] . ( map [ string ] interface { } ) [ fromActionName ] . ( map [ string ] interface { } ) toRes := a . rawResources [ toResName ] toAct := toRes . ( map [ string ] interface { } ) [ " " ] . ( map [ string ] interface { } ) [ toActionName ] . ( map [ string ] interface { } ) fromAct [ " " ] = toAct [ " " ] fromAct [ " " ] = toAct [ " " ] fromAct [ " " ] = toAct [ " " ] } }

// AnalyzeAliases goes through the aliases and copies the details from original actions to the
// aliased actions. It skips the route field since we have the routes hard-coded in the
// ParseRoute function.

AnalyzeAliases goes through the aliases and copies the details from original actions to the aliased actions . It skips the route field since we have the routes hard - coded in the ParseRoute function .


func LocatorFunc(attributes []*gen.Attribute, name string) string {
	hasLinks := false
	for _, a := range attributes {
		if a.FieldName == "Links" {
			hasLinks = true
			break
		}
	}
	if !hasLinks {
		return ""
	}
	return `for _, l := range r.Links {
			if l["rel"] == "self" {
				return api.` + name + `Locator(l["href"])
			}
		}
		return nil`
}

`Locator(l["href"])
			}
		}
		return nil`

// LocatorFunc returns the source code for building a locator instance from a resource.

LocatorFunc returns the source code for building a locator instance from a resource .


func ParseRoute(moniker string, routes []string) (pathPatterns []*gen.PathPattern) {
	// :(((( some routes are empty
	var paths []string
	var method string
	switch moniker {
	case "Deployments#servers":
		method, paths = "GET", []string{"/api/deployments/:id/servers"}
	case "ServerArrays#current_instances":
		method, paths = "GET", []string{"/api/server_arrays/:id/current_instances"}
	case "ServerArrays#launch":
		method, paths = "POST", []string{"/api/server_arrays/:id/launch"}
	case "ServerArrays#multi_run_executable":
		method, paths = "POST", []string{"/api/server_arrays/:id/multi_run_executable"}
	case "ServerArrays#multi_terminate":
		method, paths = "POST", []string{"/api/server_arrays/:id/multi_terminate"}
	case "Servers#launch":
		method, paths = "POST", []string{"/api/servers/:id/launch"}
	case "Servers#terminate":
		method, paths = "POST", []string{"/api/servers/:id/terminate"}
	default:
		for _, route := range routes {
			bound := routeRegexp.FindStringIndex(route)
			match := route[0:bound[0]]
			method = strings.TrimRight(match[0:7], " ")
			path := strings.TrimRight(match[7:], " ")
			path = strings.TrimSuffix(path, "(.:format)?")
			if isDeprecated(path) || isCustom(method, path) {
				continue
			}
			paths = append(paths, path)
		}
	}
	pathPatterns = make([]*gen.PathPattern, len(paths))
	for i, p := range paths {
		rx := routeVariablesRegexp.ReplaceAllLiteralString(regexp.QuoteMeta(p), `/([^/]+)`)
		rx = fmt.Sprintf("^%s$", rx)
		pattern := gen.PathPattern{
			HTTPMethod: method,
			Path:       p,
			Pattern:    routeVariablesRegexp.ReplaceAllLiteralString(p, "/%s"),
			Regexp:     rx,
		}
		matches := routeVariablesRegexp.FindAllStringSubmatch(p, -1)
		if len(matches) > 0 {
			pattern.Variables = make([]string, len(matches))
			for i, m := range matches {
				pattern.Variables[i] = m[1]
			}
		}
		pathPatterns[i] = &pattern
	}
	return
}

func
ParseRoute
(
moniker
string
,
routes
[
]
string
)
(
pathPatterns
[
]
*
gen
.
PathPattern
)
{
// :(((( some routes are empty
var
paths
[
]
string
var
method
string
switch
moniker
{
case
"
"
:
method
,
paths
=
"
"
,
[
]
string
{
"
"
}
case
"
"
:
method
,
paths
=
"
"
,
[
]
string
{
"
"
}
case
"
"
:
method
,
paths
=
"
"
,
[
]
string
{
"
"
}
case
"
"
:
method
,
paths
=
"
"
,
[
]
string
{
"
"
}
case
"
"
:
method
,
paths
=
"
"
,
[
]
string
{
"
"
}
case
"
"
:
method
,
paths
=
"
"
,
[
]
string
{
"
"
}
case
"
"
:
method
,
paths
=
"
"
,
[
]
string
{
"
"
}
default
:
for
_
,
route
:=
range
routes
{
bound
:=
routeRegexp
.
FindStringIndex
(
route
)
match
:=
route
[
0
:
bound
[
0
]
]
method
=
strings
.
TrimRight
(
match
[
0
:
7
]
,
"
"
)
path
:=
strings
.
TrimRight
(
match
[
7
:
]
,
"
"
)
path
=
strings
.
TrimSuffix
(
path
,
"
"
)
if
isDeprecated
(
path
)
||
isCustom
(
method
,
path
)
{
continue
}
paths
=
append
(
paths
,
path
)
}
}
pathPatterns
=
make
(
[
]
*
gen
.
PathPattern
,
len
(
paths
)
)
for
i
,
p
:=
range
paths
{
rx
:=
routeVariablesRegexp
.
ReplaceAllLiteralString
(
regexp
.
QuoteMeta
(
p
)
,
`/([^/]+)`
)
rx
=
fmt
.
Sprintf
(
"
"
,
rx
)
pattern
:=
gen
.
PathPattern
{
HTTPMethod
:
method
,
Path
:
p
,
Pattern
:
routeVariablesRegexp
.
ReplaceAllLiteralString
(
p
,
"
"
)
,
Regexp
:
rx
,
}
matches
:=
routeVariablesRegexp
.
FindAllStringSubmatch
(
p
,
1
)
if
len
(
matches
)
>
0
{
pattern
.
Variables
=
make
(
[
]
string
,
len
(
matches
)
)
for
i
,
m
:=
range
matches
{
pattern
.
Variables
[
i
]
=
m
[
1
]
}
}
pathPatterns
[
i
]
=
&
pattern
}
return
}

// ParseRoute parses a API 1.5 route and returns corresponding path patterns.

ParseRoute parses a API 1 . 5 route and returns corresponding path patterns .


func isDeprecated(path string) bool {
	return strings.Contains(path, "/api/session") && !strings.Contains(path, "/api/sessions")
}

func isDeprecated ( path string ) bool { return strings . Contains ( path , " " ) && ! strings . Contains ( path , " " ) }


func isQueryParam(a, n string) bool {
	return n == "view" || n == "filter" || (a == "index" && (n == "with_deleted" || n == "with_inherited" || n == "latest_only" || n == "lineage"))
}

// Heuristic to determine whether given param is a query string param
// For now only consider view and filter...

Heuristic to determine whether given param is a query string param For now only consider view and filter ...


func isPathParam(p string, pathPatterns []*gen.PathPattern) bool {
	for _, pattern := range pathPatterns {
		for _, v := range pattern.Variables {
			if p == v {
				return true
			}
		}
	}
	return false
}

func isPathParam ( p string , pathPatterns [ ] * gen . PathPattern ) bool { for _ , pattern := range pathPatterns { for _ , v := range pattern . Variables { if p == v { return true } } } return false }

// Look in given path patterns to chek whether given parameter name corresponds to a variable
// name.

Look in given path patterns to chek whether given parameter name corresponds to a variable name .


func fetchAuditEntries(client *cm15.API, filterEmail string) ([]*cm15.AuditEntry, error) {
	auditLocator := client.AuditEntryLocator("/api/audit_entries")
	var apiParams = rsapi.APIParams{"filter": []string{"user_email==" + filterEmail}}
	auditEntries, err := auditLocator.Index(
		tomorrow(),  // End date
		"100",       // Limit
		yesterday(), // Start date
		apiParams,
	)
	if err != nil {
		return auditEntries, err
	}
	return auditEntries, nil
}

func
fetchAuditEntries
(
client
*
cm15
.
API
,
filterEmail
string
)
(
[
]
*
cm15
.
AuditEntry
,
error
)
{
auditLocator
:=
client
.
AuditEntryLocator
(
"
"
)
var
apiParams
=
rsapi
.
APIParams
{
"
"
:
[
]
string
{
"
"
+
filterEmail
}
}
auditEntries
,
err
:=
auditLocator
.
Index
(
tomorrow
(
)
,
// End date
"
"
,
// Limit
yesterday
(
)
,
// Start date
apiParams
,
)
if
err
!=
{
return
auditEntries
,
err
}
return
auditEntries
,
}

// Make an API call and fetch the audit entries matching specified criteria


func formatTime(tm time.Time) string {
	year, month, date := tm.Date()
	return time.Date(year, month, date, 0, 0, 0, 0, time.UTC).Format("2006/01/02 15:04:05 -0700")
}

func formatTime ( tm time . Time ) string { year , month , date := tm . Date ( ) return time . Date ( year , month , date , 0 , 0 , 0 , 0 , time . UTC ) . Format ( " " ) }

// Returns time in RightScale API supported format


func printAudits(entries []*cm15.AuditEntry) {
	for _, a := range entries {
		fmt.Printf("[%v] <%v>: %v\n", a.UpdatedAt, a.UserEmail, a.Summary)
	}
}

func printAudits ( entries [ ] * cm15 . AuditEntry ) { for _ , a := range entries { fmt . Printf ( " \n " , a . UpdatedAt , a . UserEmail , a . Summary ) } }


func extractUnique(oldEntries, newEntries []*cm15.AuditEntry) []*cm15.AuditEntry {
	var uniqueEntries = make([]*cm15.AuditEntry, 0)
	var oldHrefs = make([]string, len(oldEntries))
	for i, e := range oldEntries {
		oldHrefs[i] = getHref(e)
	}
	for _, newEntry := range newEntries {
		if !stringInSlice(getHref(newEntry), oldHrefs) {
			uniqueEntries = append(uniqueEntries, newEntry)
		}
	}
	return uniqueEntries
}

func extractUnique ( oldEntries , newEntries [ ] * cm15 . AuditEntry ) [ ] * cm15 . AuditEntry { var uniqueEntries = make ( [ ] * cm15 . AuditEntry , 0 ) var oldHrefs = make ( [ ] string , len ( oldEntries ) ) for i , e := range oldEntries { oldHrefs [ i ] = getHref ( e ) } for _ , newEntry := range newEntries { if ! stringInSlice ( getHref ( newEntry ) , oldHrefs ) { uniqueEntries = append ( uniqueEntries , newEntry ) } } return uniqueEntries }

// Extract unique audit entries from the newly received list by comparing the href of audit entries
// in the old list.

Extract unique audit entries from the newly received list by comparing the href of audit entries in the old list .


func getHref(entry *cm15.AuditEntry) string {
	var href string
	for _, link := range entry.Links {
		if link["rel"] == "self" {
			href = link["href"]
			break
		}
	}
	return href
}

func getHref ( entry * cm15 . AuditEntry ) string { var href string for _ , link := range entry . Links { if link [ " " ] == " " { href = link [ " " ] break } } return href }

// Get the href of an audit entry from the Links attribute by inspecting the self link


func fail(format string, v ...interface{}) {
	if !strings.HasSuffix(format, "\n") {
		format += "\n"
	}
	fmt.Println(fmt.Sprintf(format, v...))
	os.Exit(1)
}

func fail ( format string , v ... interface { } ) { if ! strings . HasSuffix ( format , " \n " ) { format += " \n " } fmt . Println ( fmt . Sprintf ( format , v ... ) ) os . Exit ( 1 ) }

// Print error message and exit with code 1


func parameters(a *gen.Action) string {
	var m = a.MandatoryParams()
	var hasOptional = a.HasOptionalParams()
	var countParams = len(m)
	if hasOptional {
		countParams++
	}
	var params = make([]string, countParams)
	for i, param := range m {
		params[i] = fmt.Sprintf("%s %s", fixReserved(param.VarName), param.Signature())
	}
	if hasOptional {
		params[countParams-1] = "options rsapi.APIParams"
	}

	return strings.Join(params, ", ")
}

func parameters ( a * gen . Action ) string { var m = a . MandatoryParams ( ) var hasOptional = a . HasOptionalParams ( ) var countParams = len ( m ) if hasOptional { countParams ++ } var params = make ( [ ] string , countParams ) for i , param := range m { params [ i ] = fmt . Sprintf ( " " , fixReserved ( param . VarName ) , param . Signature ( ) ) } if hasOptional { params [ countParams - 1 ] = " " } return strings . Join ( params , " " ) }


func paramsInitializer(action *gen.Action, location int, varName string) string {
	var fields []string
	var optionals []*gen.ActionParam
	varName = fixReserved(varName)
	for _, param := range action.Params {
		if param.Location != location {
			continue
		}
		if param.Mandatory {
			name := param.Name
			if location == 1 { // QueryParam
				name = param.QueryName
			}
			fields = append(fields, fmt.Sprintf("\"%s\": %s,", name, fixReserved(param.VarName)))
		} else {
			optionals = append(optionals, param)
		}
	}
	if len(fields) == 0 && len(optionals) == 0 {
		return ""
	}
	var paramsDecl = fmt.Sprintf("rsapi.APIParams{\n%s\n}", strings.Join(fields, "\n\t"))
	if len(optionals) == 0 {
		return fmt.Sprintf("\n%s = %s", varName, paramsDecl)
	}
	var inits = make([]string, len(optionals))
	for i, opt := range optionals {
		name := opt.Name
		if location == 1 { // QueryParam
			name = opt.QueryName
		}
		inits[i] = fmt.Sprintf("\tvar %sOpt = options[\"%s\"]\n\tif %sOpt != nil {\n\t\t%s[\"%s\"] = %sOpt\n\t}",
			opt.VarName, opt.Name, opt.VarName, varName, name, opt.VarName)
	}
	var paramsInits = strings.Join(inits, "\n\t")
	return fmt.Sprintf("\n%s = %s\n%s", varName, paramsDecl, paramsInits)
}

func
paramsInitializer
(
action
*
gen
.
Action
,
location
int
,
varName
string
)
string
{
var
fields
[
]
string
var
optionals
[
]
*
gen
.
ActionParam
varName
=
fixReserved
(
varName
)
for
_
,
param
:=
range
action
.
Params
{
if
param
.
Location
!=
location
{
continue
}
if
param
.
Mandatory
{
name
:=
param
.
Name
if
location
==
1
{
// QueryParam
name
=
param
.
QueryName
}
fields
=
append
(
fields
,
fmt
.
Sprintf
(
"
\"
\"
"
,
name
,
fixReserved
(
param
.
VarName
)
)
)
}
else
{
optionals
=
append
(
optionals
,
param
)
}
}
if
len
(
fields
)
==
0
&&
len
(
optionals
)
==
0
{
return
"
"
}
var
paramsDecl
=
fmt
.
Sprintf
(
"
\n
\n
"
,
strings
.
Join
(
fields
,
"
\n
\t
"
)
)
if
len
(
optionals
)
==
0
{
return
fmt
.
Sprintf
(
"
\n
"
,
varName
,
paramsDecl
)
}
var
inits
=
make
(
[
]
string
,
len
(
optionals
)
)
for
i
,
opt
:=
range
optionals
{
name
:=
opt
.
Name
if
location
==
1
{
// QueryParam
name
=
opt
.
QueryName
}
inits
[
i
]
=
fmt
.
Sprintf
(
"
\t
\"
\"
\n
\t
\n
\t
\t
\"
\"
\n
\t
"
,
opt
.
VarName
,
opt
.
Name
,
opt
.
VarName
,
varName
,
name
,
opt
.
VarName
)
}
var
paramsInits
=
strings
.
Join
(
inits
,
"
\n
\t
"
)
return
fmt
.
Sprintf
(
"
\n
\n
"
,
varName
,
paramsDecl
,
paramsInits
)
}

// Produces code that initializes a APIParams struct with the values of parameters for the given
// action and location.

Produces code that initializes a APIParams struct with the values of parameters for the given action and location .


func commandLine() string {
	return fmt.Sprintf("$ %s %s", os.Args[0], strings.Join(os.Args[1:], " "))
}

func commandLine ( ) string { return fmt . Sprintf ( " " , os . Args [ 0 ] , strings . Join ( os . Args [ 1 : ] , " " ) ) }


func toVerb(text string) (res string) {
	res = strings.ToUpper(string(text[0])) + strings.ToLower(text[1:])
	if text == "GET" || text == "POST" {
		res += "Raw"
	}
	return
}

func toVerb ( text string ) ( res string ) { res = strings . ToUpper ( string ( text [ 0 ] ) ) + strings . ToLower ( text [ 1 : ] ) if text == " " || text == " " { res += " " } return }


func escapeBackticks(d string) string {
	elems := strings.Split(d, "`")
	return strings.Join(elems, "` + `")
}

func escapeBackticks ( d string ) string { elems := strings . Split ( d , " " ) return strings . Join ( elems , " " ) }

// Escape ` in string to be wrapped in them


func (api *API) AccountPreferenceLocator(href string) *AccountPreferenceLocator {
	return &AccountPreferenceLocator{Href(href), api}
}

func ( api * API ) AccountPreferenceLocator ( href string ) * AccountPreferenceLocator { return & AccountPreferenceLocator { Href ( href ) , api } }

// AccountPreferenceLocator builds a locator from the given href.

AccountPreferenceLocator builds a locator from the given href .