From 2283076c976cad9615996e5e69867cd66603d238 Mon Sep 17 00:00:00 2001 From: daimaxiaxie Date: Fri, 29 Nov 2024 16:28:46 +0800 Subject: [PATCH] improve authorization --- ...enter.k8s.alibabacloud_ecsnodeclasses.yaml | 2 +- go.mod | 3 +- go.sum | 2 - pkg/operator/operator.go | 2 +- pkg/utils/client/client.go | 36 +- pkg/utils/client/metadata/metadata.go | 257 ++++++++++ vendor/github.com/aliyun/aliyun-cli/LICENSE | 202 -------- .../github.com/aliyun/aliyun-cli/cli/color.go | 138 ----- .../aliyun/aliyun-cli/cli/command.go | 352 ------------- .../aliyun/aliyun-cli/cli/command_help.go | 83 ---- .../aliyun/aliyun-cli/cli/completion.go | 132 ----- .../aliyun-cli/cli/completion_installer.go | 198 -------- .../aliyun/aliyun-cli/cli/completion_utils.go | 159 ------ .../aliyun/aliyun-cli/cli/context.go | 149 ------ .../aliyun/aliyun-cli/cli/errors.go | 87 ---- .../aliyun/aliyun-cli/cli/exit_code.go | 34 -- .../github.com/aliyun/aliyun-cli/cli/flag.go | 284 ----------- .../aliyun/aliyun-cli/cli/flag_field.go | 89 ---- .../aliyun/aliyun-cli/cli/flag_set.go | 135 ----- .../aliyun/aliyun-cli/cli/levenshtein.go | 263 ---------- .../aliyun/aliyun-cli/cli/output.go | 45 -- .../aliyun/aliyun-cli/cli/parser.go | 172 ------- .../aliyun/aliyun-cli/cli/suggestion.go | 63 --- .../aliyun/aliyun-cli/cli/version.go | 42 -- .../aliyun/aliyun-cli/config/configuration.go | 219 -------- .../aliyun/aliyun-cli/config/configure.go | 317 ------------ .../aliyun-cli/config/configure_delete.go | 72 --- .../aliyun/aliyun-cli/config/configure_get.go | 101 ---- .../aliyun-cli/config/configure_list.go | 82 --- .../aliyun/aliyun-cli/config/configure_set.go | 135 ----- .../aliyun-cli/config/configure_switch.go | 62 --- .../aliyun/aliyun-cli/config/flags.go | 426 ---------------- .../aliyun/aliyun-cli/config/hello.go | 104 ---- .../aliyun/aliyun-cli/config/legacy.go | 102 ---- .../aliyun/aliyun-cli/config/profile.go | 470 ------------------ .../aliyun/aliyun-cli/i18n/environment.go | 45 -- .../github.com/aliyun/aliyun-cli/i18n/text.go | 46 -- .../github.com/aliyun/aliyun-cli/util/util.go | 13 - vendor/modules.txt | 6 - 39 files changed, 284 insertions(+), 4845 deletions(-) create mode 100644 pkg/utils/client/metadata/metadata.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/LICENSE delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/color.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/command.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/command_help.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/completion.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/completion_installer.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/completion_utils.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/context.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/errors.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/exit_code.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/flag.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/flag_field.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/flag_set.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/levenshtein.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/output.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/parser.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/suggestion.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/cli/version.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/configuration.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/configure.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/configure_delete.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/configure_get.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/configure_list.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/configure_set.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/configure_switch.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/flags.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/hello.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/legacy.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/config/profile.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/i18n/environment.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/i18n/text.go delete mode 100644 vendor/github.com/aliyun/aliyun-cli/util/util.go diff --git a/charts/karpenter/crds/karpenter.k8s.alibabacloud_ecsnodeclasses.yaml b/charts/karpenter/crds/karpenter.k8s.alibabacloud_ecsnodeclasses.yaml index 13162ab5..15e6c25b 100644 --- a/charts/karpenter/crds/karpenter.k8s.alibabacloud_ecsnodeclasses.yaml +++ b/charts/karpenter/crds/karpenter.k8s.alibabacloud_ecsnodeclasses.yaml @@ -3,7 +3,7 @@ apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: annotations: - controller-gen.kubebuilder.io/version: v0.16.4 + controller-gen.kubebuilder.io/version: v0.16.5 name: ecsnodeclasses.karpenter.k8s.alibabacloud spec: group: karpenter.k8s.alibabacloud diff --git a/go.mod b/go.mod index 747fb740..a7e7f306 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,6 @@ require ( github.com/alibabacloud-go/tea v1.2.2 github.com/alibabacloud-go/tea-utils/v2 v2.0.6 github.com/alibabacloud-go/vpc-20160428/v6 v6.10.4 - github.com/aliyun/aliyun-cli v0.0.0-20240925084117-158a70e275f0 github.com/awslabs/operatorpkg v0.0.0-20240805231134-67d0acfb6306 github.com/cloudpilot-ai/priceserver v0.0.0-20241011010411-15ac0e19a857 github.com/mitchellh/hashstructure/v2 v2.0.2 @@ -42,7 +41,7 @@ require ( github.com/alibabacloud-go/openapi-util v0.1.0 // indirect github.com/alibabacloud-go/tea-utils v1.3.1 // indirect github.com/alibabacloud-go/tea-xml v1.1.3 // indirect - github.com/aliyun/credentials-go v1.3.10 // indirect + github.com/aliyun/credentials-go v1.3.10 github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect github.com/blendle/zapdriver v1.3.1 // indirect diff --git a/go.sum b/go.sum index dc447f4e..14ec1e2f 100644 --- a/go.sum +++ b/go.sum @@ -91,8 +91,6 @@ github.com/alibabacloud-go/tea-xml v1.1.3 h1:7LYnm+JbOq2B+T/B0fHC4Ies4/FofC4zHzY github.com/alibabacloud-go/tea-xml v1.1.3/go.mod h1:Rq08vgCcCAjHyRi/M7xlHKUykZCEtyBy9+DPF6GgEu8= github.com/alibabacloud-go/vpc-20160428/v6 v6.10.4 h1:6OXPOw1WcEjoSCOPFtKKgFFSlSSapns0uoOML+hzn8M= github.com/alibabacloud-go/vpc-20160428/v6 v6.10.4/go.mod h1:6516WWE4Y9lzscVSfaev84DM+TQSvBEGX1oeMvDL5xk= -github.com/aliyun/aliyun-cli v0.0.0-20240925084117-158a70e275f0 h1:GyWC5h0inFp+vmJVbbRGh34KTj/HeG/tyqJwR+pQbko= -github.com/aliyun/aliyun-cli v0.0.0-20240925084117-158a70e275f0/go.mod h1:LRvAoBmigy35079C5FYKseCCHG4oCCC0dEgyuSsAVeo= github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6qTJya2bDq4X1Tw= github.com/aliyun/credentials-go v1.3.1/go.mod h1:8jKYhQuDawt8x2+fusqa1Y6mPxemTsBEN04dgcAcYz0= github.com/aliyun/credentials-go v1.3.6/go.mod h1:1LxUuX7L5YrZUWzBrRyk0SwSdH4OmPrib8NVePL3fxM= diff --git a/pkg/operator/operator.go b/pkg/operator/operator.go index 78aeca36..e73fd718 100644 --- a/pkg/operator/operator.go +++ b/pkg/operator/operator.go @@ -61,7 +61,7 @@ type Operator struct { } func NewOperator(ctx context.Context, operator *operator.Operator) (context.Context, *Operator) { - clientConfig, err := client.NewClientConfig() + clientConfig, err := client.NewClientConfig(ctx) if err != nil { log.FromContext(ctx).Error(err, "Failed to create client config") os.Exit(1) diff --git a/pkg/utils/client/client.go b/pkg/utils/client/client.go index b1caeb8a..321445a8 100644 --- a/pkg/utils/client/client.go +++ b/pkg/utils/client/client.go @@ -17,30 +17,42 @@ limitations under the License. package client import ( - "errors" + "context" + "fmt" + "os" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" "github.com/alibabacloud-go/tea/tea" - aliyunconfig "github.com/aliyun/aliyun-cli/config" + "github.com/aliyun/credentials-go/credentials" + "sigs.k8s.io/controller-runtime/pkg/log" + + "github.com/cloudpilot-ai/karpenter-provider-alibabacloud/pkg/utils/client/metadata" ) -func NewClientConfig() (*openapi.Config, error) { - profile, err := aliyunconfig.LoadCurrentProfile() +func NewClientConfig(ctx context.Context) (*openapi.Config, error) { + // Load in the following order: 1. AK/SK, 2. RRSA, 3. config.json, 4. RAMRole + // https://www.alibabacloud.com/help/zh/sdk/developer-reference/v2-manage-go-access-credentials#3ca299f04bw3c + credential, err := credentials.NewCredential(nil) if err != nil { return nil, err } - - if profile.RegionId == "" { - return nil, errors.New("regionId must be set in the config file") + if cred, err := credential.GetCredential(); err == nil && cred != nil { + log.FromContext(ctx).Info(fmt.Sprintf("using credential type: %s, AccessKeyID: %s", tea.StringValue(cred.Type), tea.StringValue(cred.AccessKeyId))) + } else { + return nil, fmt.Errorf("failed get credential, error: %w", err) } - credentialClient, err := profile.GetCredential(nil, nil) - if err != nil { - return nil, err + region := os.Getenv("REGION_ID") + if region == "" { + region, err = metadata.NewMetaData(nil).Region() + if err != nil { + return nil, err + } } return &openapi.Config{ - RegionId: tea.String(profile.RegionId), - Credential: credentialClient, + RegionId: tea.String(region), + Credential: credential, + Network: tea.String(os.Getenv("ALIBABA_CLOUD_NETWORK")), // 1. public, 2. vpc, default is public }, nil } diff --git a/pkg/utils/client/metadata/metadata.go b/pkg/utils/client/metadata/metadata.go new file mode 100644 index 00000000..cc712bbf --- /dev/null +++ b/pkg/utils/client/metadata/metadata.go @@ -0,0 +1,257 @@ +/* +Copyright 2024 The CloudPilot AI Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package metadata + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "reflect" + "strings" + "time" +) + +const ( + Endpoint = "http://100.100.100.200" + hostname = "hostname" + instanceID = "instance-id" + regionID = "region-id" + ramSecurity = "ram/security-credentials" +) + +// MetaData wrap http client +type MetaData struct { + // mock for unit test. + mock requestMock + client *http.Client +} + +// NewMetaData returns MetaData +func NewMetaData(client *http.Client) *MetaData { + if client == nil { + client = &http.Client{} + } + return &MetaData{ + client: client, + } +} + +// NewMockMetaData returns mock MetaData +func NewMockMetaData(client *http.Client, sendRequest requestMock) *MetaData { + if client == nil { + client = &http.Client{} + } + return &MetaData{ + client: client, + mock: sendRequest, + } +} + +// New returns MetaDataRequest +func (m *MetaData) New() *MetaDataRequest { + return &MetaDataRequest{ + client: m.client, + sendRequest: m.mock, + } +} + +// HostName returns host name +func (m *MetaData) HostName() (string, error) { + var name ResultList + err := m.New().Resource(hostname).Do(&name) + if err != nil { + return "", err + } + return name.result[0], nil +} + +// InstanceID returns instance Id +func (m *MetaData) InstanceID() (string, error) { + var instanceid ResultList + err := m.New().Resource(instanceID).Do(&instanceid) + if err != nil { + return "", err + } + return instanceid.result[0], err +} + +// Region returns region +func (m *MetaData) Region() (string, error) { + var region ResultList + err := m.New().Resource(regionID).Do(®ion) + if err != nil { + return "", err + } + return region.result[0], nil +} + +// RoleName returns role name +func (m *MetaData) RoleName() (string, error) { + var roleName ResultList + err := m.New().Resource("ram/security-credentials/").Do(&roleName) + if err != nil { + return "", err + } + return roleName.result[0], nil +} + +// RamRoleToken returns ram role token +func (m *MetaData) RAMRoleToken(role string) (RoleAuth, error) { + var roleauth RoleAuth + err := m.New().Resource(ramSecurity).SubResource(role).Do(&roleauth) + if err != nil { + return RoleAuth{}, err + } + return roleauth, nil +} + +type requestMock func(resource string) (string, error) + +// ResultList struct +type ResultList struct { + result []string +} + +// nolint: stylecheck +// RoleAuth struct +type RoleAuth struct { + AccessKeyId string + AccessKeySecret string + Expiration time.Time + SecurityToken string + LastUpdated time.Time + Code string +} + +// MetaDataRequest struct +type MetaDataRequest struct { + version string + resourceType string + resource string + subResource string + client *http.Client + + sendRequest requestMock +} + +// Version sets version +func (r *MetaDataRequest) Version(version string) *MetaDataRequest { + r.version = version + return r +} + +// ResourceType sets resource type +func (r *MetaDataRequest) ResourceType(rtype string) *MetaDataRequest { + r.resourceType = rtype + return r +} + +// Resource sets resource +func (r *MetaDataRequest) Resource(resource string) *MetaDataRequest { + r.resource = resource + return r +} + +// SubResource set sub resource +func (r *MetaDataRequest) SubResource(sub string) *MetaDataRequest { + r.subResource = sub + return r +} + +// URL returns url +func (r *MetaDataRequest) URL() (string, error) { + if r.version == "" { + r.version = "latest" + } + if r.resourceType == "" { + r.resourceType = "meta-data" + } + if r.resource == "" { + return "", errors.New("the resource you want to visit must not be nil") + } + endpoint := os.Getenv("METADATA_ENDPOINT") + if endpoint == "" { + endpoint = Endpoint + } + url := fmt.Sprintf("%s/%s/%s/%s", endpoint, r.version, r.resourceType, r.resource) + if r.subResource == "" { + return url, nil + } + return fmt.Sprintf("%s/%s", url, r.subResource), nil +} + +// Do try to do MetaDataRequest +func (r *MetaDataRequest) Do(api interface{}) (err error) { + res := "" + + if r.sendRequest != nil { + res, err = r.sendRequest(r.resource) + } else { + res, err = r.send() + } + + if err != nil { + return err + } + return r.Decode(res, api) +} + +// Decode returns decoded content +func (r *MetaDataRequest) Decode(data string, api interface{}) error { + if data == "" { + url, _ := r.URL() + return fmt.Errorf("metadata: alivpc decode data must not be nil. url=[%s]", url) + } + switch api := api.(type) { + case *ResultList: + api.result = strings.Split(data, "\n") + return nil + case *RoleAuth: + return json.Unmarshal([]byte(data), api) + default: + return fmt.Errorf("metadata: unknow type to decode, type=%s", reflect.TypeOf(api)) + } +} + +func (r *MetaDataRequest) send() (string, error) { + url, err := r.URL() + if err != nil { + return "", err + } + req, err := http.NewRequest(http.MethodGet, url, nil) + + if err != nil { + return "", err + } + resp, err := r.client.Do(req) + if err != nil { + return "", err + } + if resp.StatusCode != 200 { + return "", fmt.Errorf("aliyun Metadata API Error: Status Code: %d", resp.StatusCode) + } + defer resp.Body.Close() + + data, err := io.ReadAll(resp.Body) + if err != nil { + return "", err + } + return string(data), nil +} diff --git a/vendor/github.com/aliyun/aliyun-cli/LICENSE b/vendor/github.com/aliyun/aliyun-cli/LICENSE deleted file mode 100644 index 77b2dea1..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2015-2016 Ferran Rodenas - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/color.go b/vendor/github.com/aliyun/aliyun-cli/cli/color.go deleted file mode 100644 index aecf080a..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/color.go +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "io" - "os" -) - -const ( - ColorOff = "\033[0m" // Reset Color - // Regular Colors - Black = "\033[0;30m" // Black - Red = "\033[0;31m" // Red - Green = "\033[0;32m" // Green - Yellow = "\033[0;33m" // Yellow - Blue = "\033[0;34m" // Blue - Purple = "\033[0;35m" // Purple - Cyan = "\033[0;36m" // Cyan - White = "\033[0;37m" // White - - // Bold - BBlack = "\033[1;30m" // Black - BRed = "\033[1;31m" // Red - BGreen = "\033[1;32m" // Green - BYellow = "\033[1;33m" // Yellow - BBlue = "\033[1;34m" // Blue - BPurple = "\033[1;35m" // Purple - BCyan = "\033[1;36m" // Cyan - BWhite = "\033[1;37m" // White - - // Underline - UBlack = "\033[4;30m" // Black - URed = "\033[4;31m" // Red - UGreen = "\033[4;32m" // Green - UYellow = "\033[4;33m" // Yellow - UBlue = "\033[4;34m" // Blue - UPurple = "\033[4;35m" // Purple - UCyan = "\033[4;36m" // Cyan - UWhite = "\033[4;37m" // White - - // Background - OnBlack = "\033[40m" // Black - OnRed = "\033[41m" // Red - OnGreen = "\033[42m" // Green - OnYellow = "\033[43m" // Yellow - OnBlue = "\033[44m" // Blue - OnPurple = "\033[45m" // Purple - OnCyan = "\033[46m" // Cyan - OnWhite = "\033[47m" // White - - // High Intensty - IBlack = "\033[0;90m" // Black - IRed = "\033[0;91m" // Red - IGreen = "\033[0;92m" // Green - IYellow = "\033[0;93m" // Yellow - IBlue = "\033[0;94m" // Blue - IPurple = "\033[0;95m" // Purple - ICyan = "\033[0;96m" // Cyan - IWhite = "\033[0;97m" // White - - // Bold High Intensty - BIBlack = "\033[1;90m" // Black - BIRed = "\033[1;91m" // Red - BIGreen = "\033[1;92m" // Green - BIYellow = "\033[1;93m" // Yellow - BIBlue = "\033[1;94m" // Blue - BIPurple = "\033[1;95m" // Purple - BICyan = "\033[1;96m" // Cyan - BIWhite = "\033[1;97m" // White - - // High Intensty backgrounds - OnIBlack = "\033[0;100m" // Black - OnIRed = "\033[0;101m" // Red - OnIGreen = "\033[0;102m" // Green - OnIYellow = "\033[0;103m" // Yellow - OnIBlue = "\033[0;104m" // Blue - OnIPurple = "\033[10;95m" // Purple - OnICyan = "\033[0;106m" // Cyan - OnIWhite = "\033[0;107m" // White -) - -const ( - DebugColor = White - InfoColor = Cyan - NoticeColor = BYellow - WarningColor = BPurple - ErrorColor = BRed -) - -func isNoColor() bool { - var isTTY = os.FileMode(0)&os.ModeDevice != 0 - var NO_COLOR = os.Getenv("NO_COLOR") - return isTTY || NO_COLOR == "true" || NO_COLOR == "1" -} - -func Colorized(color string, a ...interface{}) string { - if !isNoColor() && color != "" { - return color + fmt.Sprint(a...) + ColorOff - } - return fmt.Sprint(a...) -} - -func PrintWithColor(w io.Writer, color string, a ...interface{}) (n int, err error) { - return Print(w, Colorized(color, a...)) -} - -func Notice(w io.Writer, a ...interface{}) (n int, err error) { - return Print(w, Colorized(NoticeColor, a...)) -} - -func Error(w io.Writer, a ...interface{}) (n int, err error) { - return Print(w, Colorized(ErrorColor, a...)) -} - -func Noticef(w io.Writer, format string, args ...interface{}) (n int, err error) { - return Notice(w, fmt.Sprintf(format, args...)) -} - -func Errorf(w io.Writer, format string, args ...interface{}) (n int, err error) { - return Error(w, fmt.Sprintf(format, args...)) -} - -func PrintfWithColor(w io.Writer, color string, format string, args ...interface{}) (n int, err error) { - return PrintWithColor(w, color, fmt.Sprintf(format, args...)) -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/command.go b/vendor/github.com/aliyun/aliyun-cli/cli/command.go deleted file mode 100644 index a3f1fdab..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/command.go +++ /dev/null @@ -1,352 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "strings" - - "github.com/aliyun/aliyun-cli/i18n" -) - -type Command struct { - // Command Name - Name string - - // Short is the short description shown in the 'help' output. - Short *i18n.Text - - // Long is the long message shown in the 'help ' output. - Long *i18n.Text - - // Syntax for usage - Usage string - - // Sample command - Sample string - - // Enable unknown flags - EnableUnknownFlag bool - - // enable suggest distance, - // disable -1 - // 0: default distance - SuggestDistance int - - // Hidden command - Hidden bool - - // Run, command error will be catch - Run func(ctx *Context, args []string) error - - // Help - Help func(ctx *Context, args []string) error - - // auto compete - AutoComplete func(ctx *Context, args []string) []string - - parent *Command - subCommands []*Command - flags *FlagSet - - // Keep args - KeepArgs bool -} - -func (c *Command) AddSubCommand(cmd *Command) { - cmd.parent = c - c.subCommands = append(c.subCommands, cmd) -} - -func (c *Command) Flags() *FlagSet { - if c.flags == nil { - c.flags = NewFlagSet() - } - return c.flags -} - -func (c *Command) Execute(ctx *Context, args []string) { - if ctx.completion != nil { - args = ctx.completion.GetArgs() - } - - err := c.executeInner(ctx, args) - if err != nil { - c.processError(ctx, err) - } -} - -func (c *Command) getName() string { - if c.parent == nil { - return c.Name - } - - return c.parent.getName() + " " + c.Name -} - -type Metadata struct { - Name string `json:"name"` - Short map[string]string `json:"short"` - Long map[string]string `json:"long"` - Usage string `json:"usage"` - Sample string `json:"sample"` - Hidden bool `json:"hidden"` - Flags map[string]*MetadataFlag `json:"flags"` -} - -type MetadataFlag struct { - Name string `json:"name"` - Shorthand rune `json:"shorthand"` - Short map[string]string `json:"short"` - Long map[string]string `json:"long"` - DefaultValue string `json:"default"` - Required bool `json:"required"` - Aliases []string `json:"aliases"` - AssignedMode int `json:"assign_mode"` - Persistent bool `json:"persistent"` - Hidden bool `json:"hidden"` - Category string `json:"category"` -} - -func (c *Command) GetMetadata(metadata map[string]*Metadata) { - name := c.getName() - - meta := &Metadata{} - meta.Name = name - meta.Short = c.Short.GetData() - if c.Long != nil { - meta.Long = c.Long.GetData() - } - - meta.Usage = c.Usage - meta.Sample = c.Sample - meta.Hidden = c.Hidden - - meta.Flags = make(map[string]*MetadataFlag) - for _, flag := range c.Flags().Flags() { - f := &MetadataFlag{} - f.Name = flag.Name - f.Shorthand = flag.Shorthand - if flag.Short != nil { - f.Short = flag.Short.GetData() - } - if flag.Long != nil { - f.Long = flag.Long.GetData() - } - f.DefaultValue = flag.DefaultValue - f.Required = flag.Required - f.Aliases = flag.Aliases - f.AssignedMode = int(flag.AssignedMode) - f.Persistent = flag.Persistent - f.Hidden = flag.Hidden - f.Category = flag.Category - - // Flag can assigned with --flag field1=value1 field2=value2 value3 ... - // must used with AssignedMode=AssignedRepeatable - // Fields []Field - - // Flag can't appear with other flags, use Flag.Name - // ExcludeWith []string - - meta.Flags[flag.Name] = f - } - metadata[name] = meta - for _, cmd := range c.subCommands { - cmd.GetMetadata(metadata) - } -} - -func (c *Command) GetSubCommand(s string) *Command { - for _, cmd := range c.subCommands { - if cmd.Name == s { - return cmd - } - } - return nil -} - -func (c *Command) GetSuggestions(s string) []string { - sr := NewSuggester(s, c.GetSuggestDistance()) - for _, cmd := range c.subCommands { - sr.Apply(cmd.Name) - } - return sr.GetResults() -} - -func (c *Command) GetSuggestDistance() int { - if c.SuggestDistance < 0 { - return 0 - } else if c.SuggestDistance == 0 { - return DefaultSuggestDistance - } else { - return c.SuggestDistance - } -} - -func (c *Command) GetUsageWithParent() string { - usage := c.Usage - for p := c.parent; p != nil; p = p.parent { - usage = p.Name + " " + usage - } - return usage -} - -func (c *Command) ExecuteComplete(ctx *Context, args []string) { - if strings.HasPrefix(ctx.completion.Current, "-") { - for _, f := range ctx.flags.Flags() { - if f.Hidden { - continue - } - if !strings.HasPrefix("--"+f.Name, ctx.completion.Current) { - continue - } - Printf(ctx.Stdout(), "--%s\n", f.Name) - } - } else { - for _, sc := range c.subCommands { - if sc.Hidden { - continue - } - if !strings.HasPrefix(sc.Name, ctx.completion.Current) { - continue - } - Printf(ctx.Stdout(), "%s\n", sc.Name) - } - } -} - -func (c *Command) executeInner(ctx *Context, args []string) error { - // fmt.Printf(">>> Execute Command: %s args=%v\n", c.Name, args) - parser := NewParser(args, ctx) - - var current = parser.GetCurrent() - // get next arg - nextArg, _, err := parser.ReadNextArg() - if err != nil { - return err - } - - // if next arg is help, run help - if nextArg == "help" { - ctx.help = true - return c.executeInner(ctx, parser.GetRemains()) - } - - // if next args is not empty, try find sub commands - if nextArg != "" { - // if has sub command, run it - subCommand := c.GetSubCommand(nextArg) - if subCommand != nil { - ctx.EnterCommand(subCommand) - return subCommand.executeInner(ctx, parser.GetRemains()) - } - - // no sub command and command.Run == nil - // raise error - if c.Run == nil { - // c.executeHelp(ctx, args, fmt.Errorf("unknown command: %s", nextArg)) - return NewInvalidCommandError(nextArg, ctx) - } - } - - var remainArgs []string - if !c.KeepArgs { - // cmd is find by args, try run cmd.Run - // parse remain args - remainArgs, err = parser.ReadAll() - if err != nil { - return fmt.Errorf("parse failed %s", err) - } - } else { - remainArgs = args[current:] - } - - // check flags - err = ctx.CheckFlags() - if err != nil { - return err - } - - if HelpFlag(ctx.Flags()).IsAssigned() { - ctx.help = true - } - - callArgs := make([]string, 0) - if nextArg != "" { - if !c.KeepArgs { - callArgs = append(callArgs, nextArg) - } - } - - for _, s := range remainArgs { - if s != "help" { - callArgs = append(callArgs, s) - } else { - ctx.help = true - } - } - - if ctx.completion != nil { - if c.AutoComplete != nil { - ss := c.AutoComplete(ctx, callArgs) - for _, s := range ss { - Printf(ctx.Stdout(), "%s\n", s) - } - } else { - c.ExecuteComplete(ctx, callArgs) - } - return nil - } - - if ctx.help { - c.executeHelp(ctx, callArgs) - return nil - } else if c.Run == nil { - c.executeHelp(ctx, callArgs) - return nil - } - - return c.Run(ctx, callArgs) -} - -func (c *Command) processError(ctx *Context, err error) { - Errorf(ctx.Stderr(), "ERROR: %s\n", err.Error()) - if e, ok := err.(SuggestibleError); ok { - PrintSuggestions(ctx, i18n.GetLanguage(), e.GetSuggestions()) - Exit(2) - return - } - if e, ok := err.(ErrorWithTip); ok { - Noticef(ctx.Stderr(), "\n%s\n", e.GetTip(i18n.GetLanguage())) - Exit(3) - return - } - Exit(1) -} - -func (c *Command) executeHelp(ctx *Context, args []string) { - if c.Help != nil { - err := c.Help(ctx, args) - if err != nil { - c.processError(ctx, err) - } - return - } - - c.PrintHead(ctx) - c.PrintUsage(ctx) - c.PrintSubCommands(ctx) - c.PrintFlags(ctx) - c.PrintTail(ctx) -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/command_help.go b/vendor/github.com/aliyun/aliyun-cli/cli/command_help.go deleted file mode 100644 index aaa88aa4..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/command_help.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "text/tabwriter" -) - -func (c *Command) PrintHead(ctx *Context) { - Printf(ctx.Stdout(), "%s\n", c.Short.Text()) -} - -func (c *Command) PrintUsage(ctx *Context) { - if c.Usage != "" { - Printf(ctx.Stdout(), "\nUsage:\n %s\n", c.GetUsageWithParent()) - } else { - c.PrintSubCommands(ctx) - } -} - -func (c *Command) PrintSample(ctx *Context) { - if c.Sample != "" { - Printf(ctx.Stdout(), "\nSample:\n %s\n", c.Sample) - } -} - -func (c *Command) PrintSubCommands(ctx *Context) { - if len(c.subCommands) > 0 { - Printf(ctx.Stdout(), "\nCommands:\n") - w := tabwriter.NewWriter(ctx.Stdout(), 8, 0, 1, ' ', 0) - for _, cmd := range c.subCommands { - if cmd.Hidden { - continue - } - fmt.Fprintf(w, " %s\t%s\n", cmd.Name, cmd.Short.Text()) - } - w.Flush() - } -} - -func (c *Command) PrintFlags(ctx *Context) { - if len(c.Flags().Flags()) == 0 { - return - } - Printf(ctx.Stdout(), "\nFlags:\n") - w := tabwriter.NewWriter(ctx.Stdout(), 8, 0, 1, ' ', 0) - fs := c.Flags() - if ctx != nil { - fs = ctx.Flags() - } - for _, flag := range fs.Flags() { - if flag.Hidden { - continue - } - s := "--" + flag.Name - if flag.Shorthand != 0 { - s = s + ",-" + string(flag.Shorthand) - } - fmt.Fprintf(w, " %s\t%s\n", s, flag.Short.Text()) - } - w.Flush() -} - -func (c *Command) PrintFailed(ctx *Context, err error, suggestion string) { - Errorf(ctx.Stderr(), "ERROR: %v\n", err) - Printf(ctx.Stderr(), "%s\n", suggestion) -} - -func (c *Command) PrintTail(ctx *Context) { - Printf(ctx.Stdout(), "\nUse `%s --help` for more information.\n", c.Name) -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/completion.go b/vendor/github.com/aliyun/aliyun-cli/cli/completion.go deleted file mode 100644 index d32e7783..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/completion.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "os" - "strconv" - "strings" -) - -type Completion struct { - Current string - Args []string - line string - point int -} - -func ParseCompletionForShell() *Completion { - return ParseCompletion(os.Getenv("COMP_LINE"), os.Getenv("COMP_POINT")) -} - -func ParseCompletion(line, point string) *Completion { - if line == "" { - return nil - } - - p, err := strconv.Atoi(point) - - if err != nil { - return nil - } - - if p >= len(line) { - p = len(line) - } - - args := parseLineForCompletion(line, p) - current := "" - - if strings.HasSuffix(line, " ") { - if len(args) == 1 { - args = []string{} - } else { - args = args[1:] - } - } else { - if len(args) > 1 { - current = args[len(args)-1] - args = args[1 : len(args)-1] - } else { - panic(fmt.Errorf("unexcepted args %v for line '%s'", args, line)) - } - } - - return &Completion{ - Current: current, - Args: args, - line: line, - point: p, - } -} - -func (c *Completion) GetCurrent() string { - return c.Current -} - -func (c *Completion) GetArgs() []string { - return c.Args -} - -func parseLineForCompletion(line string, point int) []string { - if point > len(line) { - panic(fmt.Errorf("%s[%d] out of range", line, point)) - } - - var quote rune - var backslash bool - var word []rune - cl := make([]string, 0) - for _, char := range line[:point] { - if backslash { - word = append(word, char) - backslash = false - continue - } - if char == '\\' { - word = append(word, char) - backslash = true - continue - } - - switch quote { - case 0: - switch char { - case '\'', '"': - word = append(word, char) - quote = char - case ' ', '\t': - if word != nil { - cl = append(cl, string(word)) - } - word = nil - default: - word = append(word, char) - } - case '\'': - word = append(word, char) - if char == '\'' { - quote = 0 - } - case '"': - word = append(word, char) - if char == '"' { - quote = 0 - } - } - } - - return append(cl, string(word)) -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/completion_installer.go b/vendor/github.com/aliyun/aliyun-cli/cli/completion_installer.go deleted file mode 100644 index 2bd46886..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/completion_installer.go +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "os" - "os/user" - - "github.com/aliyun/aliyun-cli/i18n" -) - -var hookGetBinaryPath = func(fn func() (string, error)) func() (string, error) { - return fn -} - -func getHomeDir() string { - homeDirFromEnv := os.Getenv("MOCK_USER_HOME_DIR") - if homeDirFromEnv != "" { - os.Mkdir(homeDirFromEnv, os.ModePerm) - return homeDirFromEnv - } - u, err := user.Current() - if err != nil { - return "" - } - return u.HomeDir -} - -var uninstallFlag = &Flag{ - Name: "uninstall", - Short: i18n.T("uninstall auto completion", "卸载自动完成"), -} - -func NewAutoCompleteCommand() *Command { - cmd := &Command{ - Name: "auto-completion", - Short: i18n.T( - "enable auto completion", - "启用自动完成"), - Usage: "auto-completion [--uninstall]", - Run: func(ctx *Context, args []string) error { - //s, _ := os.Executable() - //fmt.Printf("%s \n", s) - // - //if f := rcFile(".zshrc"); f != "" { - // // i = append(i, zshInstaller{f}) - // fmt.Printf("zshInstaller: %s\n", f) - //} - if uninstallFlag.IsAssigned() { - uninstallCompletion(ctx, "aliyun") - } else { - installCompletion(ctx, "aliyun") - } - return nil - }, - } - cmd.Flags().Add(uninstallFlag) - return cmd -} - -func installCompletion(ctx *Context, cmd string) { - bin, err := getBinaryPath() - if err != nil { - Errorf(ctx.Stderr(), "can't get binary path %s", err) - return - } - - for _, i := range completionInstallers() { - err := i.Install(cmd, bin) - if err != nil { - Errorf(ctx.Stderr(), "install completion failed for %s %s\n", bin, err) - } - } -} - -func uninstallCompletion(ctx *Context, cmd string) { - bin, err := hookGetBinaryPath(getBinaryPath)() - if err != nil { - Errorf(ctx.Stderr(), "can't get binary path %s", err) - return - } - - for _, i := range completionInstallers() { - err := i.Uninstall(cmd, bin) - if err != nil { - Errorf(ctx.Stderr(), "uninstall %s failed\n", err) - } - } -} - -func completionInstallers() (i []completionInstaller) { - for _, rc := range [...]string{".bashrc", ".bash_profile", ".bash_login", ".profile"} { - if f := rcFile(rc); f != "" { - i = append(i, bashInstaller{f}) - break - } - } - if f := rcFile(".zshrc"); f != "" { - i = append(i, zshInstaller{f}) - } - return -} - -type completionInstaller interface { - GetName() string - Install(cmd string, bin string) error - Uninstall(cmd string, bin string) error -} - -// (un)install in zshInstaller -// basically adds/remove from .zshrc: -// -// autoload -U +X bashcompinit && bashcompinit" -// complete -C -type zshInstaller struct { - rc string -} - -func (z zshInstaller) GetName() string { - return "zsh" -} - -func (z zshInstaller) Install(cmd, bin string) error { - completeCmd := z.cmd(cmd, bin) - if lineInFile(z.rc, completeCmd) { - return fmt.Errorf("already installed in %s", z.rc) - } - - compInit := "autoload -U +X compinit && compinit -i" - bashCompInit := "autoload -U +X bashcompinit && bashcompinit -i" - if !lineInFile(z.rc, compInit) { - if !lineInFile(z.rc, bashCompInit) { - completeCmd = compInit + "\n" + bashCompInit + "\n" + completeCmd - } else { - completeCmd = compInit + "\n" + completeCmd - } - } - - return appendToFile(z.rc, completeCmd) -} - -func (z zshInstaller) Uninstall(cmd, bin string) error { - completeCmd := z.cmd(cmd, bin) - if !lineInFile(z.rc, completeCmd) { - return fmt.Errorf("does not installed in %s", z.rc) - } - - return removeFromFile(z.rc, completeCmd) -} - -func (zshInstaller) cmd(cmd, bin string) string { - return fmt.Sprintf("complete -o nospace -F %s %s", bin, cmd) -} - -// (un)install in bashInstaller -// basically adds/remove from .bashrc: -// -// complete -C -type bashInstaller struct { - rc string -} - -func (b bashInstaller) GetName() string { - return "bash" -} - -func (b bashInstaller) Install(cmd, bin string) error { - completeCmd := b.cmd(cmd, bin) - if lineInFile(b.rc, completeCmd) { - return fmt.Errorf("already installed in %s", b.rc) - } - return appendToFile(b.rc, completeCmd) -} - -func (b bashInstaller) Uninstall(cmd, bin string) error { - completeCmd := b.cmd(cmd, bin) - if !lineInFile(b.rc, completeCmd) { - return fmt.Errorf("does not installed in %s", b.rc) - } - - return removeFromFile(b.rc, completeCmd) -} - -func (bashInstaller) cmd(cmd, bin string) string { - return fmt.Sprintf("complete -C %s %s", bin, cmd) -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/completion_utils.go b/vendor/github.com/aliyun/aliyun-cli/cli/completion_utils.go deleted file mode 100644 index a7b1f9b3..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/completion_utils.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "bufio" - "fmt" - "io" - "os" - "path/filepath" -) - -func lineInFile(name string, lookFor string) bool { - f, err := os.Open(name) - if err != nil { - return false - } - defer f.Close() - r := bufio.NewReader(f) - prefix := []byte{} - for { - line, isPrefix, err := r.ReadLine() - if err == io.EOF { - return false - } - if err != nil { - return false - } - if isPrefix { - prefix = append(prefix, line...) - continue - } - line = append(prefix, line...) - if string(line) == lookFor { - return true - } - prefix = prefix[:0] - } -} - -func createFile(name string, content string) error { - f, err := os.Create(name) - if err != nil { - return err - } - defer f.Close() - _, err = f.WriteString(fmt.Sprintf("%s\n", content)) - return err -} - -func appendToFile(name string, content string) error { - f, err := os.OpenFile(name, os.O_RDWR|os.O_APPEND, 0) - if err != nil { - return err - } - defer f.Close() - _, err = f.WriteString(fmt.Sprintf("\n%s\n", content)) - return err -} - -func removeFromFile(name string, content string) error { - backup := name + ".bck" - err := copyFile(name, backup) - if err != nil { - return err - } - temp, err := removeContentToTempFile(name, content) - if err != nil { - return err - } - - err = copyFile(temp, name) - if err != nil { - return err - } - - return os.Remove(backup) -} - -func removeContentToTempFile(name, content string) (string, error) { - rf, err := os.Open(name) - if err != nil { - return "", err - } - defer rf.Close() - wf, err := os.CreateTemp("", "complete-") - if err != nil { - return "", err - } - defer wf.Close() - - r := bufio.NewReader(rf) - prefix := []byte{} - for { - line, isPrefix, err := r.ReadLine() - if err == io.EOF { - break - } - if err != nil { - return "", err - } - if isPrefix { - prefix = append(prefix, line...) - continue - } - line = append(prefix, line...) - str := string(line) - if str == content { - continue - } - wf.WriteString(str + "\n") - prefix = prefix[:0] - } - return wf.Name(), nil -} - -func copyFile(src string, dst string) error { - in, err := os.Open(src) - if err != nil { - return err - } - defer in.Close() - out, err := os.Create(dst) - if err != nil { - return err - } - defer out.Close() - _, err = io.Copy(out, in) - return err -} - -func getBinaryPath() (string, error) { - bin, err := os.Executable() - if err != nil { - return "", err - } - return filepath.Abs(bin) -} - -func rcFile(name string) string { - path := filepath.Join(getHomeDir(), name) - fmt.Println(path) - if _, err := os.Stat(path); err != nil { - return "" - } - - return path -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/context.go b/vendor/github.com/aliyun/aliyun-cli/cli/context.go deleted file mode 100644 index 669af2b9..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/context.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "io" - - "github.com/aliyun/aliyun-cli/i18n" -) - -// -// default help flag - -func HelpFlag(fs *FlagSet) *Flag { - return fs.Get("help") -} - -func NewHelpFlag() *Flag { - return &Flag{ - Name: "help", - Short: i18n.T("print help", "打印帮助信息"), - AssignedMode: AssignedNone, - } -} - -// CLI Command Context -type Context struct { - help bool - flags *FlagSet - unknownFlags *FlagSet - command *Command - completion *Completion - stdout io.Writer - stderr io.Writer -} - -func NewCommandContext(stdout io.Writer, stderr io.Writer) *Context { - return &Context{ - flags: NewFlagSet(), - unknownFlags: nil, - stdout: stdout, - stderr: stderr, - } -} - -func (ctx *Context) SetUnknownFlags(flags *FlagSet) { - ctx.unknownFlags = flags -} - -func (ctx *Context) IsHelp() bool { - return ctx.help -} - -func (ctx *Context) Command() *Command { - return ctx.command -} - -func (ctx *Context) Completion() *Completion { - return ctx.completion -} - -func (ctx *Context) Flags() *FlagSet { - return ctx.flags -} - -func (ctx *Context) Stdout() io.Writer { - return ctx.stdout -} - -func (ctx *Context) Stderr() io.Writer { - return ctx.stderr -} - -func (ctx *Context) UnknownFlags() *FlagSet { - return ctx.unknownFlags -} - -func (ctx *Context) SetCompletion(completion *Completion) { - ctx.completion = completion -} - -// Before go into the sub command, we need traverse flags and merge with parent -func (ctx *Context) EnterCommand(cmd *Command) { - ctx.command = cmd - if !cmd.EnableUnknownFlag { - ctx.unknownFlags = nil - } else if ctx.unknownFlags == nil { - ctx.unknownFlags = NewFlagSet() - } - - ctx.flags = cmd.flags.mergeWith(ctx.flags, func(f *Flag) bool { - return f.Persistent - }) - ctx.flags.Add(NewHelpFlag()) -} - -func (ctx *Context) CheckFlags() error { - for _, f := range ctx.flags.Flags() { - if !f.IsAssigned() { - if f.Required { - return fmt.Errorf("missing flag --%s", f.Name) - } - } else { - if err := f.checkFields(); err != nil { - return err - } - if len(f.ExcludeWith) > 0 { - for _, es := range f.ExcludeWith { - if _, ok := ctx.flags.GetValue(es); ok { - return fmt.Errorf("flag --%s is exclusive with --%s", f.Name, es) - } - } - } - } - } - return nil -} - -func (ctx *Context) detectFlag(name string) (*Flag, error) { - flag := ctx.flags.Get(name) - - if flag != nil { - return flag, nil - } else if ctx.unknownFlags != nil { - return ctx.unknownFlags.AddByName(name) - } else { - return nil, NewInvalidFlagError(name, ctx) - } -} - -func (ctx *Context) detectFlagByShorthand(ch rune) (*Flag, error) { - flag := ctx.flags.GetByShorthand(ch) - if flag != nil { - return flag, nil - } - return nil, fmt.Errorf("unknown flag -%s", string(ch)) -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/errors.go b/vendor/github.com/aliyun/aliyun-cli/cli/errors.go deleted file mode 100644 index 00cb4e26..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/errors.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import "fmt" - -// If command.Execute return Noticeable error, print i18n Notice under error information -type ErrorWithTip interface { - GetTip(lang string) string -} - -type errorWithTip struct { - err error - tip string -} - -func NewErrorWithTip(err error, tipFormat string, args ...interface{}) error { - return &errorWithTip{ - err: err, - tip: fmt.Sprintf(tipFormat, args...), - } -} - -func (e *errorWithTip) Error() string { - return e.err.Error() -} - -func (e *errorWithTip) GetTip(lang string) string { - return e.tip -} - -// OUTPUT: -// Error: "'%s' is not a valid command -// -// {Hint} -type InvalidCommandError struct { - Name string - ctx *Context -} - -func NewInvalidCommandError(name string, ctx *Context) error { - return &InvalidCommandError{ - Name: name, - ctx: ctx, - } -} - -func (e *InvalidCommandError) Error() string { - return fmt.Sprintf("'%s' is not a vaild command", e.Name) -} - -func (e *InvalidCommandError) GetSuggestions() []string { - cmd := e.ctx.command - return cmd.GetSuggestions(e.Name) -} - -type InvalidFlagError struct { - Flag string - ctx *Context -} - -func NewInvalidFlagError(name string, ctx *Context) error { - return &InvalidFlagError{ - Flag: name, - ctx: ctx, - } -} - -func (e *InvalidFlagError) Error() string { - return fmt.Sprintf("invalid flag %s", e.Flag) -} - -func (e *InvalidFlagError) GetSuggestions() []string { - distance := e.ctx.command.GetSuggestDistance() - return e.ctx.Flags().GetSuggestions(e.Flag, distance) -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/exit_code.go b/vendor/github.com/aliyun/aliyun-cli/cli/exit_code.go deleted file mode 100644 index 39face43..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/exit_code.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import "os" - -var ( - withExitCode = true -) - -func EnableExitCode() { - withExitCode = true -} - -func DisableExitCode() { - withExitCode = false -} - -func Exit(code int) { - if withExitCode { - os.Exit(code) - } -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/flag.go b/vendor/github.com/aliyun/aliyun-cli/cli/flag.go deleted file mode 100644 index 52077fdf..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/flag.go +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "strconv" - - "github.com/aliyun/aliyun-cli/i18n" -) - -type AssignedMode int - -const ( - AssignedNone = AssignedMode(-1) - AssignedDefault = AssignedMode(0) - AssignedOnce = AssignedMode(1) - AssignedRepeatable = AssignedMode(9) -) - -type Flag struct { - // Name of flag --{Name} - Name string - - // Flag is the single characters - Shorthand rune - - // Message print with --help command - Short *i18n.Text - - // Message print with `help --flag` command - Long *i18n.Text - - // If DefaultValue is not "" and Required is true, if flag is not assign - // GetValue() will return DefaultValue, and IsAssigned() will be false - DefaultValue string - - // If Required is true, the flag must be assigned with `--flag value` or DefaultValue is not empty - Required bool - - // Enable flag has alias names - Aliases []string - - // Ref to AssignedMode - // `AssignedNone`: flag only appear with `--flag1` `--flag2` - // `AssignedDefault`: flag can appear with `--flag1` or `--flag1 value1` - // `AssignedOnce`: flag only appear with `--flag1 value1` - // `AssignedRepeatable`: flag can appear multi times sample: `--flag1 [v1] [v2] [v3] [field1=value1]`, use with Fields - AssignedMode AssignedMode - - // If Persistent is true, the flag can apply to child commands - Persistent bool - - // If Hidden is true, it will not appear in --help mode - Hidden bool - - // Using in FlagSet.GetByCategory()... - Category string - - // Use to validate flag is in correct format - Validate func(f *Flag) error - - // Flag can assigned with --flag field1=value1 field2=value2 value3 ... - // must used with AssignedMode=AssignedRepeatable - Fields []Field - - // Flag can't appear with other flags, use Flag.Name - ExcludeWith []string - - assigned bool - value string - values []string - // formation string -} - -// return true if flag appeared, either `--flag1` or `--flag1 value1` -func (f *Flag) IsAssigned() bool { - return f.assigned -} - -func (f *Flag) SetAssigned(istrue bool) { - f.assigned = istrue -} - -func (f *Flag) SetValue(value string) { - f.value = value -} - -// return flag value, if not assigned return f.DefaultValue -// -// for `AssignedMode == AssignedRepeatable`. Use GetValues() to get all values -func (f *Flag) GetValue() (string, bool) { - if f.IsAssigned() { - return f.value, true - } else if f.Required { - return f.DefaultValue, false - } else { - return "", false - } -} - -// for `AssignedMode == AssignedRepeatable` flag, return values -func (f *Flag) GetValues() []string { - return f.values -} - -func (f *Flag) SetValues(values []string) { - f.values = values -} - -// for `AssignedMode == AssignedRepeatable` flag, return fields, multiply assignable -// Sample: --output abc bbc acd bb=2 cc=3 -func (f *Flag) getField(key string) (*Field, bool) { - for i, field := range f.Fields { - if field.Key == key { - return &(f.Fields[i]), true - } - } - return nil, false -} - -// --flag field1=value1 -func (f *Flag) GetFieldValue(key string) (string, bool) { - if field, ok := f.getField(key); ok { - return field.getValue() - } - return "", false - -} - -func (f *Flag) GetFieldValues(key string) []string { - if field, ok := f.getField(key); ok { - return field.values - } - return make([]string, 0) - -} - -// return def if Flag is not assigned -func (f *Flag) GetStringOrDefault(def string) string { - if f == nil { - return def - } - if f.assigned { - return f.value - } - return def - -} - -// TODO: flag support integer validate -// return def if Flag is not assign or assign failed -func (f *Flag) GetIntegerOrDefault(def int) int { - if f == nil { - return def - } - if f.assigned { - if i, err := strconv.Atoi(f.value); err == nil { - return i - } - } - return def -} - -// get all appears forms, maybe {"--Name", "--Alias1", "-Shorthand"} -func (f *Flag) GetFormations() []string { - r := make([]string, 0) - if f.Name != "" { - r = append(r, "--"+f.Name) - } - for _, s := range f.Aliases { - r = append(r, "--"+s) - } - if f.Shorthand != 0 { - r = append(r, "-"+string(f.Shorthand)) - } - return r -} - -// if this flag is appeared set assigned = true -func (f *Flag) setIsAssigned() error { - if !f.assigned { - f.assigned = true - } else { - if f.AssignedMode != AssignedRepeatable { - return fmt.Errorf("--%s duplicated", f.Name) - } - } - return nil -} - -// return true, if this flag need assigned with values -func (f *Flag) needValue() bool { - switch f.AssignedMode { - case AssignedNone: - return false - case AssignedDefault: - return f.value == "" - case AssignedOnce: - return f.value == "" - case AssignedRepeatable: - return true - default: - panic(fmt.Errorf("unexpected Flag.AssignedMode %s", strconv.Itoa(int(f.AssignedMode)))) - } -} - -// make check valid -func (f *Flag) checkValid() { - if len(f.Fields) > 0 { - if f.AssignedMode != AssignedRepeatable { - panic(fmt.Errorf("flag %s with fields must use AssignedRepeatable", f.Name)) - } - } -} - -// validate flag value -func (f *Flag) validate() error { - if f.AssignedMode == AssignedOnce && f.value == "" { - return fmt.Errorf("--%s must be assigned with value", f.Name) - } - return nil -} - -// assign value -func (f *Flag) assign(v string) error { - if f.AssignedMode == AssignedNone { - return fmt.Errorf("flag --%s can't be assiged", f.Name) - } - - f.assigned = true - f.value = v - - if f.AssignedMode == AssignedRepeatable { - f.values = append(f.values, v) - if len(f.Fields) > 0 { - f.assignField(v) - } - } - return nil -} - -// assign field -func (f *Flag) assignField(s string) error { - if k, v, ok := SplitStringWithPrefix(s, "="); ok { - field, ok2 := f.getField(k) - if ok2 { - field.assign(v) - } else { - return fmt.Errorf("--%s can't assign with %s=", f.Name, k) - } - } else { - field, ok2 := f.getField("") - if ok2 { - field.assign(v) - } else { - return fmt.Errorf("--%s can't assign with value", f.Name) - } - } - return nil -} - -func (f *Flag) checkFields() error { - if len(f.Fields) == 0 { - return nil - } - for _, field := range f.Fields { - if err := field.check(); err != nil { - return fmt.Errorf("bad flag format --%s with field %s", f.Name, err) - } - } - return nil -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/flag_field.go b/vendor/github.com/aliyun/aliyun-cli/cli/flag_field.go deleted file mode 100644 index ed29e674..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/flag_field.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - - "github.com/aliyun/aliyun-cli/i18n" -) - -type Field struct { - // - // appear in `--flag key1=value1, key2=value2` - // if Key assigned with "", it can used with `--flag value1 value2` - Key string - - // - // if Required is true, this field must be assigned - Required bool - - // - // if Repeatable is true, this field can appear multiply times, eg: "--flag key1=value1 key2=value2" - Repeatable bool - - // - // if field not appear, use this value, not used with Required - DefaultValue string - - // - // Message show - Short *i18n.Text - - assigned bool - value string - values []string -} - -func (f *Field) assign(v string) { - f.assigned = true - f.value = v - f.values = append(f.values, v) -} - -func (f *Field) SetAssigned(istrue bool) { - f.assigned = istrue -} - -func (f *Field) SetValue(value string) { - f.value = value -} - -func (f *Field) getValue() (string, bool) { - if f.assigned { - return f.value, true - } else if f.DefaultValue != "" { - return f.DefaultValue, false - } else { - return "", false - } -} - -func (f *Field) check() error { - if f.Required && !f.assigned { - if f.Key != "" { - return fmt.Errorf("%s= required", f.Key) - } - return fmt.Errorf("value required") - - } - if !f.Repeatable && len(f.values) > 1 { - if f.Key != "" { - return fmt.Errorf("%s= duplicated", f.Key) - } - return fmt.Errorf("value duplicated") - - } - return nil -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/flag_set.go b/vendor/github.com/aliyun/aliyun-cli/cli/flag_set.go deleted file mode 100644 index 020036e2..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/flag_set.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "strings" -) - -type FlagSet struct { - // flags - flags []*Flag - // key: "--name" "-c" - index map[string]*Flag -} - -func NewFlagSet() *FlagSet { - return &FlagSet{ - flags: make([]*Flag, 0), - index: make(map[string]*Flag), - } -} - -// traverse all values -func (fs *FlagSet) Flags() []*Flag { - return fs.flags -} - -// call from user program, if flag duplicated, panic! -func (fs *FlagSet) Add(f *Flag) { - f.checkValid() - for _, s := range f.GetFormations() { - if _, ok := fs.index[s]; ok { - panic(fmt.Errorf("flag duplicated %s", string(s))) - } - fs.index[s] = f - } - fs.flags = append(fs.flags, f) -} - -// add by name, not support add by shorthand -func (fs *FlagSet) AddByName(name string) (*Flag, error) { - if _, ok := fs.index["--"+name]; ok { - return nil, fmt.Errorf("flag duplicated --%s", name) - } - f := &Flag{ - Name: name, - } - if strings.HasSuffix(name, "-FILE") { - f.Aliases = append(f.Aliases, strings.TrimSuffix(name, "-FILE")) - } - fs.Add(f) - return f, nil -} - -// get flag by name, sample --name -func (fs *FlagSet) Get(name string) *Flag { - if f, ok := fs.index["--"+name]; ok { - return f - } - return nil -} - -// get flag by shorthand, sample -a -func (fs *FlagSet) GetByShorthand(c rune) *Flag { - if f, ok := fs.index["-"+string(c)]; ok { - return f - } - return nil -} - -// get suggestions -func (fs *FlagSet) GetSuggestions(name string, distance int) []string { - sr := NewSuggester(name, distance) - for k := range fs.index { - sr.Apply(k) - } - ss := make([]string, 0) - ss = append(ss, sr.GetResults()...) - - return ss -} - -// get value by flag name, not recommended -func (fs *FlagSet) GetValue(name string) (string, bool) { - f := fs.Get(name) - if f == nil { - return "", false - } - return f.GetValue() -} - -// merge FlagSet with from -func (fs *FlagSet) mergeWith(from *FlagSet, applier func(f *Flag) bool) *FlagSet { - if from == nil { - return fs - } - r := NewFlagSet() - if fs != nil { - for _, f := range fs.flags { - r.Add(f) - } - } - for _, rv := range from.Flags() { - if applier(rv) { - r.put(rv) - } - } - return r -} - -// put flag, replace old value if duplicated -func (fs *FlagSet) put(f *Flag) { - - for _, lv := range fs.flags { - if lv == f { - return - } - } - fs.flags = append(fs.flags, f) - for _, s := range f.GetFormations() { - fs.index[s] = f - } -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/levenshtein.go b/vendor/github.com/aliyun/aliyun-cli/cli/levenshtein.go deleted file mode 100644 index 0e383762..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/levenshtein.go +++ /dev/null @@ -1,263 +0,0 @@ -// -// Copyright (c) 2013 Kilian Evang and contributors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// -// https://github.com/texttheater/golang-levenshtein -// -// This package implements the Levenshtein algorithm for computing the -// similarity between two strings. The central function is MatrixForStrings, -// which computes the Levenshtein matrix. The functions DistanceForMatrix, -// EditScriptForMatrix and RatioForMatrix read various interesting properties -// off the matrix. The package also provides the convenience functions -// DistanceForStrings, EditScriptForStrings and RatioForStrings for going -// directly from two strings to the property of interest. -// - -package cli - -import ( - "fmt" - "io" - "os" -) - -type EditOperation int - -const ( - Ins = iota - Del - Sub - Match -) - -type EditScript []EditOperation - -type MatchFunction func(rune, rune) bool - -type Options struct { - InsCost int - DelCost int - SubCost int - Matches MatchFunction -} - -// DefaultOptions is the default options: insertion cost is 1, deletion cost is -// 1, substitution cost is 2, and two runes match iff they are the same. -var DefaultOptions Options = Options{ - InsCost: 1, - DelCost: 1, - SubCost: 2, - Matches: func(sourceCharacter rune, targetCharacter rune) bool { - return sourceCharacter == targetCharacter - }, -} - -func (operation EditOperation) String() string { - if operation == Match { - return "match" - } else if operation == Ins { - return "ins" - } else if operation == Sub { - return "sub" - } - return "del" -} - -// DistanceForStrings returns the edit distance between source and target. -// -// It has a runtime proportional to len(source) * len(target) and memory use -// proportional to len(target). -func DistanceForStrings(source []rune, target []rune, op Options) int { - // Note: This algorithm is a specialization of MatrixForStrings. - // MatrixForStrings returns the full edit matrix. However, we only need a - // single value (see DistanceForMatrix) and the main loop of the algorithm - // only uses the current and previous row. As such we create a 2D matrix, - // but with height 2 (enough to store current and previous row). - height := len(source) + 1 - width := len(target) + 1 - matrix := make([][]int, 2) - - // Initialize trivial distances (from/to empty string). That is, fill - // the left column and the top row with row/column indices. - for i := 0; i < 2; i++ { - matrix[i] = make([]int, width) - matrix[i][0] = i - } - for j := 1; j < width; j++ { - matrix[0][j] = j - } - - // Fill in the remaining cells: for each prefix pair, choose the - // (edit history, operation) pair with the lowest cost. - for i := 1; i < height; i++ { - cur := matrix[i%2] - prev := matrix[(i-1)%2] - cur[0] = i - for j := 1; j < width; j++ { - delCost := prev[j] + op.DelCost - matchSubCost := prev[j-1] - if !op.Matches(source[i-1], target[j-1]) { - matchSubCost += op.SubCost - } - insCost := cur[j-1] + op.InsCost - cur[j] = min(delCost, min(matchSubCost, insCost)) - } - } - return matrix[(height-1)%2][width-1] -} - -// DistanceForMatrix reads the edit distance off the given Levenshtein matrix. -func DistanceForMatrix(matrix [][]int) int { - return matrix[len(matrix)-1][len(matrix[0])-1] -} - -// RatioForStrings returns the Levenshtein ratio for the given strings. The -// ratio is computed as follows: -// -// (sourceLength + targetLength - distance) / (sourceLength + targetLength) -func RatioForStrings(source []rune, target []rune, op Options) float64 { - matrix := MatrixForStrings(source, target, op) - return RatioForMatrix(matrix) -} - -// RatioForMatrix returns the Levenshtein ratio for the given matrix. The ratio -// is computed as follows: -// -// (sourceLength + targetLength - distance) / (sourceLength + targetLength) -func RatioForMatrix(matrix [][]int) float64 { - sourcelength := len(matrix) - 1 - targetlength := len(matrix[0]) - 1 - sum := sourcelength + targetlength - - if sum == 0 { - return 0 - } - - dist := DistanceForMatrix(matrix) - return float64(sum-dist) / float64(sum) -} - -// MatrixForStrings generates a 2-D array representing the dynamic programming -// table used by the Levenshtein algorithm, as described e.g. here: -// http://www.let.rug.nl/kleiweg/lev/ -// The reason for putting the creation of the table into a separate function is -// that it cannot only be used for reading of the edit distance between two -// strings, but also e.g. to backtrace an edit script that provides an -// alignment between the characters of both strings. -func MatrixForStrings(source []rune, target []rune, op Options) [][]int { - // Make a 2-D matrix. Rows correspond to prefixes of source, columns to - // prefixes of target. Cells will contain edit distances. - // Cf. http://www.let.rug.nl/~kleiweg/lev/levenshtein.html - height := len(source) + 1 - width := len(target) + 1 - matrix := make([][]int, height) - - // Initialize trivial distances (from/to empty string). That is, fill - // the left column and the top row with row/column indices. - for i := 0; i < height; i++ { - matrix[i] = make([]int, width) - matrix[i][0] = i - } - for j := 1; j < width; j++ { - matrix[0][j] = j - } - - // Fill in the remaining cells: for each prefix pair, choose the - // (edit history, operation) pair with the lowest cost. - for i := 1; i < height; i++ { - for j := 1; j < width; j++ { - delCost := matrix[i-1][j] + op.DelCost - matchSubCost := matrix[i-1][j-1] - if !op.Matches(source[i-1], target[j-1]) { - matchSubCost += op.SubCost - } - insCost := matrix[i][j-1] + op.InsCost - matrix[i][j] = min(delCost, min(matchSubCost, - insCost)) - } - } - //LogMatrix(source, target, matrix) - return matrix -} - -// EditScriptForStrings returns an optimal edit script to turn source into -// target. -func EditScriptForStrings(source []rune, target []rune, op Options) EditScript { - return backtrace(len(source), len(target), - MatrixForStrings(source, target, op), op) -} - -// EditScriptForMatrix returns an optimal edit script based on the given -// Levenshtein matrix. -func EditScriptForMatrix(matrix [][]int, op Options) EditScript { - return backtrace(len(matrix)-1, len(matrix[0])-1, matrix, op) -} - -// WriteMatrix writes a visual representation of the given matrix for the given -// strings to the given writer. -func WriteMatrix(source []rune, target []rune, matrix [][]int, writer io.Writer) { - fmt.Fprintf(writer, " ") - for _, targetRune := range target { - fmt.Fprintf(writer, " %c", targetRune) - } - fmt.Fprintf(writer, "\n") - fmt.Fprintf(writer, " %2d", matrix[0][0]) - for j := range target { - fmt.Fprintf(writer, " %2d", matrix[0][j+1]) - } - fmt.Fprintf(writer, "\n") - for i, sourceRune := range source { - fmt.Fprintf(writer, "%c %2d", sourceRune, matrix[i+1][0]) - for j := range target { - fmt.Fprintf(writer, " %2d", matrix[i+1][j+1]) - } - fmt.Fprintf(writer, "\n") - } -} - -// LogMatrix writes a visual representation of the given matrix for the given -// strings to os.Stderr. This function is deprecated, use -// WriteMatrix(source, target, matrix, os.Stderr) instead. -func LogMatrix(source []rune, target []rune, matrix [][]int) { - WriteMatrix(source, target, matrix, os.Stderr) -} - -func backtrace(i int, j int, matrix [][]int, op Options) EditScript { - if i > 0 && matrix[i-1][j]+op.DelCost == matrix[i][j] { - return append(backtrace(i-1, j, matrix, op), Del) - } - if j > 0 && matrix[i][j-1]+op.InsCost == matrix[i][j] { - return append(backtrace(i, j-1, matrix, op), Ins) - } - if i > 0 && j > 0 && matrix[i-1][j-1]+op.SubCost == matrix[i][j] { - return append(backtrace(i-1, j-1, matrix, op), Sub) - } - if i > 0 && j > 0 && matrix[i-1][j-1] == matrix[i][j] { - return append(backtrace(i-1, j-1, matrix, op), Match) - } - return []EditOperation{} -} - -func min(a int, b int) int { - if b < a { - return b - } - return a -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/output.go b/vendor/github.com/aliyun/aliyun-cli/cli/output.go deleted file mode 100644 index f215d2c3..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/output.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "io" - "os" -) - -var ( - defaultStdoutWriter = os.Stdout - defaultStderrWriter = os.Stderr -) - -func DefaultStdoutWriter() io.Writer { - return defaultStdoutWriter -} - -func DefaultStderrWriter() io.Writer { - return defaultStderrWriter -} - -func Print(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, a...) -} - -func Println(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, a...) -} - -func Printf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, a...) -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/parser.go b/vendor/github.com/aliyun/aliyun-cli/cli/parser.go deleted file mode 100644 index 802b72cf..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/parser.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "fmt" - "strings" -) - -type flagDetector interface { - detectFlag(name string) (*Flag, error) - detectFlagByShorthand(ch rune) (*Flag, error) -} - -type Parser struct { - current int - args []string - detector flagDetector - currentFlag *Flag -} - -func NewParser(args []string, detector flagDetector) *Parser { - return &Parser{ - args: args, - current: 0, - detector: detector, - currentFlag: nil, - } -} - -func (p *Parser) ReadNextArg() (arg string, more bool, err error) { - for { - arg, _, more, err = p.readNext() - if err != nil { - return - } - if !more { - return - } - if arg != "" { - return - } - } -} - -func (p *Parser) GetRemains() []string { - return p.args[p.current:] -} - -func (p *Parser) GetCurrent() int { - return p.current -} - -func (p *Parser) ReadAll() ([]string, error) { - r := make([]string, 0) - for { - arg, _, more, err := p.readNext() - if err != nil { - return r, err - } - if arg != "" { - r = append(r, arg) - } - if !more { - return r, nil - } - } -} - -func (p *Parser) readNext() (arg string, flag *Flag, more bool, err error) { - if p.current >= len(p.args) { - more = false - return - } - s := p.args[p.current] - p.current++ - more = true - - value := "" - flag, value, err = p.parseCommandArg(s) - if err != nil { - return - } - if flag != nil { - err = flag.setIsAssigned() - if err != nil { - return - } - } - - // fmt.Printf(">>> current=%v\n flag=%v\n value=%s\n err=%s\n", p.currentFlag, flag, value, err) - if flag == nil { // parse with value xxxx - if p.currentFlag != nil { // value need to feed to previous flag xxx - err = p.currentFlag.assign(value) - if err != nil { - return - } - if !p.currentFlag.needValue() { // if current flag is feeds close it - // fmt.Printf("$$$ clear %s\n", p.currentFlag.AssignedMode) - p.currentFlag = nil - } - } else { - arg = value // this is a arg - } - } else { // parse with flag --xxx or -x - if p.currentFlag != nil { - err = p.currentFlag.validate() - if err != nil { - return - } - p.currentFlag = nil - } - - if value != "" { // pattern --xx=aa, -x:aa, -xxx=bb - err = flag.assign(value) - if err != nil { - return - } - } else { // pattern --xx -- yy - if flag.needValue() { - p.currentFlag = flag - } - } - } - return -} - -func (p *Parser) parseCommandArg(s string) (flag *Flag, value string, err error) { - prefix, v, ok := SplitStringWithPrefix(s, "=:") - - if ok { - value = v - } - - if strings.HasPrefix(prefix, "--") { - if len(prefix) > 2 { - flag, err = p.detector.detectFlag(prefix[2:]) - } else { - err = fmt.Errorf("not support '--' in command line") - } - } else if strings.HasPrefix(prefix, "-") { - if len(prefix) == 2 { - flag, err = p.detector.detectFlagByShorthand(rune(prefix[1])) - } else { - err = fmt.Errorf("not support flag form %s", prefix) - } - } else { - value = s - } - return -} - -// SplitStringWithPrefix TODO can use function string.SplitN to replace -func SplitStringWithPrefix(s string, splitters string) (string, string, bool) { - i := strings.IndexAny(s, splitters) - if i < 0 { - return s, "", false - } - return s[:i], s[i+1:], true - -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/suggestion.go b/vendor/github.com/aliyun/aliyun-cli/cli/suggestion.go deleted file mode 100644 index 56a0518c..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/suggestion.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -const DefaultSuggestDistance = 2 - -func CalculateStringDistance(source string, target string) int { - return DistanceForStrings([]rune(source), []rune(target), DefaultOptions) -} - -// error with suggestions -type SuggestibleError interface { - GetSuggestions() []string -} - -func PrintSuggestions(ctx *Context, lang string, ss []string) { - if len(ss) > 0 { - Noticef(ctx.Stdout(), "\nDid you mean:\n") - for _, s := range ss { - Noticef(ctx.Stdout(), " %s\n", s) - } - } -} - -// helper class for Suggester -type Suggester struct { - suggestFor string - distance int - results []string -} - -func NewSuggester(v string, distance int) *Suggester { - return &Suggester{ - suggestFor: v, - distance: distance, - } -} - -func (a *Suggester) Apply(s string) { - d := CalculateStringDistance(a.suggestFor, s) - if d <= a.distance { - if d < a.distance { - a.distance = d - a.results = make([]string, 0) - } - a.results = append(a.results, s) - } -} - -func (a *Suggester) GetResults() []string { - return a.results -} diff --git a/vendor/github.com/aliyun/aliyun-cli/cli/version.go b/vendor/github.com/aliyun/aliyun-cli/cli/version.go deleted file mode 100644 index 83a87b33..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/cli/version.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package cli - -import ( - "strings" - - "github.com/aliyun/aliyun-cli/i18n" -) - -// This variable is replaced in compile time -// `-ldflags "-X 'github.com/aliyun/aliyun-cli/cli.Version=${VERSION}'"` -var ( - Version = "0.0.1" -) - -func GetVersion() string { - return strings.Replace(Version, " ", "-", -1) -} - -func NewVersionCommand() *Command { - return &Command{ - Name: "version", - Short: i18n.T("print current version", "打印当前版本号"), - Hidden: true, - Run: func(ctx *Context, args []string) error { - Printf(ctx.Stdout(), "%s\n", Version) - return nil - }, - } -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/configuration.go b/vendor/github.com/aliyun/aliyun-cli/config/configuration.go deleted file mode 100644 index 5ab6071e..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/configuration.go +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "encoding/json" - "fmt" - "os" - "runtime" - - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/util" -) - -const ( - configPath = "/.aliyun" - configFile = "config.json" - DefaultConfigProfileName = "default" -) - -type Configuration struct { - CurrentProfile string `json:"current"` - Profiles []Profile `json:"profiles"` - MetaPath string `json:"meta_path"` - //Plugins []Plugin `json:"plugin"` -} - -var hookGetHomePath = func(fn func() string) func() string { - return fn -} - -func NewConfiguration() *Configuration { - return &Configuration{ - CurrentProfile: DefaultConfigProfileName, - Profiles: []Profile{ - NewProfile(DefaultConfigProfileName), - }, - } -} - -func (c *Configuration) NewProfile(pn string) Profile { - p, ok := c.GetProfile(pn) - if !ok { - p = NewProfile(pn) - c.PutProfile(p) - } - return p -} - -func (c *Configuration) GetProfile(pn string) (Profile, bool) { - for _, p := range c.Profiles { - if p.Name == pn { - return p, true - } - } - return Profile{Name: pn}, false -} - -func (c *Configuration) GetCurrentProfile(ctx *cli.Context) Profile { - profileName := ProfileFlag(ctx.Flags()).GetStringOrDefault(c.CurrentProfile) - if profileName == "" || profileName == "default" { - if v := util.GetFromEnv("ALIBABACLOUD_PROFILE", "ALIBABA_CLOUD_PROFILE", "ALICLOUD_PROFILE"); v != "" { - profileName = v - } - } - - p, _ := c.GetProfile(profileName) - p.OverwriteWithFlags(ctx) - return p -} - -func (c *Configuration) PutProfile(profile Profile) { - for i, p := range c.Profiles { - if p.Name == profile.Name { - c.Profiles[i] = profile - return - } - } - c.Profiles = append(c.Profiles, profile) -} - -func LoadCurrentProfile() (Profile, error) { - return LoadProfile(GetConfigPath()+"/"+configFile, "") -} - -func LoadProfile(path string, name string) (Profile, error) { - var p Profile - config, err := hookLoadConfiguration(LoadConfiguration)(path) - if err != nil { - return p, fmt.Errorf("init config failed %v", err) - } - if name == "" { - name = config.CurrentProfile - } - p, ok := config.GetProfile(name) - p.parent = config - if !ok { - return p, fmt.Errorf("unknown profile %s, run configure to check", name) - } - return p, nil -} - -func getConfigurePath(ctx *cli.Context) (currentPath string) { - if path, ok := ConfigurePathFlag(ctx.Flags()).GetValue(); ok { - currentPath = path - } else { - currentPath = GetConfigPath() + "/" + configFile - } - return -} - -func getProfileName(ctx *cli.Context) (name string) { - if name, ok := ProfileFlag(ctx.Flags()).GetValue(); ok { - return name - } else if profileNameInEnv := util.GetFromEnv("ALIBABACLOUD_PROFILE", "ALIBABA_CLOUD_PROFILE", "ALICLOUD_PROFILE"); profileNameInEnv != "" { - return profileNameInEnv - } - - return "" -} - -func LoadProfileWithContext(ctx *cli.Context) (profile Profile, err error) { - if util.GetFromEnv("ALIBABA_CLOUD_IGNORE_PROFILE", "ALIBABACLOUD_IGNORE_PROFILE") == "TRUE" { - profile = NewProfile("default") - profile.RegionId = "cn-hangzhou" - } else { - currentPath := getConfigurePath(ctx) - profileName := getProfileName(ctx) - profile, err = LoadProfile(currentPath, profileName) - if err != nil { - return - } - } - - // Load from flags - profile.OverwriteWithFlags(ctx) - err = profile.Validate() - return -} - -func LoadConfiguration(path string) (conf *Configuration, err error) { - _, statErr := os.Stat(path) - if os.IsNotExist(statErr) { - conf, err = MigrateLegacyConfiguration() - if err != nil { - return - } - - if conf != nil { - err = SaveConfiguration(conf) - if err != nil { - err = fmt.Errorf("save failed %v", err) - return - } - return - } - conf = NewConfiguration() - return - } - - bytes, err := os.ReadFile(path) - if err != nil { - err = fmt.Errorf("reading config from '%s' failed %v", path, err) - return - } - - conf, err = NewConfigFromBytes(bytes) - return -} - -func SaveConfiguration(config *Configuration) (err error) { - // fmt.Printf("conf %v\n", config) - bytes, err := json.MarshalIndent(config, "", "\t") - if err != nil { - return - } - path := GetConfigPath() + "/" + configFile - err = os.WriteFile(path, bytes, 0600) - return -} - -func NewConfigFromBytes(bytes []byte) (conf *Configuration, err error) { - conf = NewConfiguration() - err = json.Unmarshal(bytes, conf) - return -} - -func GetConfigPath() string { - path := hookGetHomePath(GetHomePath)() + configPath - if _, err := os.Stat(path); os.IsNotExist(err) { - err = os.MkdirAll(path, 0755) - if err != nil { - panic(err) - } - } - return path -} - -func GetHomePath() string { - if runtime.GOOS == "windows" { - home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") - if home == "" { - home = os.Getenv("USERPROFILE") - } - return home - } - return os.Getenv("HOME") -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/configure.go b/vendor/github.com/aliyun/aliyun-cli/config/configure.go deleted file mode 100644 index 24e67999..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/configure.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "bufio" - "fmt" - "io" - "os" - "strconv" - "strings" - - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/i18n" -) - -var hookLoadConfiguration = func(fn func(path string) (*Configuration, error)) func(path string) (*Configuration, error) { - return fn -} - -var hookSaveConfiguration = func(fn func(config *Configuration) error) func(config *Configuration) error { - return fn -} - -var stdin io.Reader = os.Stdin - -func loadConfiguration() (*Configuration, error) { - return hookLoadConfiguration(LoadConfiguration)(GetConfigPath() + "/" + configFile) -} - -func NewConfigureCommand() *cli.Command { - c := &cli.Command{ - Name: "configure", - Short: i18n.T( - "configure credential and settings", - "配置身份认证和其他信息"), - Usage: "configure --mode {AK|RamRoleArn|EcsRamRole|OIDC|External|CredentialsURI|ChainableRamRoleArn} --profile ", - Run: func(ctx *cli.Context, args []string) error { - if len(args) > 0 { - return cli.NewInvalidCommandError(args[0], ctx) - } - profileName, _ := ProfileFlag(ctx.Flags()).GetValue() - mode, _ := ModeFlag(ctx.Flags()).GetValue() - return doConfigure(ctx, profileName, mode) - }, - } - - c.AddSubCommand(NewConfigureGetCommand()) - c.AddSubCommand(NewConfigureSetCommand()) - c.AddSubCommand(NewConfigureListCommand()) - c.AddSubCommand(NewConfigureDeleteCommand()) - c.AddSubCommand(NewConfigureSwitchCommand()) - return c -} - -func doConfigure(ctx *cli.Context, profileName string, mode string) error { - w := ctx.Stdout() - - conf, err := loadConfiguration() - if err != nil { - return err - } - - if profileName == "" { - if conf.CurrentProfile == "" { - profileName = "default" - } else { - profileName = conf.CurrentProfile - originMode := string(conf.GetCurrentProfile(ctx).Mode) - if mode == "" { - mode = originMode - } else if mode != originMode { - cli.Printf(w, "Warning: You are changing the authentication type of profile '%s' from '%s' to '%s'\n", profileName, originMode, mode) - } - } - } - if mode == "" { - mode = "AK" - } - cp, ok := conf.GetProfile(profileName) - if !ok { - cp = conf.NewProfile(profileName) - } - - cli.Printf(w, "Configuring profile '%s' in '%s' authenticate mode...\n", profileName, mode) - - if mode != "" { - switch AuthenticateMode(mode) { - case AK: - cp.Mode = AK - configureAK(w, &cp) - case StsToken: - cp.Mode = StsToken - configureStsToken(w, &cp) - case RamRoleArn: - cp.Mode = RamRoleArn - configureRamRoleArn(w, &cp) - case EcsRamRole: - cp.Mode = EcsRamRole - configureEcsRamRole(w, &cp) - case RamRoleArnWithEcs: - cp.Mode = RamRoleArnWithEcs - configureRamRoleArnWithEcs(w, &cp) - case ChainableRamRoleArn: - cp.Mode = ChainableRamRoleArn - configureChainableRamRoleArn(w, &cp) - case RsaKeyPair: - cp.Mode = RsaKeyPair - configureRsaKeyPair(w, &cp) - case External: - cp.Mode = External - configureExternal(w, &cp) - case CredentialsURI: - cp.Mode = CredentialsURI - configureCredentialsURI(w, &cp) - case OIDC: - cp.Mode = OIDC - configureOIDC(w, &cp) - default: - return fmt.Errorf("unexcepted authenticate mode: %s", mode) - } - } else { - configureAK(w, &cp) - } - - // - // configure common - cli.Printf(w, "Default Region Id [%s]: ", cp.RegionId) - cp.RegionId = ReadInput(cp.RegionId) - cli.Printf(w, "Default Output Format [%s]: json (Only support json)\n", cp.OutputFormat) - - // cp.OutputFormat = ReadInput(cp.OutputFormat) - cp.OutputFormat = "json" - - cli.Printf(w, "Default Language [zh|en] %s: ", cp.Language) - - cp.Language = ReadInput(cp.Language) - if cp.Language != "zh" && cp.Language != "en" { - cp.Language = i18n.GetLanguage() - } - - //fmt.Printf("User site: [china|international|japan] %s", cp.Site) - //cp.Site = ReadInput(cp.Site) - - cli.Printf(w, "Saving profile[%s] ...", profileName) - - conf.PutProfile(cp) - conf.CurrentProfile = cp.Name - err = hookSaveConfiguration(SaveConfiguration)(conf) - // cp 要在下文的 DoHello 中使用,所以 需要建立 parent 的关系 - cp.parent = conf - - if err != nil { - return err - } - cli.Printf(w, "Done.\n") - - DoHello(ctx, &cp) - return nil -} - -func configureAK(w io.Writer, cp *Profile) error { - cli.Printf(w, "Access Key Id [%s]: ", MosaicString(cp.AccessKeyId, 3)) - cp.AccessKeyId = ReadInput(cp.AccessKeyId) - cli.Printf(w, "Access Key Secret [%s]: ", MosaicString(cp.AccessKeySecret, 3)) - cp.AccessKeySecret = ReadInput(cp.AccessKeySecret) - return nil -} - -func configureStsToken(w io.Writer, cp *Profile) error { - err := configureAK(w, cp) - if err != nil { - return err - } - cli.Printf(w, "Sts Token [%s]: ", cp.StsToken) - cp.StsToken = ReadInput(cp.StsToken) - return nil -} - -func configureRamRoleArn(w io.Writer, cp *Profile) error { - err := configureAK(w, cp) - if err != nil { - return err - } - cli.Printf(w, "Sts Region [%s]: ", cp.StsRegion) - cp.StsRegion = ReadInput(cp.StsRegion) - cli.Printf(w, "Ram Role Arn [%s]: ", cp.RamRoleArn) - cp.RamRoleArn = ReadInput(cp.RamRoleArn) - cli.Printf(w, "Role Session Name [%s]: ", cp.RoleSessionName) - cp.RoleSessionName = ReadInput(cp.RoleSessionName) - if cp.ExpiredSeconds == 0 { - cp.ExpiredSeconds = 900 - } - cli.Printf(w, "Expired Seconds [%v]: ", cp.ExpiredSeconds) - cp.ExpiredSeconds, _ = strconv.Atoi(ReadInput(strconv.Itoa(cp.ExpiredSeconds))) - return nil -} - -func configureEcsRamRole(w io.Writer, cp *Profile) error { - cli.Printf(w, "Ecs Ram Role [%s]: ", cp.RamRoleName) - cp.RamRoleName = ReadInput(cp.RamRoleName) - return nil -} - -func configureRamRoleArnWithEcs(w io.Writer, cp *Profile) error { - cli.Printf(w, "Ecs Ram Role [%s]: ", cp.RamRoleName) - cp.RamRoleName = ReadInput(cp.RamRoleName) - cli.Printf(w, "Sts Region [%s]: ", cp.StsRegion) - cp.StsRegion = ReadInput(cp.StsRegion) - cli.Printf(w, "Ram Role Arn [%s]: ", cp.RamRoleArn) - cp.RamRoleArn = ReadInput(cp.RamRoleArn) - cli.Printf(w, "Role Session Name [%s]: ", cp.RoleSessionName) - cp.RoleSessionName = ReadInput(cp.RoleSessionName) - if cp.ExpiredSeconds == 0 { - cp.ExpiredSeconds = 900 - } - cli.Printf(w, "Expired Seconds [%v]: ", cp.ExpiredSeconds) - cp.ExpiredSeconds, _ = strconv.Atoi(ReadInput(strconv.Itoa(cp.ExpiredSeconds))) - return nil -} - -func configureChainableRamRoleArn(w io.Writer, cp *Profile) error { - cli.Printf(w, "Source Profile [%s]: ", cp.SourceProfile) - cp.SourceProfile = ReadInput(cp.SourceProfile) - cli.Printf(w, "Sts Region [%s]: ", cp.StsRegion) - cp.StsRegion = ReadInput(cp.StsRegion) - cli.Printf(w, "Ram Role Arn [%s]: ", cp.RamRoleArn) - cp.RamRoleArn = ReadInput(cp.RamRoleArn) - cli.Printf(w, "Role Session Name [%s]: ", cp.RoleSessionName) - cp.RoleSessionName = ReadInput(cp.RoleSessionName) - if cp.ExpiredSeconds == 0 { - cp.ExpiredSeconds = 900 - } - cli.Printf(w, "Expired Seconds [%v]: ", cp.ExpiredSeconds) - cp.ExpiredSeconds, _ = strconv.Atoi(ReadInput(strconv.Itoa(cp.ExpiredSeconds))) - return nil -} - -func configureRsaKeyPair(w io.Writer, cp *Profile) error { - cli.Printf(w, "Rsa Private Key File: ") - keyFile := ReadInput("") - buf, err := os.ReadFile(keyFile) - if err != nil { - return fmt.Errorf("read key file %s failed %v", keyFile, err) - } - cp.PrivateKey = string(buf) - cli.Printf(w, "Rsa Key Pair Name: ") - cp.KeyPairName = ReadInput("") - cp.ExpiredSeconds = 900 - return nil -} - -func configureExternal(w io.Writer, cp *Profile) error { - cli.Printf(w, "Process Command [%s]: ", cp.ProcessCommand) - cp.ProcessCommand = ReadInput(cp.ProcessCommand) - return nil -} - -func configureCredentialsURI(w io.Writer, cp *Profile) error { - cli.Printf(w, "Credentials URI [%s]: ", cp.CredentialsURI) - cp.CredentialsURI = ReadInput(cp.CredentialsURI) - return nil -} - -func configureOIDC(w io.Writer, cp *Profile) error { - cli.Printf(w, "OIDC Provider ARN [%s]: ", cp.OIDCProviderARN) - cp.OIDCProviderARN = ReadInput(cp.OIDCProviderARN) - cli.Printf(w, "OIDC Token File [%s]: ", cp.OIDCTokenFile) - cp.OIDCTokenFile = ReadInput(cp.OIDCTokenFile) - cli.Printf(w, "RAM Role ARN [%s]: ", cp.RamRoleArn) - cp.RamRoleArn = ReadInput(cp.RamRoleArn) - cli.Printf(w, "Role Session Name [%s]: ", cp.RoleSessionName) - cp.RoleSessionName = ReadInput(cp.RoleSessionName) - cp.ExpiredSeconds = 3600 - return nil -} - -func ReadInput(defaultValue string) string { - var s string - scanner := bufio.NewScanner(stdin) - if scanner.Scan() { - s = scanner.Text() - } - if s == "" { - return defaultValue - } - return strings.TrimSpace(s) -} - -func MosaicString(s string, lastChars int) string { - r := len(s) - lastChars - if r > 0 { - return strings.Repeat("*", r) + s[r:] - } else { - return strings.Repeat("*", len(s)) - } -} - -func GetLastChars(s string, lastChars int) string { - r := len(s) - lastChars - if r > 0 { - return s[r:] - } else { - return strings.Repeat("*", len(s)) - } -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/configure_delete.go b/vendor/github.com/aliyun/aliyun-cli/config/configure_delete.go deleted file mode 100644 index ce9a8765..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/configure_delete.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/i18n" -) - -func NewConfigureDeleteCommand() *cli.Command { - return &cli.Command{ - Name: "delete", - Usage: "delete --profile ", - Short: i18n.T("delete the specified profile", "删除指定配置"), - Run: func(c *cli.Context, args []string) error { - profileName, ok := ProfileFlag(c.Flags()).GetValue() - if !ok { - cli.Errorf(c.Stderr(), "missing --profile \n") - cli.Noticef(c.Stderr(), "\nusage:\n aliyun configure delete --profile \n") - return nil - } - doConfigureDelete(c, profileName) - return nil - }, - } -} - -func doConfigureDelete(ctx *cli.Context, profileName string) { - conf, err := loadConfiguration() - if err != nil { - cli.Errorf(ctx.Stderr(), "ERROR: load configure failed: %v\n", err) - } - deleted := false - r := make([]Profile, 0) - for _, p := range conf.Profiles { - if p.Name != profileName { - r = append(r, p) - } else { - deleted = true - } - } - - if !deleted { - cli.Errorf(ctx.Stderr(), "Error: configuration profile `%s` not found\n", profileName) - return - } - - conf.Profiles = r - if conf.CurrentProfile == profileName { - if len(conf.Profiles) > 0 { - conf.CurrentProfile = conf.Profiles[0].Name - } else { - conf.CurrentProfile = DefaultConfigProfileName - } - } - - err = hookSaveConfiguration(SaveConfiguration)(conf) - if err != nil { - cli.Errorf(ctx.Stderr(), "Error: save configuration failed %s\n", err) - } -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/configure_get.go b/vendor/github.com/aliyun/aliyun-cli/config/configure_get.go deleted file mode 100644 index 3d8d5ba2..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/configure_get.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "encoding/json" - "reflect" - - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/i18n" -) - -func NewConfigureGetCommand() *cli.Command { - return &cli.Command{ - Name: "get", - Short: i18n.T( - "print configuration values", - "打印配置信息"), - Usage: "get [profile] [language] ...", - Run: func(c *cli.Context, args []string) error { - doConfigureGet(c, args) - return nil - }, - } -} - -func doConfigureGet(c *cli.Context, args []string) { - config, err := loadConfiguration() - if err != nil { - cli.Errorf(c.Stderr(), "load configuration failed %s", err) - cli.Printf(c.Stderr(), "\n") - return - } - - profile := config.GetCurrentProfile(c) - - if pn, ok := ProfileFlag(c.Flags()).GetValue(); ok { - profile, ok = config.GetProfile(pn) - if !ok { - cli.Errorf(c.Stderr(), "profile %s not found!", pn) - cli.Printf(c.Stderr(), "\n") - return - } - } - - if len(args) == 0 && !reflect.DeepEqual(profile, Profile{}) { - data, err := json.MarshalIndent(profile, "", "\t") - if err != nil { - cli.Printf(c.Stderr(), "ERROR:"+err.Error()) - cli.Printf(c.Stderr(), "\n") - return - } - cli.Println(c.Stdout(), string(data)) - cli.Printf(c.Stdout(), "\n") - return - } - - for _, arg := range args { - switch arg { - case ProfileFlagName: - cli.Printf(c.Stdout(), "profile=%s\n", profile.Name) - case ModeFlagName: - cli.Printf(c.Stdout(), "mode=%s\n", profile.Mode) - case AccessKeyIdFlagName: - cli.Printf(c.Stdout(), "access-key-id=%s\n", MosaicString(profile.AccessKeyId, 3)) - case AccessKeySecretFlagName: - cli.Printf(c.Stdout(), "access-key-secret=%s\n", MosaicString(profile.AccessKeySecret, 3)) - case StsTokenFlagName: - cli.Printf(c.Stdout(), "sts-token=%s\n", profile.StsToken) - case StsRegionFlagName: - cli.Printf(c.Stdout(), "sts-region=%s\n", profile.StsRegion) - case RamRoleNameFlagName: - cli.Printf(c.Stdout(), "ram-role-name=%s\n", profile.RamRoleName) - case RamRoleArnFlagName: - cli.Printf(c.Stdout(), "ram-role-arn=%s\n", profile.RamRoleArn) - case RoleSessionNameFlagName: - cli.Printf(c.Stdout(), "role-session-name=%s\n", profile.RoleSessionName) - case KeyPairNameFlagName: - cli.Printf(c.Stdout(), "key-pair-name=%s\n", profile.KeyPairName) - case PrivateKeyFlagName: - cli.Printf(c.Stdout(), "private-key=%s\n", profile.PrivateKey) - case RegionFlagName: - cli.Printf(c.Stdout(), profile.RegionId) - case LanguageFlagName: - cli.Printf(c.Stdout(), "language=%s\n", profile.Language) - } - } - - cli.Printf(c.Stdout(), "\n") -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/configure_list.go b/vendor/github.com/aliyun/aliyun-cli/config/configure_list.go deleted file mode 100644 index 18616586..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/configure_list.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "fmt" - "io" - "text/tabwriter" - - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/i18n" -) - -func NewConfigureListCommand() *cli.Command { - return &cli.Command{ - Name: "list", - Usage: "list", - Short: i18n.T("list all config profile", "列出所有配置集"), - Run: func(c *cli.Context, args []string) error { - doConfigureList(c.Stdout()) - return nil - }, - } -} - -func doConfigureList(w io.Writer) { - conf, err := loadConfiguration() - if err != nil { - cli.Errorf(w, "ERROR: load configure failed: %v\n", err) - } - tw := tabwriter.NewWriter(w, 8, 0, 1, ' ', 0) - fmt.Fprint(tw, "Profile\t| Credential \t| Valid\t| Region\t| Language\n") - fmt.Fprint(tw, "---------\t| ------------------\t| -------\t| ----------------\t| --------\n") - for _, pf := range conf.Profiles { - name := pf.Name - if name == conf.CurrentProfile { - name = name + " *" - } - err := pf.Validate() - valid := "Valid" - if err != nil { - valid = "Invalid" - } - - cred := "" - switch pf.Mode { - case AK: - cred = "AK:" + "***" + GetLastChars(pf.AccessKeyId, 3) - case StsToken: - cred = "StsToken:" + "***" + GetLastChars(pf.AccessKeyId, 3) - case RamRoleArn: - cred = "RamRoleArn:" + "***" + GetLastChars(pf.AccessKeyId, 3) - case EcsRamRole: - cred = "EcsRamRole:" + pf.RamRoleName - case RamRoleArnWithEcs: - cred = "arn:" + "***" + GetLastChars(pf.AccessKeyId, 3) - case ChainableRamRoleArn: - cred = "ChainableRamRoleArn:" + pf.SourceProfile + ":" + pf.RamRoleArn - case RsaKeyPair: - cred = "RsaKeyPair:" + pf.KeyPairName - case External: - cred = "ProcessCommand:" + pf.ProcessCommand - case CredentialsURI: - cred = "CredentialsURI:" + pf.CredentialsURI - case OIDC: - cred = "OIDC:" + "***" + GetLastChars(pf.OIDCProviderARN, 5) + "@***" + GetLastChars(pf.OIDCTokenFile, 5) + "@" + pf.RamRoleArn - } - fmt.Fprintf(tw, "%s\t| %s\t| %s\t| %s\t| %s\n", name, cred, valid, pf.RegionId, pf.Language) - } - tw.Flush() -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/configure_set.go b/vendor/github.com/aliyun/aliyun-cli/config/configure_set.go deleted file mode 100644 index 7b7e64ee..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/configure_set.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "io" - - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/i18n" -) - -func NewConfigureSetCommand() *cli.Command { - cmd := &cli.Command{ - Name: "set", - Short: i18n.T( - "set config in non interactive mode", - "使用非交互式方式进行配置"), - Usage: "set [--profile ] [--language {en|zh}] ...", - Run: func(c *cli.Context, args []string) error { - doConfigureSet(c.Stdout(), c.Flags()) - return nil - }, - } - - AddFlags(cmd.Flags()) - - return cmd -} - -func doConfigureSet(w io.Writer, flags *cli.FlagSet) { - config, err := loadConfiguration() - if err != nil { - cli.Errorf(w, "load configuration failed %s", err) - return - } - - profileName, ok := ProfileFlag(flags).GetValue() - if !ok { - profileName = config.CurrentProfile - } - - profile, ok := config.GetProfile(profileName) - if !ok { - profile = NewProfile(profileName) - } - - path, ok := ConfigurePathFlag(flags).GetValue() - if ok { - profile, err = LoadProfile(path, profileName) - if err != nil { - cli.Errorf(w, "load configuration file failed %s", err) - return - } - } - - mode, ok := ModeFlag(flags).GetValue() - if ok { - profile.Mode = AuthenticateMode(mode) - } else { - if profile.Mode == "" { - profile.Mode = AK - } - } - - switch profile.Mode { - case AK: - profile.AccessKeyId = AccessKeyIdFlag(flags).GetStringOrDefault(profile.AccessKeyId) - profile.AccessKeySecret = AccessKeySecretFlag(flags).GetStringOrDefault(profile.AccessKeySecret) - case StsToken: - profile.AccessKeyId = AccessKeyIdFlag(flags).GetStringOrDefault(profile.AccessKeyId) - profile.AccessKeySecret = AccessKeySecretFlag(flags).GetStringOrDefault(profile.AccessKeySecret) - profile.StsToken = StsTokenFlag(flags).GetStringOrDefault(profile.StsToken) - case RamRoleArn: - profile.AccessKeyId = AccessKeyIdFlag(flags).GetStringOrDefault(profile.AccessKeyId) - profile.AccessKeySecret = AccessKeySecretFlag(flags).GetStringOrDefault(profile.AccessKeySecret) - profile.RamRoleArn = RamRoleArnFlag(flags).GetStringOrDefault(profile.RamRoleArn) - profile.RoleSessionName = RoleSessionNameFlag(flags).GetStringOrDefault(profile.RoleSessionName) - profile.ExpiredSeconds = ExpiredSecondsFlag(flags).GetIntegerOrDefault(profile.ExpiredSeconds) - case EcsRamRole: - profile.RamRoleName = RamRoleNameFlag(flags).GetStringOrDefault(profile.RamRoleName) - case RamRoleArnWithEcs: - profile.RamRoleName = RamRoleNameFlag(flags).GetStringOrDefault(profile.RamRoleName) - profile.RamRoleArn = RamRoleArnFlag(flags).GetStringOrDefault(profile.RamRoleArn) - profile.RoleSessionName = RoleSessionNameFlag(flags).GetStringOrDefault(profile.RoleSessionName) - profile.ExpiredSeconds = ExpiredSecondsFlag(flags).GetIntegerOrDefault(profile.ExpiredSeconds) - case ChainableRamRoleArn: - profile.SourceProfile = SourceProfileFlag(flags).GetStringOrDefault(profile.SourceProfile) - profile.RamRoleArn = RamRoleArnFlag(flags).GetStringOrDefault(profile.RamRoleArn) - profile.RoleSessionName = RoleSessionNameFlag(flags).GetStringOrDefault(profile.RoleSessionName) - profile.ExpiredSeconds = ExpiredSecondsFlag(flags).GetIntegerOrDefault(profile.ExpiredSeconds) - case RsaKeyPair: - profile.PrivateKey = PrivateKeyFlag(flags).GetStringOrDefault(profile.PrivateKey) - profile.KeyPairName = KeyPairNameFlag(flags).GetStringOrDefault(profile.KeyPairName) - case External: - profile.ProcessCommand = ProcessCommandFlag(flags).GetStringOrDefault(profile.ProcessCommand) - case OIDC: - profile.OIDCProviderARN = OIDCProviderARNFlag(flags).GetStringOrDefault(profile.OIDCProviderARN) - profile.OIDCTokenFile = OIDCTokenFileFlag(flags).GetStringOrDefault(profile.OIDCTokenFile) - profile.RamRoleArn = RamRoleArnFlag(flags).GetStringOrDefault(profile.RamRoleArn) - profile.RoleSessionName = RoleSessionNameFlag(flags).GetStringOrDefault(profile.RoleSessionName) - profile.ExpiredSeconds = ExpiredSecondsFlag(flags).GetIntegerOrDefault(profile.ExpiredSeconds) - } - - profile.RegionId = RegionFlag(flags).GetStringOrDefault(profile.RegionId) - profile.Language = LanguageFlag(flags).GetStringOrDefault(profile.Language) - profile.OutputFormat = "json" // "output", profile.OutputFormat) - profile.Site = "china" // "site", profile.Site) - profile.ReadTimeout = ReadTimeoutFlag(flags).GetIntegerOrDefault(profile.ReadTimeout) - profile.ConnectTimeout = ConnectTimeoutFlag(flags).GetIntegerOrDefault(profile.ConnectTimeout) - profile.RetryCount = RetryCountFlag(flags).GetIntegerOrDefault(profile.RetryCount) - - err = profile.Validate() - if err != nil { - cli.Errorf(w, "fail to set configuration: %s", err.Error()) - return - } - - config.PutProfile(profile) - config.CurrentProfile = profile.Name - err = hookSaveConfiguration(SaveConfiguration)(config) - if err != nil { - cli.Errorf(w, "save configuration failed %s", err) - } -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/configure_switch.go b/vendor/github.com/aliyun/aliyun-cli/config/configure_switch.go deleted file mode 100644 index c22a6c84..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/configure_switch.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "fmt" - "io" - - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/i18n" -) - -func NewConfigureSwitchCommand() *cli.Command { - cmd := &cli.Command{ - Name: "switch", - Usage: "switch [--profile ]", - Short: i18n.T("switch default profile", "切换默认配置"), - Run: func(c *cli.Context, args []string) error { - return doConfigureSwitch(c.Stdout(), c.Flags()) - }, - } - - AddFlags(cmd.Flags()) - return cmd -} - -func doConfigureSwitch(stdout io.Writer, flags *cli.FlagSet) error { - config, err := loadConfiguration() - if err != nil { - return fmt.Errorf("load configuration failed: %s", err) - } - - profileName, ok := ProfileFlag(flags).GetValue() - if !ok { - return fmt.Errorf("the --profile is required") - } - - _, ok = config.GetProfile(profileName) - if !ok { - return fmt.Errorf("the profile `%s` is inexist", profileName) - } - - config.CurrentProfile = profileName - err = hookSaveConfiguration(SaveConfiguration)(config) - if err != nil { - return fmt.Errorf("save configuration failed: %s", err) - } - - cli.Println(stdout, fmt.Sprintf("The default profile is `%s` now.", profileName)) - return nil -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/flags.go b/vendor/github.com/aliyun/aliyun-cli/config/flags.go deleted file mode 100644 index 502210d2..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/flags.go +++ /dev/null @@ -1,426 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/i18n" -) - -const ( - ProfileFlagName = "profile" - ModeFlagName = "mode" - AccessKeyIdFlagName = "access-key-id" - AccessKeySecretFlagName = "access-key-secret" - StsTokenFlagName = "sts-token" - StsRegionFlagName = "sts-region" - RamRoleNameFlagName = "ram-role-name" - RamRoleArnFlagName = "ram-role-arn" - RoleSessionNameFlagName = "role-session-name" - SourceProfileFlagName = "source-profile" - PrivateKeyFlagName = "private-key" - KeyPairNameFlagName = "key-pair-name" - RegionFlagName = "region" - RegionIdFlagName = "RegionId" - LanguageFlagName = "language" - ReadTimeoutFlagName = "read-timeout" - ConnectTimeoutFlagName = "connect-timeout" - RetryCountFlagName = "retry-count" - SkipSecureVerifyName = "skip-secure-verify" - ConfigurePathFlagName = "config-path" - ExpiredSecondsFlagName = "expired-seconds" - ProcessCommandFlagName = "process-command" - OIDCProviderARNFlagName = "oidc-provider-arn" - OIDCTokenFileFlagName = "oidc-token-file" -) - -func AddFlags(fs *cli.FlagSet) { - fs.Add(NewModeFlag()) - fs.Add(NewProfileFlag()) - fs.Add(NewLanguageFlag()) - fs.Add(NewRegionFlag()) - fs.Add(NewRegionIdFlag()) - fs.Add(NewConfigurePathFlag()) - fs.Add(NewAccessKeyIdFlag()) - fs.Add(NewAccessKeySecretFlag()) - fs.Add(NewStsTokenFlag()) - fs.Add(NewStsRegionFlag()) - fs.Add(NewRamRoleNameFlag()) - fs.Add(NewRamRoleArnFlag()) - fs.Add(NewRoleSessionNameFlag()) - fs.Add(NewPrivateKeyFlag()) - fs.Add(NewKeyPairNameFlag()) - fs.Add(NewReadTimeoutFlag()) - fs.Add(NewConnectTimeoutFlag()) - fs.Add(NewRetryCountFlag()) - fs.Add(NewSkipSecureVerify()) - fs.Add(NewExpiredSecondsFlag()) - fs.Add(NewProcessCommandFlag()) - fs.Add(NewOIDCProviderARNFlag()) - fs.Add(NewOIDCTokenFileFlag()) -} - -func ConnectTimeoutFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(ConnectTimeoutFlagName) -} - -func ProfileFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(ProfileFlagName) -} - -func ModeFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(ModeFlagName) -} - -func AccessKeyIdFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(AccessKeyIdFlagName) -} - -func AccessKeySecretFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(AccessKeySecretFlagName) -} - -func StsTokenFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(StsTokenFlagName) -} - -func StsRegionFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(StsRegionFlagName) -} - -func RamRoleNameFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(RamRoleNameFlagName) -} - -func RamRoleArnFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(RamRoleArnFlagName) -} - -func SourceProfileFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(SourceProfileFlagName) -} - -func RoleSessionNameFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(RoleSessionNameFlagName) -} - -func PrivateKeyFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(PrivateKeyFlagName) -} - -func KeyPairNameFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(KeyPairNameFlagName) -} - -func RegionFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(RegionFlagName) -} - -func RegionIdFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(RegionIdFlagName) -} - -func LanguageFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(LanguageFlagName) -} - -func ReadTimeoutFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(ReadTimeoutFlagName) -} - -func RetryCountFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(RetryCountFlagName) -} - -func SkipSecureVerify(fs *cli.FlagSet) *cli.Flag { - return fs.Get(SkipSecureVerifyName) -} - -func ConfigurePathFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(ConfigurePathFlagName) -} - -func ExpiredSecondsFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(ExpiredSecondsFlagName) -} - -func ProcessCommandFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(ProcessCommandFlagName) -} - -func OIDCProviderARNFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(OIDCProviderARNFlagName) -} - -func OIDCTokenFileFlag(fs *cli.FlagSet) *cli.Flag { - return fs.Get(OIDCTokenFileFlagName) -} - -func NewProfileFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: ProfileFlagName, - Shorthand: 'p', - DefaultValue: "default", - Persistent: true, - Short: i18n.T( - "use `--profile ` to select profile", - "使用 `--profile ` 指定操作的配置集"), - } -} - -func NewModeFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: ModeFlagName, - DefaultValue: "AK", - Persistent: true, - Short: i18n.T( - "use `--mode {AK|StsToken|RamRoleArn|EcsRamRole|RsaKeyPair|RamRoleArnWithRoleName}` to assign authenticate mode", - "使用 `--mode {AK|StsToken|RamRoleArn|EcsRamRole|RsaKeyPair|RamRoleArnWithRoleName}` 指定认证方式"), - } -} - -func NewAccessKeyIdFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: AccessKeyIdFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--access-key-id ` to assign AccessKeyId, required in AK/StsToken/RamRoleArn mode", - "使用 `--access-key-id ` 指定AccessKeyId"), - } -} - -func NewAccessKeySecretFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: AccessKeySecretFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--access-key-secret ` to assign AccessKeySecret", - "使用 `--access-key-secret ` 指定AccessKeySecret"), - } -} - -func NewStsTokenFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: StsTokenFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--sts-token ` to assign StsToken", - "使用 `--sts-token ` 指定StsToken"), - } -} - -func NewStsRegionFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: StsRegionFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--sts-region ` to assign StsRegion", - "使用 `--sts-region ` 指定StsRegion"), - } -} - -func NewRamRoleNameFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: RamRoleNameFlagName, - AssignedMode: cli.AssignedOnce, - Persistent: true, - Short: i18n.T( - "use `--ram-role-name ` to assign RamRoleName", - "使用 `--ram-role-name ` 指定RamRoleName"), - } -} - -func NewRamRoleArnFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: RamRoleArnFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--ram-role-arn ` to assign RamRoleArn", - "使用 `--ram-role-arn ` 指定RamRoleArn"), - } -} - -func NewRoleSessionNameFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: RoleSessionNameFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--role-session-name ` to assign RoleSessionName", - "使用 `--role-session-name ` 指定RoleSessionName"), - } -} - -func NewExpiredSecondsFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: ExpiredSecondsFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--expired-seconds ` to specify expiration time", - "使用 `--expired-seconds ` 指定凭证过期时间"), - } -} - -func NewPrivateKeyFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: PrivateKeyFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--private-key ` to assign RSA PrivateKey", - "使用 `--private-key ` 指定RSA私钥"), - } -} - -func NewKeyPairNameFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: KeyPairNameFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--key-pair-name ` to assign KeyPairName", - "使用 `--key-pair-name ` 指定KeyPairName"), - } -} - -func NewProcessCommandFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: ProcessCommandFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--process-command ` to specify external program execution command", - "使用 `--process-command ` 指定外部程序运行命令"), - } -} - -func NewOIDCProviderARNFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: OIDCProviderARNFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--oidc-provider-arn ` to assign OIDC provider ARN", - "使用 `--oidc-provider-arn ` 来指定 OIDC 提供者 ARN"), - } -} - -func NewOIDCTokenFileFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: OIDCTokenFileFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--oidc-token-file ` to assign OIDC token file path", - "使用 `--oidc-token-file ` 来指定 OIDC Token 文件路径"), - } -} - -func NewRegionFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: RegionFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--region ` to assign region", - "使用 `--region ` 来指定访问大区"), - } -} - -func NewRegionIdFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: RegionIdFlagName, - AssignedMode: cli.AssignedOnce, - Hidden: true, - } -} - -func NewLanguageFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: LanguageFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--language [en|zh]` to assign language", - "使用 `--language [en|zh]` 来指定语言"), - } -} - -func NewConfigurePathFlag() *cli.Flag { - return &cli.Flag{ - Category: "config", - Name: ConfigurePathFlagName, - AssignedMode: cli.AssignedOnce, - Persistent: true, - Short: i18n.T( - "use `--config-path` to specify the configuration file path", - "使用 `--config-path` 指定配置文件路径"), - } -} - -func NewReadTimeoutFlag() *cli.Flag { - return &cli.Flag{ - Category: "caller", - Name: ReadTimeoutFlagName, - AssignedMode: cli.AssignedOnce, - Aliases: []string{"retry-timeout"}, - Short: i18n.T( - "use `--read-timeout ` to set I/O timeout(seconds)", - "使用 `--read-timeout ` 指定I/O超时时间(秒)"), - } -} - -func NewConnectTimeoutFlag() *cli.Flag { - return &cli.Flag{ - Category: "caller", - Name: ConnectTimeoutFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--connect-timeout ` to set connect timeout(seconds)", - "使用 `--connect-timeout ` 指定请求连接超时时间(秒)"), - } -} - -func NewRetryCountFlag() *cli.Flag { - return &cli.Flag{ - Category: "caller", - Name: RetryCountFlagName, - AssignedMode: cli.AssignedOnce, - Short: i18n.T( - "use `--retry-count ` to set retry count", - "使用 `--retry-count ` 指定重试次数"), - } -} - -func NewSkipSecureVerify() *cli.Flag { - return &cli.Flag{ - Category: "caller", - Name: SkipSecureVerifyName, - AssignedMode: cli.AssignedNone, - Persistent: true, - Short: i18n.T( - "use `--skip-secure-verify` to skip https certification validate [Not recommended]", - "使用 `--skip-secure-verify` 跳过https的证书校验 [不推荐使用]"), - } -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/hello.go b/vendor/github.com/aliyun/aliyun-cli/config/hello.go deleted file mode 100644 index 039f0398..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/hello.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "fmt" - "os" - - openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" - util "github.com/alibabacloud-go/tea-utils/v2/service" - "github.com/alibabacloud-go/tea/tea" - "github.com/aliyun/aliyun-cli/cli" -) - -func doHello(ctx *cli.Context, profile *Profile) (err error) { - profile.OverwriteWithFlags(ctx) - credential, err := profile.GetCredential(ctx, nil) - if err != nil { - return - } - - config := &openapi.Config{ - Credential: credential, - } - - config.Endpoint = tea.String(getSTSEndpoint(profile.StsRegion)) - client, err := openapi.NewClient(config) - if err != nil { - return - } - - params := &openapi.Params{ - // 接口名称 - Action: tea.String("GetCallerIdentity"), - // 接口版本 - Version: tea.String("2015-04-01"), - // 接口协议 - Protocol: tea.String("HTTPS"), - // 接口 HTTP 方法 - Method: tea.String("POST"), - AuthType: tea.String("AK"), - Style: tea.String("RPC"), - // 接口 PATH - Pathname: tea.String("/"), - // 接口请求体内容格式 - ReqBodyType: tea.String("json"), - // 接口响应体内容格式 - BodyType: tea.String("json"), - } - // runtime options - runtime := &util.RuntimeOptions{} - request := &openapi.OpenApiRequest{} - - ua := "Aliyun-CLI/" + cli.GetVersion() - if vendorEnv, ok := os.LookupEnv("ALIBABA_CLOUD_VENDOR"); ok { - ua += " vendor/" + vendorEnv - } - - client.UserAgent = tea.String(ua) - _, err = client.CallApi(params, request, runtime) - return -} - -func DoHello(ctx *cli.Context, profile *Profile) { - w := ctx.Stdout() - err := doHello(ctx, profile) - if err != nil { - cli.Println(w, "-----------------------------------------------") - cli.Println(w, "!!! Configure Failed please configure again !!!") - cli.Println(w, "-----------------------------------------------") - cli.Println(w, err) - cli.Println(w, "-----------------------------------------------") - cli.Println(w, "!!! Configure Failed please configure again !!!") - cli.Println(w, "-----------------------------------------------") - return - } - - fmt.Println(icon) -} - -var icon = string(` -Configure Done!!! -..............888888888888888888888 ........=8888888888888888888D=.............. -...........88888888888888888888888 ..........D8888888888888888888888I........... -.........,8888888888888ZI: ...........................=Z88D8888888888D.......... -.........+88888888 ..........................................88888888D.......... -.........+88888888 .......Welcome to use Alibaba Cloud.......O8888888D.......... -.........+88888888 ............. ************* ..............O8888888D.......... -.........+88888888 .... Command Line Interface(Reloaded) ....O8888888D.......... -.........+88888888...........................................88888888D.......... -..........D888888888888DO+. ..........................?ND888888888888D.......... -...........O8888888888888888888888...........D8888888888888888888888=........... -............ .:D8888888888888888888.........78888888888888888888O ..............`) diff --git a/vendor/github.com/aliyun/aliyun-cli/config/legacy.go b/vendor/github.com/aliyun/aliyun-cli/config/legacy.go deleted file mode 100644 index 78f2ad47..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/legacy.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "fmt" - "os" - - ini "gopkg.in/ini.v1" -) - -func MigrateLegacyConfiguration() (conf *Configuration, err error) { - path := hookGetHomePath(GetHomePath)() + "/.aliyuncli/credentials" - _, statErr := os.Stat(path) - if os.IsNotExist(statErr) { - return - } - - conf, migrateErr := MigrateCredentials(path) - if migrateErr != nil { - return - } - - path = hookGetHomePath(GetHomePath)() + "/.aliyuncli/configure" - mfErr := MigrateConfigure(path, conf) - if mfErr != nil { - return - } - - return -} - -func MigrateCredentials(path string) (conf *Configuration, err error) { - conf = &Configuration{} - ini, err := ini.Load(path) - if err != nil { - err = fmt.Errorf(" parse failed: %v", err) - return - } - - for _, section := range ini.Sections() { - if section.Name() == "DEFAULT" { - continue - } - profileName := section.Name() - if section.Name() == "default" { - conf.CurrentProfile = "default" - } else { - profileName = section.Name()[len("profile "):] - if conf.CurrentProfile != "default" { - conf.CurrentProfile = profileName - } - } - // fmt.Printf("\n %s:", profileName) - k1, e1 := section.GetKey("aliyun_access_key_id") - k2, e2 := section.GetKey("aliyun_access_key_secret") - if e1 == nil && e2 == nil { - conf.Profiles = append(conf.Profiles, Profile{ - Name: profileName, - Mode: AK, - AccessKeyId: k1.String(), - AccessKeySecret: k2.String(), - OutputFormat: "json", - }) - } - } - return -} - -func MigrateConfigure(path string, conf *Configuration) (err error) { - ini, err := ini.Load(path) - if err != nil { - err = fmt.Errorf("parse failed: %s", err) - return - } - - for _, section := range ini.Sections() { - profile, ok := conf.GetProfile(section.Name()) - if !ok { - continue - } - - r, err := section.GetKey("region") - if err == nil { - profile.RegionId = r.String() - conf.PutProfile(profile) - } - } - - return nil -} diff --git a/vendor/github.com/aliyun/aliyun-cli/config/profile.go b/vendor/github.com/aliyun/aliyun-cli/config/profile.go deleted file mode 100644 index 20525aad..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/config/profile.go +++ /dev/null @@ -1,470 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package config - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "os" - "os/exec" - "regexp" - "strings" - - "github.com/aliyun/aliyun-cli/cli" - "github.com/aliyun/aliyun-cli/i18n" - "github.com/aliyun/aliyun-cli/util" - credentialsv2 "github.com/aliyun/credentials-go/credentials" -) - -type AuthenticateMode string - -const ( - AK = AuthenticateMode("AK") - // Deprecated: StsToken is deprecated - StsToken = AuthenticateMode("StsToken") - RamRoleArn = AuthenticateMode("RamRoleArn") - EcsRamRole = AuthenticateMode("EcsRamRole") - // Deprecated: RsaKeyPair is deprecated - RsaKeyPair = AuthenticateMode("RsaKeyPair") - // Deprecated: RamRoleArnWithRoleName is deprecated, use ChainableRamRoleArn instead of - RamRoleArnWithEcs = AuthenticateMode("RamRoleArnWithRoleName") - ChainableRamRoleArn = AuthenticateMode("ChainableRamRoleArn") - External = AuthenticateMode("External") - CredentialsURI = AuthenticateMode("CredentialsURI") - OIDC = AuthenticateMode("OIDC") -) - -type Profile struct { - Name string `json:"name"` - Mode AuthenticateMode `json:"mode"` - AccessKeyId string `json:"access_key_id,omitempty"` - AccessKeySecret string `json:"access_key_secret,omitempty"` - StsToken string `json:"sts_token,omitempty"` - StsRegion string `json:"sts_region,omitempty"` - RamRoleName string `json:"ram_role_name,omitempty"` - RamRoleArn string `json:"ram_role_arn,omitempty"` - RoleSessionName string `json:"ram_session_name,omitempty"` - SourceProfile string `json:"source_profile,omitempty"` - PrivateKey string `json:"private_key,omitempty"` - KeyPairName string `json:"key_pair_name,omitempty"` - ExpiredSeconds int `json:"expired_seconds,omitempty"` - Verified string `json:"verified,omitempty"` - RegionId string `json:"region_id,omitempty"` - OutputFormat string `json:"output_format,omitempty"` - Language string `json:"language,omitempty"` - Site string `json:"site,omitempty"` - ReadTimeout int `json:"retry_timeout,omitempty"` - ConnectTimeout int `json:"connect_timeout,omitempty"` - RetryCount int `json:"retry_count,omitempty"` - ProcessCommand string `json:"process_command,omitempty"` - CredentialsURI string `json:"credentials_uri,omitempty"` - OIDCProviderARN string `json:"oidc_provider_arn,omitempty"` - OIDCTokenFile string `json:"oidc_token_file,omitempty"` - parent *Configuration //`json:"-"` -} - -func NewProfile(name string) Profile { - return Profile{ - Name: name, - Mode: "", - OutputFormat: "json", - Language: i18n.GetLanguage(), - } -} - -func (cp *Profile) Validate() error { - if cp.RegionId == "" { - return fmt.Errorf("region can't be empty") - } - - if !IsRegion(cp.RegionId) { - return fmt.Errorf("invalid region %s", cp.RegionId) - } - - if cp.Mode == "" { - return fmt.Errorf("profile %s is not configure yet, run `aliyun configure --profile %s` first", cp.Name, cp.Name) - } - - switch cp.Mode { - case AK: - return cp.ValidateAK() - case StsToken: - err := cp.ValidateAK() - if err != nil { - return err - } - if cp.StsToken == "" { - return fmt.Errorf("invalid sts_token") - } - case RamRoleArn: - err := cp.ValidateAK() - if err != nil { - return err - } - if cp.RamRoleArn == "" { - return fmt.Errorf("invalid ram_role_arn") - } - if cp.RoleSessionName == "" { - return fmt.Errorf("invalid role_session_name") - } - case EcsRamRole, RamRoleArnWithEcs: - case RsaKeyPair: - if cp.PrivateKey == "" { - return fmt.Errorf("invalid private_key") - } - if cp.KeyPairName == "" { - return fmt.Errorf("invalid key_pair_name") - } - case External: - if cp.ProcessCommand == "" { - return fmt.Errorf("invalid process_command") - } - case CredentialsURI: - if cp.CredentialsURI == "" { - return fmt.Errorf("invalid credentials_uri") - } - case OIDC: - if cp.OIDCProviderARN == "" { - return fmt.Errorf("invalid oidc_provider_arn") - } - if cp.OIDCTokenFile == "" { - return fmt.Errorf("invalid oidc_token_file") - } - if cp.RamRoleArn == "" { - return fmt.Errorf("invalid ram_role_arn") - } - if cp.RoleSessionName == "" { - return fmt.Errorf("invalid role_session_name") - } - case ChainableRamRoleArn: - if cp.SourceProfile == "" { - return fmt.Errorf("invalid source_profile") - } - if cp.RamRoleArn == "" { - return fmt.Errorf("invalid ram_role_arn") - } - if cp.RoleSessionName == "" { - return fmt.Errorf("invalid role_session_name") - } - default: - return fmt.Errorf("invalid mode: %s", cp.Mode) - } - return nil -} - -func (cp *Profile) GetParent() *Configuration { - return cp.parent -} - -func (cp *Profile) OverwriteWithFlags(ctx *cli.Context) { - cp.Mode = AuthenticateMode(ModeFlag(ctx.Flags()).GetStringOrDefault(string(cp.Mode))) - cp.AccessKeyId = AccessKeyIdFlag(ctx.Flags()).GetStringOrDefault(cp.AccessKeyId) - cp.AccessKeySecret = AccessKeySecretFlag(ctx.Flags()).GetStringOrDefault(cp.AccessKeySecret) - cp.StsToken = StsTokenFlag(ctx.Flags()).GetStringOrDefault(cp.StsToken) - cp.StsRegion = StsRegionFlag(ctx.Flags()).GetStringOrDefault(cp.StsRegion) - cp.RamRoleName = RamRoleNameFlag(ctx.Flags()).GetStringOrDefault(cp.RamRoleName) - cp.RamRoleArn = RamRoleArnFlag(ctx.Flags()).GetStringOrDefault(cp.RamRoleArn) - cp.RoleSessionName = RoleSessionNameFlag(ctx.Flags()).GetStringOrDefault(cp.RoleSessionName) - cp.KeyPairName = KeyPairNameFlag(ctx.Flags()).GetStringOrDefault(cp.KeyPairName) - cp.PrivateKey = PrivateKeyFlag(ctx.Flags()).GetStringOrDefault(cp.PrivateKey) - cp.RegionId = RegionFlag(ctx.Flags()).GetStringOrDefault(cp.RegionId) - cp.Language = LanguageFlag(ctx.Flags()).GetStringOrDefault(cp.Language) - cp.ReadTimeout = ReadTimeoutFlag(ctx.Flags()).GetIntegerOrDefault(cp.ReadTimeout) - cp.ConnectTimeout = ConnectTimeoutFlag(ctx.Flags()).GetIntegerOrDefault(cp.ConnectTimeout) - cp.RetryCount = RetryCountFlag(ctx.Flags()).GetIntegerOrDefault(cp.RetryCount) - cp.ExpiredSeconds = ExpiredSecondsFlag(ctx.Flags()).GetIntegerOrDefault(cp.ExpiredSeconds) - cp.ProcessCommand = ProcessCommandFlag(ctx.Flags()).GetStringOrDefault(cp.ProcessCommand) - - if cp.AccessKeyId == "" { - cp.AccessKeyId = util.GetFromEnv("ALIBABA_CLOUD_ACCESS_KEY_ID", "ALIBABACLOUD_ACCESS_KEY_ID", "ALICLOUD_ACCESS_KEY_ID", "ACCESS_KEY_ID") - } - - if cp.AccessKeySecret == "" { - cp.AccessKeySecret = util.GetFromEnv("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "ALIBABACLOUD_ACCESS_KEY_SECRET", "ALICLOUD_ACCESS_KEY_SECRET", "ACCESS_KEY_SECRET") - } - - if cp.StsToken == "" { - cp.StsToken = util.GetFromEnv("ALIBABA_CLOUD_SECURITY_TOKEN", "ALIBABACLOUD_SECURITY_TOKEN", "ALICLOUD_SECURITY_TOKEN", "SECURITY_TOKEN") - } - - if cp.RegionId == "" { - cp.RegionId = util.GetFromEnv("ALIBABA_CLOUD_REGION_ID", "ALIBABACLOUD_REGION_ID", "ALICLOUD_REGION_ID", "REGION_ID", "REGION") - } - - if cp.CredentialsURI == "" { - cp.CredentialsURI = os.Getenv("ALIBABA_CLOUD_CREDENTIALS_URI") - } - - if cp.OIDCProviderARN == "" { - cp.OIDCProviderARN = util.GetFromEnv("ALIBABACLOUD_OIDC_PROVIDER_ARN", "ALIBABA_CLOUD_OIDC_PROVIDER_ARN") - } - - if cp.OIDCTokenFile == "" { - cp.OIDCTokenFile = util.GetFromEnv("ALIBABACLOUD_OIDC_TOKEN_FILE", "ALIBABA_CLOUD_OIDC_TOKEN_FILE") - } - - if cp.RamRoleArn == "" { - cp.RamRoleArn = util.GetFromEnv("ALIBABACLOUD_ROLE_ARN", "ALIBABA_CLOUD_ROLE_ARN") - } - - AutoModeRecognition(cp) -} - -func AutoModeRecognition(cp *Profile) { - if cp.Mode != AuthenticateMode("") { - return - } - if cp.AccessKeyId != "" && cp.AccessKeySecret != "" { - cp.Mode = AK - if cp.StsToken != "" { - cp.Mode = StsToken - } else if cp.RamRoleArn != "" { - cp.Mode = RamRoleArn - } - } else if cp.PrivateKey != "" && cp.KeyPairName != "" { - cp.Mode = RsaKeyPair - } else if cp.RamRoleName != "" { - cp.Mode = EcsRamRole - } else if cp.ProcessCommand != "" { - cp.Mode = External - } else if cp.OIDCProviderARN != "" && cp.OIDCTokenFile != "" && cp.RamRoleArn != "" { - cp.Mode = OIDC - } -} - -func (cp *Profile) ValidateAK() error { - if len(cp.AccessKeyId) == 0 { - return fmt.Errorf("invalid access_key_id: %s", cp.AccessKeyId) - } - if len(cp.AccessKeySecret) == 0 { - return fmt.Errorf("invaild access_key_secret: %s", cp.AccessKeySecret) - } - return nil -} - -func getSTSEndpoint(regionId string) string { - if regionId != "" { - return fmt.Sprintf("sts.%s.aliyuncs.com", regionId) - } - return "sts.aliyuncs.com" -} - -func (cp *Profile) GetCredential(ctx *cli.Context, proxyHost *string) (cred credentialsv2.Credential, err error) { - config := new(credentialsv2.Config) - // The AK, StsToken are direct credential - // Others are indirect credential - cp.Validate() - switch cp.Mode { - case AK: - if cp.AccessKeyId == "" || cp.AccessKeySecret == "" { - err = fmt.Errorf("AccessKeyId/AccessKeySecret is empty! run `aliyun configure` first") - return - } - - if cp.RegionId == "" { - err = fmt.Errorf("default RegionId is empty! run `aliyun configure` first") - return - } - - config.SetType("access_key"). - SetAccessKeyId(cp.AccessKeyId). - SetAccessKeySecret(cp.AccessKeySecret) - - case StsToken: - config.SetType("sts"). - SetAccessKeyId(cp.AccessKeyId). - SetAccessKeySecret(cp.AccessKeySecret). - SetSecurityToken(cp.StsToken) - - case RamRoleArn: - config.SetType("ram_role_arn"). - SetAccessKeyId(cp.AccessKeyId). - SetAccessKeySecret(cp.AccessKeySecret). - SetRoleArn(cp.RamRoleArn). - SetRoleSessionName(cp.RoleSessionName). - SetRoleSessionExpiration(cp.ExpiredSeconds). - SetSTSEndpoint(getSTSEndpoint(cp.StsRegion)) - - if cp.StsToken != "" { - config.SetSecurityToken(cp.StsToken) - } - - case EcsRamRole: - config.SetType("ecs_ram_role"). - SetRoleName(cp.RamRoleName) - - case RsaKeyPair: - config.SetType("rsa_key_pair"). - SetPrivateKeyFile(cp.PrivateKey). - SetPublicKeyId(cp.KeyPairName). - SetSessionExpiration(cp.ExpiredSeconds). - SetSTSEndpoint(getSTSEndpoint(cp.StsRegion)) - - case RamRoleArnWithEcs: - config.SetType("ecs_ram_role"). - SetRoleName(cp.RamRoleName) - client, err := credentialsv2.NewCredential(config) - if err != nil { - return nil, err - } - // 从 ECS RAM Role 获取中间 STS - model, err := client.GetCredential() - if err != nil { - return nil, err - } - - // 扮演最终角色 - config.SetType("ram_role_arn"). - SetAccessKeyId(*model.AccessKeyId). - SetAccessKeySecret(*model.AccessKeySecret). - SetSecurityToken(*model.SecurityToken). - SetRoleArn(cp.RamRoleArn). - SetRoleSessionName(cp.RoleSessionName). - SetRoleSessionExpiration(cp.ExpiredSeconds). - SetSTSEndpoint(getSTSEndpoint(cp.StsRegion)) - - case ChainableRamRoleArn: - profileName := cp.SourceProfile - - // 从 configuration 中重新获取 source profile - source, loaded := cp.parent.GetProfile(profileName) - if !loaded { - err = fmt.Errorf("can not load the source profile: " + profileName) - return - } - - middle, err2 := source.GetCredential(ctx, proxyHost) - if err2 != nil { - err = err2 - return - } - - // 从上游处获得中间 AK/STS - model, err3 := middle.GetCredential() - - if err3 != nil { - err = err3 - return - } - - // 扮演最终角色 - config.SetType("ram_role_arn"). - SetAccessKeyId(*model.AccessKeyId). - SetAccessKeySecret(*model.AccessKeySecret). - SetRoleArn(cp.RamRoleArn). - SetRoleSessionName(cp.RoleSessionName). - SetRoleSessionExpiration(cp.ExpiredSeconds). - SetSTSEndpoint(getSTSEndpoint(cp.StsRegion)) - - if model.SecurityToken != nil { - config.SetSecurityToken(*model.SecurityToken) - } - - case External: - args := strings.Fields(cp.ProcessCommand) - cmd := exec.Command(args[0], args[1:]...) - buf, err := cmd.CombinedOutput() - if err != nil { - return nil, err - } - // 解析得到新的 profile 配置 - err = json.Unmarshal(buf, cp) - if err != nil { - fmt.Println(cp.ProcessCommand) - fmt.Println(string(buf)) - return nil, err - } - return cp.GetCredential(ctx, proxyHost) - - case CredentialsURI: - uri := cp.CredentialsURI - - if uri == "" { - uri = os.Getenv("ALIBABA_CLOUD_CREDENTIALS_URI") - } - - if uri == "" { - return nil, fmt.Errorf("invalid credentials uri") - } - - res, err := http.Get(uri) - if err != nil { - return nil, err - } - - if res.StatusCode != 200 { - return nil, fmt.Errorf("get credentials from %s failed, status code %d", uri, res.StatusCode) - } - - body, err := io.ReadAll(res.Body) - res.Body.Close() - if err != nil { - return nil, err - } - - type Response struct { - Code string - AccessKeyId string - AccessKeySecret string - SecurityToken string - Expiration string - } - var response Response - err = json.Unmarshal(body, &response) - if err != nil { - return nil, fmt.Errorf("unmarshal credentials failed, the body %s", string(body)) - } - - if response.Code != "Success" { - return nil, fmt.Errorf("get sts token err, Code is not Success") - } - - config.SetType("sts"). - SetAccessKeyId(response.AccessKeyId). - SetAccessKeySecret(response.AccessKeySecret). - SetSecurityToken(response.SecurityToken) - - case OIDC: - config.SetType("oidc_role_arn"). - SetOIDCProviderArn(cp.OIDCProviderARN). - SetOIDCTokenFilePath(cp.OIDCTokenFile). - SetRoleArn(cp.RamRoleArn). - SetRoleSessionName(cp.RoleSessionName). - SetSTSEndpoint(getSTSEndpoint(cp.StsRegion)). - SetSessionExpiration(3600) - - default: - return nil, fmt.Errorf("unexcepted certificate mode: %s", cp.Mode) - } - - if proxyHost != nil { - config.SetProxy(*proxyHost) - } else { - proxy := util.GetFromEnv("HTTPS_PROXY", "https_proxy") - if proxy != "" { - config.SetProxy(proxy) - } - } - - return credentialsv2.NewCredential(config) -} - -func IsRegion(region string) bool { - if match, _ := regexp.MatchString("^[a-zA-Z0-9-]*$", region); !match { - return false - } - return true -} diff --git a/vendor/github.com/aliyun/aliyun-cli/i18n/environment.go b/vendor/github.com/aliyun/aliyun-cli/i18n/environment.go deleted file mode 100644 index d9b77a61..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/i18n/environment.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package i18n - -import ( - "os" - "strings" -) - -type LanguageCode string - -const ( - Zh = LanguageCode("zh") - En = LanguageCode("en") -) - -func getLanguageFromEnv() string { - lang := os.Getenv("LANG") - if strings.HasPrefix(lang, "zh_CN") { - return "zh" - } else { - return "en" - } -} - -var language = getLanguageFromEnv() - -func SetLanguage(lang string) { - language = lang -} - -func GetLanguage() string { - return language -} diff --git a/vendor/github.com/aliyun/aliyun-cli/i18n/text.go b/vendor/github.com/aliyun/aliyun-cli/i18n/text.go deleted file mode 100644 index 310b04e3..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/i18n/text.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) 2009-present, Alibaba Cloud All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -package i18n - -func T(en string, zh string) *Text { - t := &Text{ - dic: make(map[string]string), - } - t.dic["en"] = en - if zh != "" { - t.dic["zh"] = zh - } - return t -} - -type Text struct { - dic map[string]string -} - -func (a *Text) Text() string { - lang := GetLanguage() - return a.Get(lang) -} - -func (a *Text) Get(lang string) string { - s, ok := a.dic[lang] - if !ok { - return "" - } - return s -} - -func (a *Text) GetData() map[string]string { - return a.dic -} diff --git a/vendor/github.com/aliyun/aliyun-cli/util/util.go b/vendor/github.com/aliyun/aliyun-cli/util/util.go deleted file mode 100644 index aad1ced8..00000000 --- a/vendor/github.com/aliyun/aliyun-cli/util/util.go +++ /dev/null @@ -1,13 +0,0 @@ -package util - -import "os" - -func GetFromEnv(args ...string) string { - for _, key := range args { - if value := os.Getenv(key); value != "" { - return value - } - } - - return "" -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 9eab7054..63079a0e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -41,12 +41,6 @@ github.com/alibabacloud-go/tea-xml/service # github.com/alibabacloud-go/vpc-20160428/v6 v6.10.4 ## explicit; go 1.14 github.com/alibabacloud-go/vpc-20160428/v6/client -# github.com/aliyun/aliyun-cli v0.0.0-20240925084117-158a70e275f0 -## explicit; go 1.18 -github.com/aliyun/aliyun-cli/cli -github.com/aliyun/aliyun-cli/config -github.com/aliyun/aliyun-cli/i18n -github.com/aliyun/aliyun-cli/util # github.com/aliyun/credentials-go v1.3.10 ## explicit; go 1.14 github.com/aliyun/credentials-go/credentials