Commit 56accd87 authored by Brendan Burns's avatar Brendan Burns Committed by Brendan Burns

Update godeps.

parent 8e9186a5
...@@ -30,61 +30,66 @@ ...@@ -30,61 +30,66 @@
}, },
{ {
"ImportPath": "github.com/Azure/azure-sdk-for-go/arm/compute", "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/compute",
"Comment": "v7.0.1-beta", "Comment": "v10.0.4-beta-1-g786cc84",
"Rev": "0984e0641ae43b89283223034574d6465be93bf4" "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad"
}, },
{ {
"ImportPath": "github.com/Azure/azure-sdk-for-go/arm/containerregistry", "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/containerregistry",
"Comment": "v7.0.1-beta", "Comment": "v10.0.4-beta-1-g786cc84",
"Rev": "0984e0641ae43b89283223034574d6465be93bf4" "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad"
}, },
{ {
"ImportPath": "github.com/Azure/azure-sdk-for-go/arm/network", "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/network",
"Comment": "v7.0.1-beta", "Comment": "v10.0.4-beta-1-g786cc84",
"Rev": "0984e0641ae43b89283223034574d6465be93bf4" "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad"
}, },
{ {
"ImportPath": "github.com/Azure/azure-sdk-for-go/arm/storage", "ImportPath": "github.com/Azure/azure-sdk-for-go/arm/storage",
"Comment": "v7.0.1-beta", "Comment": "v10.0.4-beta-1-g786cc84",
"Rev": "0984e0641ae43b89283223034574d6465be93bf4" "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad"
}, },
{ {
"ImportPath": "github.com/Azure/azure-sdk-for-go/storage", "ImportPath": "github.com/Azure/azure-sdk-for-go/storage",
"Comment": "v7.0.1-beta", "Comment": "v10.0.4-beta-1-g786cc84",
"Rev": "0984e0641ae43b89283223034574d6465be93bf4" "Rev": "786cc84138518bf7fd6d60e92fad1ac9d1a117ad"
}, },
{ {
"ImportPath": "github.com/Azure/go-ansiterm", "ImportPath": "github.com/Azure/go-ansiterm",
"Rev": "70b2c90b260171e829f1ebd7c17f600c11858dbe" "Rev": "fa152c58bc15761d0200cb75fe958b89a9d4888e"
}, },
{ {
"ImportPath": "github.com/Azure/go-ansiterm/winterm", "ImportPath": "github.com/Azure/go-ansiterm/winterm",
"Rev": "70b2c90b260171e829f1ebd7c17f600c11858dbe" "Rev": "fa152c58bc15761d0200cb75fe958b89a9d4888e"
}, },
{ {
"ImportPath": "github.com/Azure/go-autorest/autorest", "ImportPath": "github.com/Azure/go-autorest/autorest",
"Comment": "v7.2.3", "Comment": "v8.0.0",
"Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d"
},
{
"ImportPath": "github.com/Azure/go-autorest/autorest/adal",
"Comment": "v8.0.0",
"Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d"
}, },
{ {
"ImportPath": "github.com/Azure/go-autorest/autorest/azure", "ImportPath": "github.com/Azure/go-autorest/autorest/azure",
"Comment": "v7.2.3", "Comment": "v8.0.0",
"Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d"
}, },
{ {
"ImportPath": "github.com/Azure/go-autorest/autorest/date", "ImportPath": "github.com/Azure/go-autorest/autorest/date",
"Comment": "v7.2.3", "Comment": "v8.0.0",
"Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d"
}, },
{ {
"ImportPath": "github.com/Azure/go-autorest/autorest/to", "ImportPath": "github.com/Azure/go-autorest/autorest/to",
"Comment": "v7.2.3", "Comment": "v8.0.0",
"Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d"
}, },
{ {
"ImportPath": "github.com/Azure/go-autorest/autorest/validation", "ImportPath": "github.com/Azure/go-autorest/autorest/validation",
"Comment": "v7.2.3", "Comment": "v8.0.0",
"Rev": "d7c034a8af24eda120dd6460bfcd6d9ed14e43ca" "Rev": "58f6f26e200fa5dfb40c9cd1c83f3e2c860d779d"
}, },
{ {
"ImportPath": "github.com/MakeNowJust/heredoc", "ImportPath": "github.com/MakeNowJust/heredoc",
......
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"systemstat.go",
"systemstat_linux.go",
],
tags = ["automanaged"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["autoneg.go"],
tags = ["automanaged"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["metadata.go"],
tags = ["automanaged"],
deps = [
"//vendor/cloud.google.com/go/internal:go_default_library",
"//vendor/golang.org/x/net/context:go_default_library",
"//vendor/golang.org/x/net/context/ctxhttp:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["cloud.go"],
tags = ["automanaged"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"availabilitysets.go",
"client.go",
"models.go",
"usageoperations.go",
"version.go",
"virtualmachineextensionimages.go",
"virtualmachineextensions.go",
"virtualmachineimages.go",
"virtualmachines.go",
"virtualmachinescalesets.go",
"virtualmachinescalesetvms.go",
"virtualmachinesizes.go",
],
tags = ["automanaged"],
deps = [
"//vendor/github.com/Azure/go-autorest/autorest:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/date:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/to:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/validation:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
...@@ -14,14 +14,13 @@ package compute ...@@ -14,14 +14,13 @@ package compute
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
import ( import (
"github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http" "net/http"
) )
...@@ -44,26 +43,21 @@ func NewAvailabilitySetsClientWithBaseURI(baseURI string, subscriptionID string) ...@@ -44,26 +43,21 @@ func NewAvailabilitySetsClientWithBaseURI(baseURI string, subscriptionID string)
// CreateOrUpdate create or update an availability set. // CreateOrUpdate create or update an availability set.
// //
// resourceGroupName is the name of the resource group. name is the name of // resourceGroupName is the name of the resource group. name is the name of the
// the availability set. parameters is parameters supplied to the Create // availability set. parameters is parameters supplied to the Create
// Availability Set operation. // Availability Set operation.
func (client AvailabilitySetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters AvailabilitySet) (result AvailabilitySet, err error) { func (client AvailabilitySetsClient) CreateOrUpdate(resourceGroupName string, name string, parameters AvailabilitySet) (result AvailabilitySet, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.AvailabilitySetProperties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.AvailabilitySetProperties.Statuses", Name: validation.ReadOnly, Rule: true, Chain: nil}}}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate")
}
req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters) req, err := client.CreateOrUpdatePreparer(resourceGroupName, name, parameters)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", nil, "Failure preparing request")
return
} }
resp, err := client.CreateOrUpdateSender(req) resp, err := client.CreateOrUpdateSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "CreateOrUpdate", resp, "Failure sending request")
return
} }
result, err = client.CreateOrUpdateResponder(resp) result, err = client.CreateOrUpdateResponder(resp)
...@@ -82,8 +76,9 @@ func (client AvailabilitySetsClient) CreateOrUpdatePreparer(resourceGroupName st ...@@ -82,8 +76,9 @@ func (client AvailabilitySetsClient) CreateOrUpdatePreparer(resourceGroupName st
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -119,16 +114,18 @@ func (client AvailabilitySetsClient) CreateOrUpdateResponder(resp *http.Response ...@@ -119,16 +114,18 @@ func (client AvailabilitySetsClient) CreateOrUpdateResponder(resp *http.Response
// //
// resourceGroupName is the name of the resource group. availabilitySetName is // resourceGroupName is the name of the resource group. availabilitySetName is
// the name of the availability set. // the name of the availability set.
func (client AvailabilitySetsClient) Delete(resourceGroupName string, availabilitySetName string) (result autorest.Response, err error) { func (client AvailabilitySetsClient) Delete(resourceGroupName string, availabilitySetName string) (result OperationStatusResponse, err error) {
req, err := client.DeletePreparer(resourceGroupName, availabilitySetName) req, err := client.DeletePreparer(resourceGroupName, availabilitySetName)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", nil, "Failure preparing request")
return
} }
resp, err := client.DeleteSender(req) resp, err := client.DeleteSender(req)
if err != nil { if err != nil {
result.Response = resp result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Delete", resp, "Failure sending request")
return
} }
result, err = client.DeleteResponder(resp) result, err = client.DeleteResponder(resp)
...@@ -147,8 +144,9 @@ func (client AvailabilitySetsClient) DeletePreparer(resourceGroupName string, av ...@@ -147,8 +144,9 @@ func (client AvailabilitySetsClient) DeletePreparer(resourceGroupName string, av
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -167,13 +165,14 @@ func (client AvailabilitySetsClient) DeleteSender(req *http.Request) (*http.Resp ...@@ -167,13 +165,14 @@ func (client AvailabilitySetsClient) DeleteSender(req *http.Request) (*http.Resp
// DeleteResponder handles the response to the Delete request. The method always // DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body. // closes the http.Response Body.
func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (result OperationStatusResponse, err error) {
err = autorest.Respond( err = autorest.Respond(
resp, resp,
client.ByInspecting(), client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing()) autorest.ByClosing())
result.Response = resp result.Response = autorest.Response{Response: resp}
return return
} }
...@@ -184,13 +183,15 @@ func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (resul ...@@ -184,13 +183,15 @@ func (client AvailabilitySetsClient) DeleteResponder(resp *http.Response) (resul
func (client AvailabilitySetsClient) Get(resourceGroupName string, availabilitySetName string) (result AvailabilitySet, err error) { func (client AvailabilitySetsClient) Get(resourceGroupName string, availabilitySetName string) (result AvailabilitySet, err error) {
req, err := client.GetPreparer(resourceGroupName, availabilitySetName) req, err := client.GetPreparer(resourceGroupName, availabilitySetName)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", nil, "Failure preparing request")
return
} }
resp, err := client.GetSender(req) resp, err := client.GetSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "Get", resp, "Failure sending request")
return
} }
result, err = client.GetResponder(resp) result, err = client.GetResponder(resp)
...@@ -209,8 +210,9 @@ func (client AvailabilitySetsClient) GetPreparer(resourceGroupName string, avail ...@@ -209,8 +210,9 @@ func (client AvailabilitySetsClient) GetPreparer(resourceGroupName string, avail
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -246,13 +248,15 @@ func (client AvailabilitySetsClient) GetResponder(resp *http.Response) (result A ...@@ -246,13 +248,15 @@ func (client AvailabilitySetsClient) GetResponder(resp *http.Response) (result A
func (client AvailabilitySetsClient) List(resourceGroupName string) (result AvailabilitySetListResult, err error) { func (client AvailabilitySetsClient) List(resourceGroupName string) (result AvailabilitySetListResult, err error) {
req, err := client.ListPreparer(resourceGroupName) req, err := client.ListPreparer(resourceGroupName)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", nil, "Failure preparing request")
return
} }
resp, err := client.ListSender(req) resp, err := client.ListSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "List", resp, "Failure sending request")
return
} }
result, err = client.ListResponder(resp) result, err = client.ListResponder(resp)
...@@ -270,8 +274,9 @@ func (client AvailabilitySetsClient) ListPreparer(resourceGroupName string) (*ht ...@@ -270,8 +274,9 @@ func (client AvailabilitySetsClient) ListPreparer(resourceGroupName string) (*ht
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -309,13 +314,15 @@ func (client AvailabilitySetsClient) ListResponder(resp *http.Response) (result ...@@ -309,13 +314,15 @@ func (client AvailabilitySetsClient) ListResponder(resp *http.Response) (result
func (client AvailabilitySetsClient) ListAvailableSizes(resourceGroupName string, availabilitySetName string) (result VirtualMachineSizeListResult, err error) { func (client AvailabilitySetsClient) ListAvailableSizes(resourceGroupName string, availabilitySetName string) (result VirtualMachineSizeListResult, err error) {
req, err := client.ListAvailableSizesPreparer(resourceGroupName, availabilitySetName) req, err := client.ListAvailableSizesPreparer(resourceGroupName, availabilitySetName)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", nil, "Failure preparing request")
return
} }
resp, err := client.ListAvailableSizesSender(req) resp, err := client.ListAvailableSizesSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.AvailabilitySetsClient", "ListAvailableSizes", resp, "Failure sending request")
return
} }
result, err = client.ListAvailableSizesResponder(resp) result, err = client.ListAvailableSizesResponder(resp)
...@@ -334,8 +341,9 @@ func (client AvailabilitySetsClient) ListAvailableSizesPreparer(resourceGroupNam ...@@ -334,8 +341,9 @@ func (client AvailabilitySetsClient) ListAvailableSizesPreparer(resourceGroupNam
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
......
// Package compute implements the Azure ARM Compute service API version // Package compute implements the Azure ARM Compute service API version
// 2016-03-30. // 2016-04-30-preview.
// //
// The Compute Management Client. // The Compute Management Client.
package compute package compute
...@@ -18,7 +18,7 @@ package compute ...@@ -18,7 +18,7 @@ package compute
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -27,9 +27,6 @@ import ( ...@@ -27,9 +27,6 @@ import (
) )
const ( const (
// APIVersion is the version of the Compute
APIVersion = "2016-03-30"
// DefaultBaseURI is the default URI used for the service Compute // DefaultBaseURI is the default URI used for the service Compute
DefaultBaseURI = "https://management.azure.com" DefaultBaseURI = "https://management.azure.com"
) )
...@@ -38,7 +35,6 @@ const ( ...@@ -38,7 +35,6 @@ const (
type ManagementClient struct { type ManagementClient struct {
autorest.Client autorest.Client
BaseURI string BaseURI string
APIVersion string
SubscriptionID string SubscriptionID string
} }
...@@ -52,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { ...@@ -52,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {
return ManagementClient{ return ManagementClient{
Client: autorest.NewClientWithUserAgent(UserAgent()), Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI, BaseURI: baseURI,
APIVersion: APIVersion,
SubscriptionID: subscriptionID, SubscriptionID: subscriptionID,
} }
} }
package compute
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// UsageOperationsClient is the the Compute Management Client.
type UsageOperationsClient struct {
ManagementClient
}
// NewUsageOperationsClient creates an instance of the UsageOperationsClient
// client.
func NewUsageOperationsClient(subscriptionID string) UsageOperationsClient {
return NewUsageOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewUsageOperationsClientWithBaseURI creates an instance of the
// UsageOperationsClient client.
func NewUsageOperationsClientWithBaseURI(baseURI string, subscriptionID string) UsageOperationsClient {
return UsageOperationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List gets, for the specified location, the current compute resource usage
// information as well as the limits for compute resources under the
// subscription.
//
// location is the location for which resource usage is queried.
func (client UsageOperationsClient) List(location string) (result ListUsagesResult, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: location,
Constraints: []validation.Constraint{{Target: "location", Name: validation.Pattern, Rule: `^[-\w\._]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "compute.UsageOperationsClient", "List")
}
req, err := client.ListPreparer(location)
if err != nil {
return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", nil, "Failure preparing request")
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure sending request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client UsageOperationsClient) ListPreparer(location string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"location": autorest.Encode("path", location),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
queryParameters := map[string]interface{}{
"api-version": client.APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client UsageOperationsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client UsageOperationsClient) ListResponder(resp *http.Response) (result ListUsagesResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListNextResults retrieves the next set of results, if any.
func (client UsageOperationsClient) ListNextResults(lastResults ListUsagesResult) (result ListUsagesResult, err error) {
req, err := lastResults.ListUsagesResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "compute.UsageOperationsClient", "List", resp, "Failure responding to next results request")
}
return
}
...@@ -14,30 +14,16 @@ package compute ...@@ -14,30 +14,16 @@ package compute
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
import (
"fmt"
)
const (
major = "7"
minor = "0"
patch = "1"
// Always begin a "tag" with a dash (as per http://semver.org)
tag = "-beta"
semVerFormat = "%s.%s.%s%s"
userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s"
)
// UserAgent returns the UserAgent string to use when sending http.Requests. // UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string { func UserAgent() string {
return fmt.Sprintf(userAgentFormat, Version(), "compute", "2016-03-30") return "Azure-SDK-For-Go/v10.0.2-beta arm-compute/2016-04-30-preview"
} }
// Version returns the semantic version (see http://semver.org) of the client. // Version returns the semantic version (see http://semver.org) of the client.
func Version() string { func Version() string {
return fmt.Sprintf(semVerFormat, major, minor, patch, tag) return "v10.0.2-beta"
} }
...@@ -14,7 +14,7 @@ package compute ...@@ -14,7 +14,7 @@ package compute
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -35,8 +35,8 @@ func NewVirtualMachineExtensionImagesClient(subscriptionID string) VirtualMachin ...@@ -35,8 +35,8 @@ func NewVirtualMachineExtensionImagesClient(subscriptionID string) VirtualMachin
return NewVirtualMachineExtensionImagesClientWithBaseURI(DefaultBaseURI, subscriptionID) return NewVirtualMachineExtensionImagesClientWithBaseURI(DefaultBaseURI, subscriptionID)
} }
// NewVirtualMachineExtensionImagesClientWithBaseURI creates an instance of // NewVirtualMachineExtensionImagesClientWithBaseURI creates an instance of the
// the VirtualMachineExtensionImagesClient client. // VirtualMachineExtensionImagesClient client.
func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineExtensionImagesClient { func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscriptionID string) VirtualMachineExtensionImagesClient {
return VirtualMachineExtensionImagesClient{NewWithBaseURI(baseURI, subscriptionID)} return VirtualMachineExtensionImagesClient{NewWithBaseURI(baseURI, subscriptionID)}
} }
...@@ -46,13 +46,15 @@ func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscript ...@@ -46,13 +46,15 @@ func NewVirtualMachineExtensionImagesClientWithBaseURI(baseURI string, subscript
func (client VirtualMachineExtensionImagesClient) Get(location string, publisherName string, typeParameter string, version string) (result VirtualMachineExtensionImage, err error) { func (client VirtualMachineExtensionImagesClient) Get(location string, publisherName string, typeParameter string, version string) (result VirtualMachineExtensionImage, err error) {
req, err := client.GetPreparer(location, publisherName, typeParameter, version) req, err := client.GetPreparer(location, publisherName, typeParameter, version)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", nil, "Failure preparing request")
return
} }
resp, err := client.GetSender(req) resp, err := client.GetSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "Get", resp, "Failure sending request")
return
} }
result, err = client.GetResponder(resp) result, err = client.GetResponder(resp)
...@@ -73,8 +75,9 @@ func (client VirtualMachineExtensionImagesClient) GetPreparer(location string, p ...@@ -73,8 +75,9 @@ func (client VirtualMachineExtensionImagesClient) GetPreparer(location string, p
"version": autorest.Encode("path", version), "version": autorest.Encode("path", version),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -109,13 +112,15 @@ func (client VirtualMachineExtensionImagesClient) GetResponder(resp *http.Respon ...@@ -109,13 +112,15 @@ func (client VirtualMachineExtensionImagesClient) GetResponder(resp *http.Respon
func (client VirtualMachineExtensionImagesClient) ListTypes(location string, publisherName string) (result ListVirtualMachineExtensionImage, err error) { func (client VirtualMachineExtensionImagesClient) ListTypes(location string, publisherName string) (result ListVirtualMachineExtensionImage, err error) {
req, err := client.ListTypesPreparer(location, publisherName) req, err := client.ListTypesPreparer(location, publisherName)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", nil, "Failure preparing request")
return
} }
resp, err := client.ListTypesSender(req) resp, err := client.ListTypesSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListTypes", resp, "Failure sending request")
return
} }
result, err = client.ListTypesResponder(resp) result, err = client.ListTypesResponder(resp)
...@@ -134,8 +139,9 @@ func (client VirtualMachineExtensionImagesClient) ListTypesPreparer(location str ...@@ -134,8 +139,9 @@ func (client VirtualMachineExtensionImagesClient) ListTypesPreparer(location str
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -171,13 +177,15 @@ func (client VirtualMachineExtensionImagesClient) ListTypesResponder(resp *http. ...@@ -171,13 +177,15 @@ func (client VirtualMachineExtensionImagesClient) ListTypesResponder(resp *http.
func (client VirtualMachineExtensionImagesClient) ListVersions(location string, publisherName string, typeParameter string, filter string, top *int32, orderby string) (result ListVirtualMachineExtensionImage, err error) { func (client VirtualMachineExtensionImagesClient) ListVersions(location string, publisherName string, typeParameter string, filter string, top *int32, orderby string) (result ListVirtualMachineExtensionImage, err error) {
req, err := client.ListVersionsPreparer(location, publisherName, typeParameter, filter, top, orderby) req, err := client.ListVersionsPreparer(location, publisherName, typeParameter, filter, top, orderby)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", nil, "Failure preparing request")
return
} }
resp, err := client.ListVersionsSender(req) resp, err := client.ListVersionsSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineExtensionImagesClient", "ListVersions", resp, "Failure sending request")
return
} }
result, err = client.ListVersionsResponder(resp) result, err = client.ListVersionsResponder(resp)
...@@ -197,8 +205,9 @@ func (client VirtualMachineExtensionImagesClient) ListVersionsPreparer(location ...@@ -197,8 +205,9 @@ func (client VirtualMachineExtensionImagesClient) ListVersionsPreparer(location
"type": autorest.Encode("path", typeParameter), "type": autorest.Encode("path", typeParameter),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
if len(filter) > 0 { if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter) queryParameters["$filter"] = autorest.Encode("query", filter)
......
...@@ -14,7 +14,7 @@ package compute ...@@ -14,7 +14,7 @@ package compute
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -49,13 +49,15 @@ func NewVirtualMachineImagesClientWithBaseURI(baseURI string, subscriptionID str ...@@ -49,13 +49,15 @@ func NewVirtualMachineImagesClientWithBaseURI(baseURI string, subscriptionID str
func (client VirtualMachineImagesClient) Get(location string, publisherName string, offer string, skus string, version string) (result VirtualMachineImage, err error) { func (client VirtualMachineImagesClient) Get(location string, publisherName string, offer string, skus string, version string) (result VirtualMachineImage, err error) {
req, err := client.GetPreparer(location, publisherName, offer, skus, version) req, err := client.GetPreparer(location, publisherName, offer, skus, version)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", nil, "Failure preparing request")
return
} }
resp, err := client.GetSender(req) resp, err := client.GetSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "Get", resp, "Failure sending request")
return
} }
result, err = client.GetResponder(resp) result, err = client.GetResponder(resp)
...@@ -77,8 +79,9 @@ func (client VirtualMachineImagesClient) GetPreparer(location string, publisherN ...@@ -77,8 +79,9 @@ func (client VirtualMachineImagesClient) GetPreparer(location string, publisherN
"version": autorest.Encode("path", version), "version": autorest.Encode("path", version),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -117,13 +120,15 @@ func (client VirtualMachineImagesClient) GetResponder(resp *http.Response) (resu ...@@ -117,13 +120,15 @@ func (client VirtualMachineImagesClient) GetResponder(resp *http.Response) (resu
func (client VirtualMachineImagesClient) List(location string, publisherName string, offer string, skus string, filter string, top *int32, orderby string) (result ListVirtualMachineImageResource, err error) { func (client VirtualMachineImagesClient) List(location string, publisherName string, offer string, skus string, filter string, top *int32, orderby string) (result ListVirtualMachineImageResource, err error) {
req, err := client.ListPreparer(location, publisherName, offer, skus, filter, top, orderby) req, err := client.ListPreparer(location, publisherName, offer, skus, filter, top, orderby)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", nil, "Failure preparing request")
return
} }
resp, err := client.ListSender(req) resp, err := client.ListSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "List", resp, "Failure sending request")
return
} }
result, err = client.ListResponder(resp) result, err = client.ListResponder(resp)
...@@ -144,8 +149,9 @@ func (client VirtualMachineImagesClient) ListPreparer(location string, publisher ...@@ -144,8 +149,9 @@ func (client VirtualMachineImagesClient) ListPreparer(location string, publisher
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
if len(filter) > 0 { if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter) queryParameters["$filter"] = autorest.Encode("query", filter)
...@@ -192,13 +198,15 @@ func (client VirtualMachineImagesClient) ListResponder(resp *http.Response) (res ...@@ -192,13 +198,15 @@ func (client VirtualMachineImagesClient) ListResponder(resp *http.Response) (res
func (client VirtualMachineImagesClient) ListOffers(location string, publisherName string) (result ListVirtualMachineImageResource, err error) { func (client VirtualMachineImagesClient) ListOffers(location string, publisherName string) (result ListVirtualMachineImageResource, err error) {
req, err := client.ListOffersPreparer(location, publisherName) req, err := client.ListOffersPreparer(location, publisherName)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", nil, "Failure preparing request")
return
} }
resp, err := client.ListOffersSender(req) resp, err := client.ListOffersSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListOffers", resp, "Failure sending request")
return
} }
result, err = client.ListOffersResponder(resp) result, err = client.ListOffersResponder(resp)
...@@ -217,8 +225,9 @@ func (client VirtualMachineImagesClient) ListOffersPreparer(location string, pub ...@@ -217,8 +225,9 @@ func (client VirtualMachineImagesClient) ListOffersPreparer(location string, pub
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -255,13 +264,15 @@ func (client VirtualMachineImagesClient) ListOffersResponder(resp *http.Response ...@@ -255,13 +264,15 @@ func (client VirtualMachineImagesClient) ListOffersResponder(resp *http.Response
func (client VirtualMachineImagesClient) ListPublishers(location string) (result ListVirtualMachineImageResource, err error) { func (client VirtualMachineImagesClient) ListPublishers(location string) (result ListVirtualMachineImageResource, err error) {
req, err := client.ListPublishersPreparer(location) req, err := client.ListPublishersPreparer(location)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", nil, "Failure preparing request")
return
} }
resp, err := client.ListPublishersSender(req) resp, err := client.ListPublishersSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListPublishers", resp, "Failure sending request")
return
} }
result, err = client.ListPublishersResponder(resp) result, err = client.ListPublishersResponder(resp)
...@@ -279,8 +290,9 @@ func (client VirtualMachineImagesClient) ListPublishersPreparer(location string) ...@@ -279,8 +290,9 @@ func (client VirtualMachineImagesClient) ListPublishersPreparer(location string)
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
...@@ -318,13 +330,15 @@ func (client VirtualMachineImagesClient) ListPublishersResponder(resp *http.Resp ...@@ -318,13 +330,15 @@ func (client VirtualMachineImagesClient) ListPublishersResponder(resp *http.Resp
func (client VirtualMachineImagesClient) ListSkus(location string, publisherName string, offer string) (result ListVirtualMachineImageResource, err error) { func (client VirtualMachineImagesClient) ListSkus(location string, publisherName string, offer string) (result ListVirtualMachineImageResource, err error) {
req, err := client.ListSkusPreparer(location, publisherName, offer) req, err := client.ListSkusPreparer(location, publisherName, offer)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", nil, "Failure preparing request")
return
} }
resp, err := client.ListSkusSender(req) resp, err := client.ListSkusSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineImagesClient", "ListSkus", resp, "Failure sending request")
return
} }
result, err = client.ListSkusResponder(resp) result, err = client.ListSkusResponder(resp)
...@@ -344,8 +358,9 @@ func (client VirtualMachineImagesClient) ListSkusPreparer(location string, publi ...@@ -344,8 +358,9 @@ func (client VirtualMachineImagesClient) ListSkusPreparer(location string, publi
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
......
...@@ -14,7 +14,7 @@ package compute ...@@ -14,7 +14,7 @@ package compute
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -55,13 +55,15 @@ func (client VirtualMachineSizesClient) List(location string) (result VirtualMac ...@@ -55,13 +55,15 @@ func (client VirtualMachineSizesClient) List(location string) (result VirtualMac
req, err := client.ListPreparer(location) req, err := client.ListPreparer(location)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", nil, "Failure preparing request")
return
} }
resp, err := client.ListSender(req) resp, err := client.ListSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "compute.VirtualMachineSizesClient", "List", resp, "Failure sending request")
return
} }
result, err = client.ListResponder(resp) result, err = client.ListResponder(resp)
...@@ -79,8 +81,9 @@ func (client VirtualMachineSizesClient) ListPreparer(location string) (*http.Req ...@@ -79,8 +81,9 @@ func (client VirtualMachineSizesClient) ListPreparer(location string) (*http.Req
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2016-04-30-preview"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
......
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"client.go",
"models.go",
"registries.go",
"version.go",
],
tags = ["automanaged"],
deps = [
"//vendor/github.com/Azure/go-autorest/autorest:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/date:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/to:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/validation:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
// Package containerregistry implements the Azure ARM Containerregistry // Package containerregistry implements the Azure ARM Containerregistry service
// service API version 2016-06-27-preview. // API version 2017-03-01.
//
// //
package containerregistry package containerregistry
...@@ -17,7 +18,7 @@ package containerregistry ...@@ -17,7 +18,7 @@ package containerregistry
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -26,9 +27,6 @@ import ( ...@@ -26,9 +27,6 @@ import (
) )
const ( const (
// APIVersion is the version of the Containerregistry
APIVersion = "2016-06-27-preview"
// DefaultBaseURI is the default URI used for the service Containerregistry // DefaultBaseURI is the default URI used for the service Containerregistry
DefaultBaseURI = "https://management.azure.com" DefaultBaseURI = "https://management.azure.com"
) )
...@@ -37,7 +35,6 @@ const ( ...@@ -37,7 +35,6 @@ const (
type ManagementClient struct { type ManagementClient struct {
autorest.Client autorest.Client
BaseURI string BaseURI string
APIVersion string
SubscriptionID string SubscriptionID string
} }
...@@ -51,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { ...@@ -51,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {
return ManagementClient{ return ManagementClient{
Client: autorest.NewClientWithUserAgent(UserAgent()), Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI, BaseURI: baseURI,
APIVersion: APIVersion,
SubscriptionID: subscriptionID, SubscriptionID: subscriptionID,
} }
} }
...@@ -14,7 +14,7 @@ package containerregistry ...@@ -14,7 +14,7 @@ package containerregistry
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -25,6 +25,75 @@ import ( ...@@ -25,6 +25,75 @@ import (
"net/http" "net/http"
) )
// PasswordName enumerates the values for password name.
type PasswordName string
const (
// Password specifies the password state for password name.
Password PasswordName = "password"
// Password2 specifies the password 2 state for password name.
Password2 PasswordName = "password2"
)
// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string
const (
// Creating specifies the creating state for provisioning state.
Creating ProvisioningState = "Creating"
// Succeeded specifies the succeeded state for provisioning state.
Succeeded ProvisioningState = "Succeeded"
)
// SkuTier enumerates the values for sku tier.
type SkuTier string
const (
// Basic specifies the basic state for sku tier.
Basic SkuTier = "Basic"
)
// OperationDefinition is the definition of a container registry operation.
type OperationDefinition struct {
Name *string `json:"name,omitempty"`
Display *OperationDisplayDefinition `json:"display,omitempty"`
}
// OperationDisplayDefinition is the display information for a container
// registry operation.
type OperationDisplayDefinition struct {
Provider *string `json:"provider,omitempty"`
Resource *string `json:"resource,omitempty"`
Operation *string `json:"operation,omitempty"`
Description *string `json:"description,omitempty"`
}
// OperationListResult is the result of a request to list container registry
// operations.
type OperationListResult struct {
autorest.Response `json:"-"`
Value *[]OperationDefinition `json:"value,omitempty"`
NextLink *string `json:"nextLink,omitempty"`
}
// OperationListResultPreparer prepares a request to retrieve the next set of results. It returns
// nil if no more results exist.
func (client OperationListResult) OperationListResultPreparer() (*http.Request, error) {
if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
return nil, nil
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(to.String(client.NextLink)))
}
// RegenerateCredentialParameters is the parameters used to regenerate the
// login credential.
type RegenerateCredentialParameters struct {
Name PasswordName `json:"name,omitempty"`
}
// Registry is an object that represents a container registry. // Registry is an object that represents a container registry.
type Registry struct { type Registry struct {
autorest.Response `json:"-"` autorest.Response `json:"-"`
...@@ -33,15 +102,25 @@ type Registry struct { ...@@ -33,15 +102,25 @@ type Registry struct {
Type *string `json:"type,omitempty"` Type *string `json:"type,omitempty"`
Location *string `json:"location,omitempty"` Location *string `json:"location,omitempty"`
Tags *map[string]*string `json:"tags,omitempty"` Tags *map[string]*string `json:"tags,omitempty"`
Sku *Sku `json:"sku,omitempty"`
*RegistryProperties `json:"properties,omitempty"` *RegistryProperties `json:"properties,omitempty"`
} }
// RegistryCredentials is the result of a request to get the administrator // RegistryCreateParameters is the parameters for creating a container
// login credentials for a container registry. // registry.
type RegistryCredentials struct { type RegistryCreateParameters struct {
Tags *map[string]*string `json:"tags,omitempty"`
Location *string `json:"location,omitempty"`
Sku *Sku `json:"sku,omitempty"`
*RegistryPropertiesCreateParameters `json:"properties,omitempty"`
}
// RegistryListCredentialsResult is the response from the ListCredentials
// operation.
type RegistryListCredentialsResult struct {
autorest.Response `json:"-"` autorest.Response `json:"-"`
Username *string `json:"username,omitempty"` Username *string `json:"username,omitempty"`
Password *string `json:"password,omitempty"` Passwords *[]RegistryPassword `json:"passwords,omitempty"`
} }
// RegistryListResult is the result of a request to list container registries. // RegistryListResult is the result of a request to list container registries.
...@@ -63,15 +142,15 @@ func (client RegistryListResult) RegistryListResultPreparer() (*http.Request, er ...@@ -63,15 +142,15 @@ func (client RegistryListResult) RegistryListResultPreparer() (*http.Request, er
autorest.WithBaseURL(to.String(client.NextLink))) autorest.WithBaseURL(to.String(client.NextLink)))
} }
// RegistryNameCheckRequest is a request to check whether the container // RegistryNameCheckRequest is a request to check whether a container registry
// registry name is available. // name is available.
type RegistryNameCheckRequest struct { type RegistryNameCheckRequest struct {
Name *string `json:"name,omitempty"` Name *string `json:"name,omitempty"`
Type *string `json:"type,omitempty"` Type *string `json:"type,omitempty"`
} }
// RegistryNameStatus is the result of a request to check the availability of // RegistryNameStatus is the result of a request to check the availability of a
// a container registry name. // container registry name.
type RegistryNameStatus struct { type RegistryNameStatus struct {
autorest.Response `json:"-"` autorest.Response `json:"-"`
NameAvailable *bool `json:"nameAvailable,omitempty"` NameAvailable *bool `json:"nameAvailable,omitempty"`
...@@ -79,19 +158,33 @@ type RegistryNameStatus struct { ...@@ -79,19 +158,33 @@ type RegistryNameStatus struct {
Message *string `json:"message,omitempty"` Message *string `json:"message,omitempty"`
} }
// RegistryPassword is the login password for the container registry.
type RegistryPassword struct {
Name PasswordName `json:"name,omitempty"`
Value *string `json:"value,omitempty"`
}
// RegistryProperties is the properties of a container registry. // RegistryProperties is the properties of a container registry.
type RegistryProperties struct { type RegistryProperties struct {
LoginServer *string `json:"loginServer,omitempty"` LoginServer *string `json:"loginServer,omitempty"`
CreationDate *date.Time `json:"creationDate,omitempty"` CreationDate *date.Time `json:"creationDate,omitempty"`
ProvisioningState ProvisioningState `json:"provisioningState,omitempty"`
AdminUserEnabled *bool `json:"adminUserEnabled,omitempty"`
StorageAccount *StorageAccountProperties `json:"storageAccount,omitempty"`
}
// RegistryPropertiesCreateParameters is the parameters for creating the
// properties of a container registry.
type RegistryPropertiesCreateParameters struct {
AdminUserEnabled *bool `json:"adminUserEnabled,omitempty"` AdminUserEnabled *bool `json:"adminUserEnabled,omitempty"`
StorageAccount *StorageAccountProperties `json:"storageAccount,omitempty"` StorageAccount *StorageAccountParameters `json:"storageAccount,omitempty"`
} }
// RegistryPropertiesUpdateParameters is the parameters for updating the // RegistryPropertiesUpdateParameters is the parameters for updating the
// properties of a container registry. // properties of a container registry.
type RegistryPropertiesUpdateParameters struct { type RegistryPropertiesUpdateParameters struct {
AdminUserEnabled *bool `json:"adminUserEnabled,omitempty"` AdminUserEnabled *bool `json:"adminUserEnabled,omitempty"`
StorageAccount *StorageAccountProperties `json:"storageAccount,omitempty"` StorageAccount *StorageAccountParameters `json:"storageAccount,omitempty"`
} }
// RegistryUpdateParameters is the parameters for updating a container // RegistryUpdateParameters is the parameters for updating a container
...@@ -110,9 +203,21 @@ type Resource struct { ...@@ -110,9 +203,21 @@ type Resource struct {
Tags *map[string]*string `json:"tags,omitempty"` Tags *map[string]*string `json:"tags,omitempty"`
} }
// StorageAccountProperties is the properties of a storage account for a // Sku is the SKU of a container registry.
type Sku struct {
Name *string `json:"name,omitempty"`
Tier SkuTier `json:"tier,omitempty"`
}
// StorageAccountParameters is the parameters of a storage account for a
// container registry. // container registry.
type StorageAccountProperties struct { type StorageAccountParameters struct {
Name *string `json:"name,omitempty"` Name *string `json:"name,omitempty"`
AccessKey *string `json:"accessKey,omitempty"` AccessKey *string `json:"accessKey,omitempty"`
} }
// StorageAccountProperties is the properties of a storage account for a
// container registry.
type StorageAccountProperties struct {
Name *string `json:"name,omitempty"`
}
...@@ -14,30 +14,16 @@ package containerregistry ...@@ -14,30 +14,16 @@ package containerregistry
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
import (
"fmt"
)
const (
major = "7"
minor = "0"
patch = "1"
// Always begin a "tag" with a dash (as per http://semver.org)
tag = "-beta"
semVerFormat = "%s.%s.%s%s"
userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s"
)
// UserAgent returns the UserAgent string to use when sending http.Requests. // UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string { func UserAgent() string {
return fmt.Sprintf(userAgentFormat, Version(), "containerregistry", "2016-06-27-preview") return "Azure-SDK-For-Go/v10.0.2-beta arm-containerregistry/2017-03-01"
} }
// Version returns the semantic version (see http://semver.org) of the client. // Version returns the semantic version (see http://semver.org) of the client.
func Version() string { func Version() string {
return fmt.Sprintf(semVerFormat, major, minor, patch, tag) return "v10.0.2-beta"
} }
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"applicationgateways.go",
"client.go",
"expressroutecircuitauthorizations.go",
"expressroutecircuitpeerings.go",
"expressroutecircuits.go",
"expressrouteserviceproviders.go",
"interfaces.go",
"loadbalancers.go",
"localnetworkgateways.go",
"models.go",
"publicipaddresses.go",
"routes.go",
"routetables.go",
"securitygroups.go",
"securityrules.go",
"subnets.go",
"usages.go",
"version.go",
"virtualnetworkgatewayconnections.go",
"virtualnetworkgateways.go",
"virtualnetworkpeerings.go",
"virtualnetworks.go",
],
tags = ["automanaged"],
deps = [
"//vendor/github.com/Azure/go-autorest/autorest:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/to:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/validation:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
// Package network implements the Azure ARM Network service API version // Package network implements the Azure ARM Network service API version .
// 2016-09-01.
// //
// The Microsoft Azure Network management API provides a RESTful set of web // Composite Swagger for Network Client
// services that interact with Microsoft Azure Networks service to manage
// your network resources. The API has entities that capture the relationship
// between an end user and the Microsoft Azure Networks service.
package network package network
// Copyright (c) Microsoft and contributors. All rights reserved. // Copyright (c) Microsoft and contributors. All rights reserved.
...@@ -21,7 +17,7 @@ package network ...@@ -21,7 +17,7 @@ package network
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -32,9 +28,6 @@ import ( ...@@ -32,9 +28,6 @@ import (
) )
const ( const (
// APIVersion is the version of the Network
APIVersion = "2016-09-01"
// DefaultBaseURI is the default URI used for the service Network // DefaultBaseURI is the default URI used for the service Network
DefaultBaseURI = "https://management.azure.com" DefaultBaseURI = "https://management.azure.com"
) )
...@@ -43,7 +36,6 @@ const ( ...@@ -43,7 +36,6 @@ const (
type ManagementClient struct { type ManagementClient struct {
autorest.Client autorest.Client
BaseURI string BaseURI string
APIVersion string
SubscriptionID string SubscriptionID string
} }
...@@ -57,7 +49,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { ...@@ -57,7 +49,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {
return ManagementClient{ return ManagementClient{
Client: autorest.NewClientWithUserAgent(UserAgent()), Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI, BaseURI: baseURI,
APIVersion: APIVersion,
SubscriptionID: subscriptionID, SubscriptionID: subscriptionID,
} }
} }
...@@ -71,13 +62,15 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { ...@@ -71,13 +62,15 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {
func (client ManagementClient) CheckDNSNameAvailability(location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) { func (client ManagementClient) CheckDNSNameAvailability(location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) {
req, err := client.CheckDNSNameAvailabilityPreparer(location, domainNameLabel) req, err := client.CheckDNSNameAvailabilityPreparer(location, domainNameLabel)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", nil, "Failure preparing request")
return
} }
resp, err := client.CheckDNSNameAvailabilitySender(req) resp, err := client.CheckDNSNameAvailabilitySender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "network.ManagementClient", "CheckDNSNameAvailability", resp, "Failure sending request")
return
} }
result, err = client.CheckDNSNameAvailabilityResponder(resp) result, err = client.CheckDNSNameAvailabilityResponder(resp)
...@@ -95,8 +88,9 @@ func (client ManagementClient) CheckDNSNameAvailabilityPreparer(location string, ...@@ -95,8 +88,9 @@ func (client ManagementClient) CheckDNSNameAvailabilityPreparer(location string,
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2017-03-01"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
if len(domainNameLabel) > 0 { if len(domainNameLabel) > 0 {
queryParameters["domainNameLabel"] = autorest.Encode("query", domainNameLabel) queryParameters["domainNameLabel"] = autorest.Encode("query", domainNameLabel)
......
...@@ -14,7 +14,7 @@ package network ...@@ -14,7 +14,7 @@ package network
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -24,11 +24,8 @@ import ( ...@@ -24,11 +24,8 @@ import (
"net/http" "net/http"
) )
// ExpressRouteServiceProvidersClient is the the Microsoft Azure Network // ExpressRouteServiceProvidersClient is the composite Swagger for Network
// management API provides a RESTful set of web services that interact with // Client
// Microsoft Azure Networks service to manage your network resources. The API
// has entities that capture the relationship between an end user and the
// Microsoft Azure Networks service.
type ExpressRouteServiceProvidersClient struct { type ExpressRouteServiceProvidersClient struct {
ManagementClient ManagementClient
} }
...@@ -49,13 +46,15 @@ func NewExpressRouteServiceProvidersClientWithBaseURI(baseURI string, subscripti ...@@ -49,13 +46,15 @@ func NewExpressRouteServiceProvidersClientWithBaseURI(baseURI string, subscripti
func (client ExpressRouteServiceProvidersClient) List() (result ExpressRouteServiceProviderListResult, err error) { func (client ExpressRouteServiceProvidersClient) List() (result ExpressRouteServiceProviderListResult, err error) {
req, err := client.ListPreparer() req, err := client.ListPreparer()
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", nil, "Failure preparing request")
return
} }
resp, err := client.ListSender(req) resp, err := client.ListSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "network.ExpressRouteServiceProvidersClient", "List", resp, "Failure sending request")
return
} }
result, err = client.ListResponder(resp) result, err = client.ListResponder(resp)
...@@ -72,8 +71,9 @@ func (client ExpressRouteServiceProvidersClient) ListPreparer() (*http.Request, ...@@ -72,8 +71,9 @@ func (client ExpressRouteServiceProvidersClient) ListPreparer() (*http.Request,
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2017-03-01"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
......
...@@ -14,7 +14,7 @@ package network ...@@ -14,7 +14,7 @@ package network
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -25,11 +25,7 @@ import ( ...@@ -25,11 +25,7 @@ import (
"net/http" "net/http"
) )
// UsagesClient is the the Microsoft Azure Network management API provides a // UsagesClient is the composite Swagger for Network Client
// RESTful set of web services that interact with Microsoft Azure Networks
// service to manage your network resources. The API has entities that
// capture the relationship between an end user and the Microsoft Azure
// Networks service.
type UsagesClient struct { type UsagesClient struct {
ManagementClient ManagementClient
} }
...@@ -56,13 +52,15 @@ func (client UsagesClient) List(location string) (result UsagesListResult, err e ...@@ -56,13 +52,15 @@ func (client UsagesClient) List(location string) (result UsagesListResult, err e
req, err := client.ListPreparer(location) req, err := client.ListPreparer(location)
if err != nil { if err != nil {
return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing request") err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", nil, "Failure preparing request")
return
} }
resp, err := client.ListSender(req) resp, err := client.ListSender(req)
if err != nil { if err != nil {
result.Response = autorest.Response{Response: resp} result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending request") err = autorest.NewErrorWithError(err, "network.UsagesClient", "List", resp, "Failure sending request")
return
} }
result, err = client.ListResponder(resp) result, err = client.ListResponder(resp)
...@@ -80,8 +78,9 @@ func (client UsagesClient) ListPreparer(location string) (*http.Request, error) ...@@ -80,8 +78,9 @@ func (client UsagesClient) ListPreparer(location string) (*http.Request, error)
"subscriptionId": autorest.Encode("path", client.SubscriptionID), "subscriptionId": autorest.Encode("path", client.SubscriptionID),
} }
const APIVersion = "2017-03-01"
queryParameters := map[string]interface{}{ queryParameters := map[string]interface{}{
"api-version": client.APIVersion, "api-version": APIVersion,
} }
preparer := autorest.CreatePreparer( preparer := autorest.CreatePreparer(
......
...@@ -14,30 +14,16 @@ package network ...@@ -14,30 +14,16 @@ package network
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
import (
"fmt"
)
const (
major = "7"
minor = "0"
patch = "1"
// Always begin a "tag" with a dash (as per http://semver.org)
tag = "-beta"
semVerFormat = "%s.%s.%s%s"
userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s"
)
// UserAgent returns the UserAgent string to use when sending http.Requests. // UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string { func UserAgent() string {
return fmt.Sprintf(userAgentFormat, Version(), "network", "2016-09-01") return "Azure-SDK-For-Go/v10.0.2-beta arm-network/"
} }
// Version returns the semantic version (see http://semver.org) of the client. // Version returns the semantic version (see http://semver.org) of the client.
func Version() string { func Version() string {
return fmt.Sprintf(semVerFormat, major, minor, patch, tag) return "v10.0.2-beta"
} }
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"accounts.go",
"client.go",
"models.go",
"usageoperations.go",
"version.go",
],
tags = ["automanaged"],
deps = [
"//vendor/github.com/Azure/go-autorest/autorest:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/date:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/validation:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
// Package storage implements the Azure ARM Storage service API version // Package storage implements the Azure ARM Storage service API version
// 2016-01-01. // 2016-12-01.
// //
// The Storage Management Client. // The Azure Storage Management API.
package storage package storage
// Copyright (c) Microsoft and contributors. All rights reserved. // Copyright (c) Microsoft and contributors. All rights reserved.
...@@ -18,7 +18,7 @@ package storage ...@@ -18,7 +18,7 @@ package storage
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
...@@ -27,9 +27,6 @@ import ( ...@@ -27,9 +27,6 @@ import (
) )
const ( const (
// APIVersion is the version of the Storage
APIVersion = "2016-01-01"
// DefaultBaseURI is the default URI used for the service Storage // DefaultBaseURI is the default URI used for the service Storage
DefaultBaseURI = "https://management.azure.com" DefaultBaseURI = "https://management.azure.com"
) )
...@@ -38,7 +35,6 @@ const ( ...@@ -38,7 +35,6 @@ const (
type ManagementClient struct { type ManagementClient struct {
autorest.Client autorest.Client
BaseURI string BaseURI string
APIVersion string
SubscriptionID string SubscriptionID string
} }
...@@ -52,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient { ...@@ -52,7 +48,6 @@ func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {
return ManagementClient{ return ManagementClient{
Client: autorest.NewClientWithUserAgent(UserAgent()), Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI, BaseURI: baseURI,
APIVersion: APIVersion,
SubscriptionID: subscriptionID, SubscriptionID: subscriptionID,
} }
} }
package storage
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// UsageOperationsClient is the the Storage Management Client.
type UsageOperationsClient struct {
ManagementClient
}
// NewUsageOperationsClient creates an instance of the UsageOperationsClient
// client.
func NewUsageOperationsClient(subscriptionID string) UsageOperationsClient {
return NewUsageOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewUsageOperationsClientWithBaseURI creates an instance of the
// UsageOperationsClient client.
func NewUsageOperationsClientWithBaseURI(baseURI string, subscriptionID string) UsageOperationsClient {
return UsageOperationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List gets the current usage count and the limit for the resources under the
// subscription.
func (client UsageOperationsClient) List() (result UsageListResult, err error) {
req, err := client.ListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", nil, "Failure preparing request")
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", resp, "Failure sending request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storage.UsageOperationsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client UsageOperationsClient) ListPreparer() (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
queryParameters := map[string]interface{}{
"api-version": client.APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client UsageOperationsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client UsageOperationsClient) ListResponder(resp *http.Response) (result UsageListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
...@@ -14,30 +14,16 @@ package storage ...@@ -14,30 +14,16 @@ package storage
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is // Changes may cause incorrect behavior and will be lost if the code is
// regenerated. // regenerated.
import (
"fmt"
)
const (
major = "7"
minor = "0"
patch = "1"
// Always begin a "tag" with a dash (as per http://semver.org)
tag = "-beta"
semVerFormat = "%s.%s.%s%s"
userAgentFormat = "Azure-SDK-for-Go/%s arm-%s/%s"
)
// UserAgent returns the UserAgent string to use when sending http.Requests. // UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string { func UserAgent() string {
return fmt.Sprintf(userAgentFormat, Version(), "storage", "2016-01-01") return "Azure-SDK-For-Go/v10.0.2-beta arm-storage/2016-12-01"
} }
// Version returns the semantic version (see http://semver.org) of the client. // Version returns the semantic version (see http://semver.org) of the client.
func Version() string { func Version() string {
return fmt.Sprintf(semVerFormat, major, minor, patch, tag) return "v10.0.2-beta"
} }
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"blob.go",
"client.go",
"file.go",
"queue.go",
"table.go",
"table_entities.go",
"util.go",
],
tags = ["automanaged"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
# Azure Storage SDK for Go
The `github.com/Azure/azure-sdk-for-go/storage` package is used to perform operations in Azure Storage Service. To manage your storage accounts (Azure Resource Manager / ARM), use the [github.com/Azure/azure-sdk-for-go/arm/storage](../arm/storage) package. For your classic storage accounts (Azure Service Management / ASM), use [github.com/Azure/azure-sdk-for-go/management/storageservice](../management/storageservice) package.
This package includes support for [Azure Storage Emulator](https://azure.microsoft.com/documentation/articles/storage-use-emulator/)
\ No newline at end of file
...@@ -12,9 +12,15 @@ import ( ...@@ -12,9 +12,15 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"reflect" "reflect"
"strconv"
"strings"
"time" "time"
) )
var (
fixedTime = time.Date(2050, time.December, 20, 21, 55, 0, 0, time.FixedZone("GMT", -6))
)
func (c Client) computeHmac256(message string) string { func (c Client) computeHmac256(message string) string {
h := hmac.New(sha256.New, c.accountKey) h := hmac.New(sha256.New, c.accountKey)
h.Write([]byte(message)) h.Write([]byte(message))
...@@ -76,10 +82,118 @@ func headersFromStruct(v interface{}) map[string]string { ...@@ -76,10 +82,118 @@ func headersFromStruct(v interface{}) map[string]string {
value := reflect.ValueOf(v) value := reflect.ValueOf(v)
for i := 0; i < value.NumField(); i++ { for i := 0; i < value.NumField(); i++ {
key := value.Type().Field(i).Tag.Get("header") key := value.Type().Field(i).Tag.Get("header")
val := value.Field(i).String() if key != "" {
if key != "" && val != "" { reflectedValue := reflect.Indirect(value.Field(i))
headers[key] = val var val string
if reflectedValue.IsValid() {
switch reflectedValue.Type() {
case reflect.TypeOf(fixedTime):
val = timeRfc1123Formatted(reflectedValue.Interface().(time.Time))
case reflect.TypeOf(uint64(0)), reflect.TypeOf(uint(0)):
val = strconv.FormatUint(reflectedValue.Uint(), 10)
case reflect.TypeOf(int(0)):
val = strconv.FormatInt(reflectedValue.Int(), 10)
default:
val = reflectedValue.String()
}
}
if val != "" {
headers[key] = val
}
} }
} }
return headers return headers
} }
// merges extraHeaders into headers and returns headers
func mergeHeaders(headers, extraHeaders map[string]string) map[string]string {
for k, v := range extraHeaders {
headers[k] = v
}
return headers
}
func addToHeaders(h map[string]string, key, value string) map[string]string {
if value != "" {
h[key] = value
}
return h
}
func addTimeToHeaders(h map[string]string, key string, value *time.Time) map[string]string {
if value != nil {
h = addToHeaders(h, key, timeRfc1123Formatted(*value))
}
return h
}
func addTimeout(params url.Values, timeout uint) url.Values {
if timeout > 0 {
params.Add("timeout", fmt.Sprintf("%v", timeout))
}
return params
}
func addSnapshot(params url.Values, snapshot *time.Time) url.Values {
if snapshot != nil {
params.Add("snapshot", timeRfc1123Formatted(*snapshot))
}
return params
}
func getTimeFromHeaders(h http.Header, key string) (*time.Time, error) {
var out time.Time
var err error
outStr := h.Get(key)
if outStr != "" {
out, err = time.Parse(time.RFC1123, outStr)
if err != nil {
return nil, err
}
}
return &out, nil
}
// TimeRFC1123 is an alias for time.Time needed for custom Unmarshalling
type TimeRFC1123 time.Time
// UnmarshalXML is a custom unmarshaller that overrides the default time unmarshal which uses a different time layout.
func (t *TimeRFC1123) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var value string
d.DecodeElement(&value, &start)
parse, err := time.Parse(time.RFC1123, value)
if err != nil {
return err
}
*t = TimeRFC1123(parse)
return nil
}
// returns a map of custom metadata values from the specified HTTP header
func getMetadataFromHeaders(header http.Header) map[string]string {
metadata := make(map[string]string)
for k, v := range header {
// Can't trust CanonicalHeaderKey() to munge case
// reliably. "_" is allowed in identifiers:
// https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx
// https://msdn.microsoft.com/library/aa664670(VS.71).aspx
// http://tools.ietf.org/html/rfc7230#section-3.2
// ...but "_" is considered invalid by
// CanonicalMIMEHeaderKey in
// https://golang.org/src/net/textproto/reader.go?s=14615:14659#L542
// so k can be "X-Ms-Meta-Lol" or "x-ms-meta-lol_rofl".
k = strings.ToLower(k)
if len(v) == 0 || !strings.HasPrefix(k, strings.ToLower(userDefinedMetadataHeaderPrefix)) {
continue
}
// metadata["lol"] = content of the last X-Ms-Meta-Lol header
k = k[len(userDefinedMetadataHeaderPrefix):]
metadata[k] = v[len(v)-1]
}
if len(metadata) == 0 {
return nil
}
return metadata
}
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"constants.go",
"context.go",
"csi_entry_state.go",
"csi_param_state.go",
"escape_intermediate_state.go",
"escape_state.go",
"event_handler.go",
"ground_state.go",
"osc_string_state.go",
"parser.go",
"parser_action_helpers.go",
"parser_actions.go",
"parser_test_helpers.go",
"parser_test_utilities.go",
"states.go",
"test_event_handler.go",
"utilities.go",
],
tags = ["automanaged"],
deps = ["//vendor/github.com/Sirupsen/logrus:go_default_library"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
...@@ -7,3 +7,6 @@ For example the parser might receive "ESC, [, A" as a stream of three characters ...@@ -7,3 +7,6 @@ For example the parser might receive "ESC, [, A" as a stream of three characters
The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go). The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go).
See parser_test.go for examples exercising the state machine and generating appropriate function calls. See parser_test.go for examples exercising the state machine and generating appropriate function calls.
-----
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
...@@ -124,32 +124,32 @@ func getByteRange(start byte, end byte) []byte { ...@@ -124,32 +124,32 @@ func getByteRange(start byte, end byte) []byte {
return bytes return bytes
} }
var ToGroundBytes = getToGroundBytes() var toGroundBytes = getToGroundBytes()
var Executors = getExecuteBytes() var executors = getExecuteBytes()
// SPACE 20+A0 hex Always and everywhere a blank space // SPACE 20+A0 hex Always and everywhere a blank space
// Intermediate 20-2F hex !"#$%&'()*+,-./ // Intermediate 20-2F hex !"#$%&'()*+,-./
var Intermeds = getByteRange(0x20, 0x2F) var intermeds = getByteRange(0x20, 0x2F)
// Parameters 30-3F hex 0123456789:;<=>? // Parameters 30-3F hex 0123456789:;<=>?
// CSI Parameters 30-39, 3B hex 0123456789; // CSI Parameters 30-39, 3B hex 0123456789;
var CsiParams = getByteRange(0x30, 0x3F) var csiParams = getByteRange(0x30, 0x3F)
var CsiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...) var csiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...)
// Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ // Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
var UpperCase = getByteRange(0x40, 0x5F) var upperCase = getByteRange(0x40, 0x5F)
// Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~ // Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~
var LowerCase = getByteRange(0x60, 0x7E) var lowerCase = getByteRange(0x60, 0x7E)
// Alphabetics 40-7E hex (all of upper and lower case) // Alphabetics 40-7E hex (all of upper and lower case)
var Alphabetics = append(UpperCase, LowerCase...) var alphabetics = append(upperCase, lowerCase...)
var Printables = getByteRange(0x20, 0x7F) var printables = getByteRange(0x20, 0x7F)
var EscapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E) var escapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E)
var EscapeToGroundBytes = getEscapeToGroundBytes() var escapeToGroundBytes = getEscapeToGroundBytes()
// See http://www.vt100.net/emu/vt500_parser.png for description of the complex // See http://www.vt100.net/emu/vt500_parser.png for description of the complex
// byte ranges below // byte ranges below
......
package ansiterm package ansiterm
type AnsiContext struct { type ansiContext struct {
currentChar byte currentChar byte
paramBuffer []byte paramBuffer []byte
interBuffer []byte interBuffer []byte
......
package ansiterm package ansiterm
type CsiEntryState struct { type csiEntryState struct {
BaseState baseState
} }
func (csiState CsiEntryState) Handle(b byte) (s State, e error) { func (csiState csiEntryState) Handle(b byte) (s state, e error) {
logger.Infof("CsiEntry::Handle %#x", b) logger.Infof("CsiEntry::Handle %#x", b)
nextState, err := csiState.BaseState.Handle(b) nextState, err := csiState.baseState.Handle(b)
if nextState != nil || err != nil { if nextState != nil || err != nil {
return nextState, err return nextState, err
} }
switch { switch {
case sliceContains(Alphabetics, b): case sliceContains(alphabetics, b):
return csiState.parser.Ground, nil return csiState.parser.ground, nil
case sliceContains(CsiCollectables, b): case sliceContains(csiCollectables, b):
return csiState.parser.CsiParam, nil return csiState.parser.csiParam, nil
case sliceContains(Executors, b): case sliceContains(executors, b):
return csiState, csiState.parser.execute() return csiState, csiState.parser.execute()
} }
return csiState, nil return csiState, nil
} }
func (csiState CsiEntryState) Transition(s State) error { func (csiState csiEntryState) Transition(s state) error {
logger.Infof("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name()) logger.Infof("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name())
csiState.BaseState.Transition(s) csiState.baseState.Transition(s)
switch s { switch s {
case csiState.parser.Ground: case csiState.parser.ground:
return csiState.parser.csiDispatch() return csiState.parser.csiDispatch()
case csiState.parser.CsiParam: case csiState.parser.csiParam:
switch { switch {
case sliceContains(CsiParams, csiState.parser.context.currentChar): case sliceContains(csiParams, csiState.parser.context.currentChar):
csiState.parser.collectParam() csiState.parser.collectParam()
case sliceContains(Intermeds, csiState.parser.context.currentChar): case sliceContains(intermeds, csiState.parser.context.currentChar):
csiState.parser.collectInter() csiState.parser.collectInter()
} }
} }
...@@ -43,7 +43,7 @@ func (csiState CsiEntryState) Transition(s State) error { ...@@ -43,7 +43,7 @@ func (csiState CsiEntryState) Transition(s State) error {
return nil return nil
} }
func (csiState CsiEntryState) Enter() error { func (csiState csiEntryState) Enter() error {
csiState.parser.clear() csiState.parser.clear()
return nil return nil
} }
package ansiterm package ansiterm
type CsiParamState struct { type csiParamState struct {
BaseState baseState
} }
func (csiState CsiParamState) Handle(b byte) (s State, e error) { func (csiState csiParamState) Handle(b byte) (s state, e error) {
logger.Infof("CsiParam::Handle %#x", b) logger.Infof("CsiParam::Handle %#x", b)
nextState, err := csiState.BaseState.Handle(b) nextState, err := csiState.baseState.Handle(b)
if nextState != nil || err != nil { if nextState != nil || err != nil {
return nextState, err return nextState, err
} }
switch { switch {
case sliceContains(Alphabetics, b): case sliceContains(alphabetics, b):
return csiState.parser.Ground, nil return csiState.parser.ground, nil
case sliceContains(CsiCollectables, b): case sliceContains(csiCollectables, b):
csiState.parser.collectParam() csiState.parser.collectParam()
return csiState, nil return csiState, nil
case sliceContains(Executors, b): case sliceContains(executors, b):
return csiState, csiState.parser.execute() return csiState, csiState.parser.execute()
} }
return csiState, nil return csiState, nil
} }
func (csiState CsiParamState) Transition(s State) error { func (csiState csiParamState) Transition(s state) error {
logger.Infof("CsiParam::Transition %s --> %s", csiState.Name(), s.Name()) logger.Infof("CsiParam::Transition %s --> %s", csiState.Name(), s.Name())
csiState.BaseState.Transition(s) csiState.baseState.Transition(s)
switch s { switch s {
case csiState.parser.Ground: case csiState.parser.ground:
return csiState.parser.csiDispatch() return csiState.parser.csiDispatch()
} }
......
package ansiterm package ansiterm
type EscapeIntermediateState struct { type escapeIntermediateState struct {
BaseState baseState
} }
func (escState EscapeIntermediateState) Handle(b byte) (s State, e error) { func (escState escapeIntermediateState) Handle(b byte) (s state, e error) {
logger.Infof("EscapeIntermediateState::Handle %#x", b) logger.Infof("escapeIntermediateState::Handle %#x", b)
nextState, err := escState.BaseState.Handle(b) nextState, err := escState.baseState.Handle(b)
if nextState != nil || err != nil { if nextState != nil || err != nil {
return nextState, err return nextState, err
} }
switch { switch {
case sliceContains(Intermeds, b): case sliceContains(intermeds, b):
return escState, escState.parser.collectInter() return escState, escState.parser.collectInter()
case sliceContains(Executors, b): case sliceContains(executors, b):
return escState, escState.parser.execute() return escState, escState.parser.execute()
case sliceContains(EscapeIntermediateToGroundBytes, b): case sliceContains(escapeIntermediateToGroundBytes, b):
return escState.parser.Ground, nil return escState.parser.ground, nil
} }
return escState, nil return escState, nil
} }
func (escState EscapeIntermediateState) Transition(s State) error { func (escState escapeIntermediateState) Transition(s state) error {
logger.Infof("EscapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) logger.Infof("escapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name())
escState.BaseState.Transition(s) escState.baseState.Transition(s)
switch s { switch s {
case escState.parser.Ground: case escState.parser.ground:
return escState.parser.escDispatch() return escState.parser.escDispatch()
} }
......
package ansiterm package ansiterm
type EscapeState struct { type escapeState struct {
BaseState baseState
} }
func (escState EscapeState) Handle(b byte) (s State, e error) { func (escState escapeState) Handle(b byte) (s state, e error) {
logger.Infof("EscapeState::Handle %#x", b) logger.Infof("escapeState::Handle %#x", b)
nextState, err := escState.BaseState.Handle(b) nextState, err := escState.baseState.Handle(b)
if nextState != nil || err != nil { if nextState != nil || err != nil {
return nextState, err return nextState, err
} }
switch { switch {
case b == ANSI_ESCAPE_SECONDARY: case b == ANSI_ESCAPE_SECONDARY:
return escState.parser.CsiEntry, nil return escState.parser.csiEntry, nil
case b == ANSI_OSC_STRING_ENTRY: case b == ANSI_OSC_STRING_ENTRY:
return escState.parser.OscString, nil return escState.parser.oscString, nil
case sliceContains(Executors, b): case sliceContains(executors, b):
return escState, escState.parser.execute() return escState, escState.parser.execute()
case sliceContains(EscapeToGroundBytes, b): case sliceContains(escapeToGroundBytes, b):
return escState.parser.Ground, nil return escState.parser.ground, nil
case sliceContains(Intermeds, b): case sliceContains(intermeds, b):
return escState.parser.EscapeIntermediate, nil return escState.parser.escapeIntermediate, nil
} }
return escState, nil return escState, nil
} }
func (escState EscapeState) Transition(s State) error { func (escState escapeState) Transition(s state) error {
logger.Infof("Escape::Transition %s --> %s", escState.Name(), s.Name()) logger.Infof("Escape::Transition %s --> %s", escState.Name(), s.Name())
escState.BaseState.Transition(s) escState.baseState.Transition(s)
switch s { switch s {
case escState.parser.Ground: case escState.parser.ground:
return escState.parser.escDispatch() return escState.parser.escDispatch()
case escState.parser.EscapeIntermediate: case escState.parser.escapeIntermediate:
return escState.parser.collectInter() return escState.parser.collectInter()
} }
return nil return nil
} }
func (escState EscapeState) Enter() error { func (escState escapeState) Enter() error {
escState.parser.clear() escState.parser.clear()
return nil return nil
} }
package ansiterm package ansiterm
type GroundState struct { type groundState struct {
BaseState baseState
} }
func (gs GroundState) Handle(b byte) (s State, e error) { func (gs groundState) Handle(b byte) (s state, e error) {
gs.parser.context.currentChar = b gs.parser.context.currentChar = b
nextState, err := gs.BaseState.Handle(b) nextState, err := gs.baseState.Handle(b)
if nextState != nil || err != nil { if nextState != nil || err != nil {
return nextState, err return nextState, err
} }
switch { switch {
case sliceContains(Printables, b): case sliceContains(printables, b):
return gs, gs.parser.print() return gs, gs.parser.print()
case sliceContains(Executors, b): case sliceContains(executors, b):
return gs, gs.parser.execute() return gs, gs.parser.execute()
} }
......
package ansiterm package ansiterm
type OscStringState struct { type oscStringState struct {
BaseState baseState
} }
func (oscState OscStringState) Handle(b byte) (s State, e error) { func (oscState oscStringState) Handle(b byte) (s state, e error) {
logger.Infof("OscString::Handle %#x", b) logger.Infof("OscString::Handle %#x", b)
nextState, err := oscState.BaseState.Handle(b) nextState, err := oscState.baseState.Handle(b)
if nextState != nil || err != nil { if nextState != nil || err != nil {
return nextState, err return nextState, err
} }
switch { switch {
case isOscStringTerminator(b): case isOscStringTerminator(b):
return oscState.parser.Ground, nil return oscState.parser.ground, nil
} }
return oscState, nil return oscState, nil
......
...@@ -2,7 +2,6 @@ package ansiterm ...@@ -2,7 +2,6 @@ package ansiterm
import ( import (
"errors" "errors"
"fmt"
"io/ioutil" "io/ioutil"
"os" "os"
...@@ -12,18 +11,18 @@ import ( ...@@ -12,18 +11,18 @@ import (
var logger *logrus.Logger var logger *logrus.Logger
type AnsiParser struct { type AnsiParser struct {
currState State currState state
eventHandler AnsiEventHandler eventHandler AnsiEventHandler
context *AnsiContext context *ansiContext
CsiEntry State csiEntry state
CsiParam State csiParam state
DcsEntry State dcsEntry state
Escape State escape state
EscapeIntermediate State escapeIntermediate state
Error State error state
Ground State ground state
OscString State oscString state
stateMap []State stateMap []state
} }
func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser { func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser {
...@@ -41,27 +40,27 @@ func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser ...@@ -41,27 +40,27 @@ func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser
parser := &AnsiParser{ parser := &AnsiParser{
eventHandler: evtHandler, eventHandler: evtHandler,
context: &AnsiContext{}, context: &ansiContext{},
} }
parser.CsiEntry = CsiEntryState{BaseState{name: "CsiEntry", parser: parser}} parser.csiEntry = csiEntryState{baseState{name: "CsiEntry", parser: parser}}
parser.CsiParam = CsiParamState{BaseState{name: "CsiParam", parser: parser}} parser.csiParam = csiParamState{baseState{name: "CsiParam", parser: parser}}
parser.DcsEntry = DcsEntryState{BaseState{name: "DcsEntry", parser: parser}} parser.dcsEntry = dcsEntryState{baseState{name: "DcsEntry", parser: parser}}
parser.Escape = EscapeState{BaseState{name: "Escape", parser: parser}} parser.escape = escapeState{baseState{name: "Escape", parser: parser}}
parser.EscapeIntermediate = EscapeIntermediateState{BaseState{name: "EscapeIntermediate", parser: parser}} parser.escapeIntermediate = escapeIntermediateState{baseState{name: "EscapeIntermediate", parser: parser}}
parser.Error = ErrorState{BaseState{name: "Error", parser: parser}} parser.error = errorState{baseState{name: "Error", parser: parser}}
parser.Ground = GroundState{BaseState{name: "Ground", parser: parser}} parser.ground = groundState{baseState{name: "Ground", parser: parser}}
parser.OscString = OscStringState{BaseState{name: "OscString", parser: parser}} parser.oscString = oscStringState{baseState{name: "OscString", parser: parser}}
parser.stateMap = []State{ parser.stateMap = []state{
parser.CsiEntry, parser.csiEntry,
parser.CsiParam, parser.csiParam,
parser.DcsEntry, parser.dcsEntry,
parser.Escape, parser.escape,
parser.EscapeIntermediate, parser.escapeIntermediate,
parser.Error, parser.error,
parser.Ground, parser.ground,
parser.OscString, parser.oscString,
} }
parser.currState = getState(initialState, parser.stateMap) parser.currState = getState(initialState, parser.stateMap)
...@@ -70,7 +69,7 @@ func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser ...@@ -70,7 +69,7 @@ func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser
return parser return parser
} }
func getState(name string, states []State) State { func getState(name string, states []state) state {
for _, el := range states { for _, el := range states {
if el.Name() == name { if el.Name() == name {
return el return el
...@@ -99,7 +98,7 @@ func (ap *AnsiParser) handle(b byte) error { ...@@ -99,7 +98,7 @@ func (ap *AnsiParser) handle(b byte) error {
if newState == nil { if newState == nil {
logger.Warning("newState is nil") logger.Warning("newState is nil")
return errors.New(fmt.Sprintf("New state of 'nil' is invalid.")) return errors.New("New state of 'nil' is invalid.")
} }
if newState != ap.currState { if newState != ap.currState {
...@@ -111,7 +110,7 @@ func (ap *AnsiParser) handle(b byte) error { ...@@ -111,7 +110,7 @@ func (ap *AnsiParser) handle(b byte) error {
return nil return nil
} }
func (ap *AnsiParser) changeState(newState State) error { func (ap *AnsiParser) changeState(newState state) error {
logger.Infof("ChangeState %s --> %s", ap.currState.Name(), newState.Name()) logger.Infof("ChangeState %s --> %s", ap.currState.Name(), newState.Name())
// Exit old state // Exit old state
......
...@@ -31,7 +31,7 @@ func parseParams(bytes []byte) ([]string, error) { ...@@ -31,7 +31,7 @@ func parseParams(bytes []byte) ([]string, error) {
return params, nil return params, nil
} }
func parseCmd(context AnsiContext) (string, error) { func parseCmd(context ansiContext) (string, error) {
return string(context.currentChar), nil return string(context.currentChar), nil
} }
......
...@@ -113,7 +113,7 @@ func (ap *AnsiParser) print() error { ...@@ -113,7 +113,7 @@ func (ap *AnsiParser) print() error {
} }
func (ap *AnsiParser) clear() error { func (ap *AnsiParser) clear() error {
ap.context = &AnsiContext{} ap.context = &ansiContext{}
return nil return nil
} }
......
package ansiterm
import (
"fmt"
"testing"
)
func getStateNames() []string {
parser, _ := createTestParser("Ground")
stateNames := []string{}
for _, state := range parser.stateMap {
stateNames = append(stateNames, state.Name())
}
return stateNames
}
func stateTransitionHelper(t *testing.T, start string, end string, bytes []byte) {
for _, b := range bytes {
bytes := []byte{byte(b)}
parser, _ := createTestParser(start)
parser.Parse(bytes)
validateState(t, parser.currState, end)
}
}
func anyToXHelper(t *testing.T, bytes []byte, expectedState string) {
for _, s := range getStateNames() {
stateTransitionHelper(t, s, expectedState, bytes)
}
}
func funcCallParamHelper(t *testing.T, bytes []byte, start string, expected string, expectedCalls []string) {
parser, evtHandler := createTestParser(start)
parser.Parse(bytes)
validateState(t, parser.currState, expected)
validateFuncCalls(t, evtHandler.FunctionCalls, expectedCalls)
}
func parseParamsHelper(t *testing.T, bytes []byte, expectedParams []string) {
params, err := parseParams(bytes)
if err != nil {
t.Errorf("Parameter parse error: %v", err)
return
}
if len(params) != len(expectedParams) {
t.Errorf("Parsed parameters: %v", params)
t.Errorf("Expected parameters: %v", expectedParams)
t.Errorf("Parameter length failure: %d != %d", len(params), len(expectedParams))
return
}
for i, v := range expectedParams {
if v != params[i] {
t.Errorf("Parsed parameters: %v", params)
t.Errorf("Expected parameters: %v", expectedParams)
t.Errorf("Parameter parse failure: %s != %s at position %d", v, params[i], i)
}
}
}
func cursorSingleParamHelper(t *testing.T, command byte, funcName string) {
funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)})
funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)})
funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)})
funcCallParamHelper(t, []byte{'2', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([23])", funcName)})
funcCallParamHelper(t, []byte{'2', ';', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)})
funcCallParamHelper(t, []byte{'2', ';', '3', ';', '4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)})
}
func cursorTwoParamHelper(t *testing.T, command byte, funcName string) {
funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1 1])", funcName)})
funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1 1])", funcName)})
funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 1])", funcName)})
funcCallParamHelper(t, []byte{'2', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([23 1])", funcName)})
funcCallParamHelper(t, []byte{'2', ';', '3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 3])", funcName)})
funcCallParamHelper(t, []byte{'2', ';', '3', ';', '4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2 3])", funcName)})
}
func eraseHelper(t *testing.T, command byte, funcName string) {
funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)})
funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)})
funcCallParamHelper(t, []byte{'1', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)})
funcCallParamHelper(t, []byte{'2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([2])", funcName)})
funcCallParamHelper(t, []byte{'3', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([3])", funcName)})
funcCallParamHelper(t, []byte{'4', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([0])", funcName)})
funcCallParamHelper(t, []byte{'1', ';', '2', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)})
}
func scrollHelper(t *testing.T, command byte, funcName string) {
funcCallParamHelper(t, []byte{command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)})
funcCallParamHelper(t, []byte{'0', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)})
funcCallParamHelper(t, []byte{'1', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([1])", funcName)})
funcCallParamHelper(t, []byte{'5', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([5])", funcName)})
funcCallParamHelper(t, []byte{'4', ';', '6', command}, "CsiEntry", "Ground", []string{fmt.Sprintf("%s([4])", funcName)})
}
func clearOnStateChangeHelper(t *testing.T, start string, end string, bytes []byte) {
p, _ := createTestParser(start)
fillContext(p.context)
p.Parse(bytes)
validateState(t, p.currState, end)
validateEmptyContext(t, p.context)
}
func c0Helper(t *testing.T, bytes []byte, expectedState string, expectedCalls []string) {
parser, evtHandler := createTestParser("Ground")
parser.Parse(bytes)
validateState(t, parser.currState, expectedState)
validateFuncCalls(t, evtHandler.FunctionCalls, expectedCalls)
}
package ansiterm
import (
"testing"
)
func createTestParser(s string) (*AnsiParser, *TestAnsiEventHandler) {
evtHandler := CreateTestAnsiEventHandler()
parser := CreateParser(s, evtHandler)
return parser, evtHandler
}
func validateState(t *testing.T, actualState State, expectedStateName string) {
actualName := "Nil"
if actualState != nil {
actualName = actualState.Name()
}
if actualName != expectedStateName {
t.Errorf("Invalid State: '%s' != '%s'", actualName, expectedStateName)
}
}
func validateFuncCalls(t *testing.T, actualCalls []string, expectedCalls []string) {
actualCount := len(actualCalls)
expectedCount := len(expectedCalls)
if actualCount != expectedCount {
t.Errorf("Actual calls: %v", actualCalls)
t.Errorf("Expected calls: %v", expectedCalls)
t.Errorf("Call count error: %d != %d", actualCount, expectedCount)
return
}
for i, v := range actualCalls {
if v != expectedCalls[i] {
t.Errorf("Actual calls: %v", actualCalls)
t.Errorf("Expected calls: %v", expectedCalls)
t.Errorf("Mismatched calls: %s != %s with lengths %d and %d", v, expectedCalls[i], len(v), len(expectedCalls[i]))
}
}
}
func fillContext(context *AnsiContext) {
context.currentChar = 'A'
context.paramBuffer = []byte{'C', 'D', 'E'}
context.interBuffer = []byte{'F', 'G', 'H'}
}
func validateEmptyContext(t *testing.T, context *AnsiContext) {
var expectedCurrChar byte = 0x0
if context.currentChar != expectedCurrChar {
t.Errorf("Currentchar mismatch '%#x' != '%#x'", context.currentChar, expectedCurrChar)
}
if len(context.paramBuffer) != 0 {
t.Errorf("Non-empty parameter buffer: %v", context.paramBuffer)
}
if len(context.paramBuffer) != 0 {
t.Errorf("Non-empty intermediate buffer: %v", context.interBuffer)
}
}
package ansiterm package ansiterm
type StateId int type stateID int
type State interface { type state interface {
Enter() error Enter() error
Exit() error Exit() error
Handle(byte) (State, error) Handle(byte) (state, error)
Name() string Name() string
Transition(State) error Transition(state) error
} }
type BaseState struct { type baseState struct {
name string name string
parser *AnsiParser parser *AnsiParser
} }
func (base BaseState) Enter() error { func (base baseState) Enter() error {
return nil return nil
} }
func (base BaseState) Exit() error { func (base baseState) Exit() error {
return nil return nil
} }
func (base BaseState) Handle(b byte) (s State, e error) { func (base baseState) Handle(b byte) (s state, e error) {
switch { switch {
case b == CSI_ENTRY: case b == CSI_ENTRY:
return base.parser.CsiEntry, nil return base.parser.csiEntry, nil
case b == DCS_ENTRY: case b == DCS_ENTRY:
return base.parser.DcsEntry, nil return base.parser.dcsEntry, nil
case b == ANSI_ESCAPE_PRIMARY: case b == ANSI_ESCAPE_PRIMARY:
return base.parser.Escape, nil return base.parser.escape, nil
case b == OSC_STRING: case b == OSC_STRING:
return base.parser.OscString, nil return base.parser.oscString, nil
case sliceContains(ToGroundBytes, b): case sliceContains(toGroundBytes, b):
return base.parser.Ground, nil return base.parser.ground, nil
} }
return nil, nil return nil, nil
} }
func (base BaseState) Name() string { func (base baseState) Name() string {
return base.name return base.name
} }
func (base BaseState) Transition(s State) error { func (base baseState) Transition(s state) error {
if s == base.parser.Ground { if s == base.parser.ground {
execBytes := []byte{0x18} execBytes := []byte{0x18}
execBytes = append(execBytes, 0x1A) execBytes = append(execBytes, 0x1A)
execBytes = append(execBytes, getByteRange(0x80, 0x8F)...) execBytes = append(execBytes, getByteRange(0x80, 0x8F)...)
...@@ -62,10 +62,10 @@ func (base BaseState) Transition(s State) error { ...@@ -62,10 +62,10 @@ func (base BaseState) Transition(s State) error {
return nil return nil
} }
type DcsEntryState struct { type dcsEntryState struct {
BaseState baseState
} }
type ErrorState struct { type errorState struct {
BaseState baseState
} }
package ansiterm
import (
"fmt"
"strconv"
)
type TestAnsiEventHandler struct {
FunctionCalls []string
}
func CreateTestAnsiEventHandler() *TestAnsiEventHandler {
evtHandler := TestAnsiEventHandler{}
evtHandler.FunctionCalls = make([]string, 0)
return &evtHandler
}
func (h *TestAnsiEventHandler) recordCall(call string, params []string) {
s := fmt.Sprintf("%s(%v)", call, params)
h.FunctionCalls = append(h.FunctionCalls, s)
}
func (h *TestAnsiEventHandler) Print(b byte) error {
h.recordCall("Print", []string{string(b)})
return nil
}
func (h *TestAnsiEventHandler) Execute(b byte) error {
h.recordCall("Execute", []string{string(b)})
return nil
}
func (h *TestAnsiEventHandler) CUU(param int) error {
h.recordCall("CUU", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) CUD(param int) error {
h.recordCall("CUD", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) CUF(param int) error {
h.recordCall("CUF", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) CUB(param int) error {
h.recordCall("CUB", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) CNL(param int) error {
h.recordCall("CNL", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) CPL(param int) error {
h.recordCall("CPL", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) CHA(param int) error {
h.recordCall("CHA", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) VPA(param int) error {
h.recordCall("VPA", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) CUP(x int, y int) error {
xS, yS := strconv.Itoa(x), strconv.Itoa(y)
h.recordCall("CUP", []string{xS, yS})
return nil
}
func (h *TestAnsiEventHandler) HVP(x int, y int) error {
xS, yS := strconv.Itoa(x), strconv.Itoa(y)
h.recordCall("HVP", []string{xS, yS})
return nil
}
func (h *TestAnsiEventHandler) DECTCEM(visible bool) error {
h.recordCall("DECTCEM", []string{strconv.FormatBool(visible)})
return nil
}
func (h *TestAnsiEventHandler) DECOM(visible bool) error {
h.recordCall("DECOM", []string{strconv.FormatBool(visible)})
return nil
}
func (h *TestAnsiEventHandler) DECCOLM(use132 bool) error {
h.recordCall("DECOLM", []string{strconv.FormatBool(use132)})
return nil
}
func (h *TestAnsiEventHandler) ED(param int) error {
h.recordCall("ED", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) EL(param int) error {
h.recordCall("EL", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) IL(param int) error {
h.recordCall("IL", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) DL(param int) error {
h.recordCall("DL", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) ICH(param int) error {
h.recordCall("ICH", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) DCH(param int) error {
h.recordCall("DCH", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) SGR(params []int) error {
strings := []string{}
for _, v := range params {
strings = append(strings, strconv.Itoa(v))
}
h.recordCall("SGR", strings)
return nil
}
func (h *TestAnsiEventHandler) SU(param int) error {
h.recordCall("SU", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) SD(param int) error {
h.recordCall("SD", []string{strconv.Itoa(param)})
return nil
}
func (h *TestAnsiEventHandler) DA(params []string) error {
h.recordCall("DA", params)
return nil
}
func (h *TestAnsiEventHandler) DECSTBM(top int, bottom int) error {
topS, bottomS := strconv.Itoa(top), strconv.Itoa(bottom)
h.recordCall("DECSTBM", []string{topS, bottomS})
return nil
}
func (h *TestAnsiEventHandler) RI() error {
h.recordCall("RI", nil)
return nil
}
func (h *TestAnsiEventHandler) IND() error {
h.recordCall("IND", nil)
return nil
}
func (h *TestAnsiEventHandler) Flush() error {
return nil
}
...@@ -9,7 +9,7 @@ import ( ...@@ -9,7 +9,7 @@ import (
"strings" "strings"
"syscall" "syscall"
. "github.com/Azure/go-ansiterm" "github.com/Azure/go-ansiterm"
) )
// Windows keyboard constants // Windows keyboard constants
...@@ -85,17 +85,17 @@ func newAnsiCommand(command []byte) *ansiCommand { ...@@ -85,17 +85,17 @@ func newAnsiCommand(command []byte) *ansiCommand {
if lastCharIndex != 0 { if lastCharIndex != 0 {
start := 1 start := 1
// skip if double char escape sequence // skip if double char escape sequence
if command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_ESCAPE_SECONDARY { if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY {
start++ start++
} }
// convert this to GetNextParam method // convert this to GetNextParam method
ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ANSI_PARAMETER_SEP) ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP)
} }
return ac return ac
} }
func (ac *ansiCommand) paramAsSHORT(index int, defaultValue SHORT) SHORT { func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 {
if index < 0 || index >= len(ac.Parameters) { if index < 0 || index >= len(ac.Parameters) {
return defaultValue return defaultValue
} }
...@@ -105,7 +105,7 @@ func (ac *ansiCommand) paramAsSHORT(index int, defaultValue SHORT) SHORT { ...@@ -105,7 +105,7 @@ func (ac *ansiCommand) paramAsSHORT(index int, defaultValue SHORT) SHORT {
return defaultValue return defaultValue
} }
return SHORT(param) return int16(param)
} }
func (ac *ansiCommand) String() string { func (ac *ansiCommand) String() string {
...@@ -119,12 +119,12 @@ func (ac *ansiCommand) String() string { ...@@ -119,12 +119,12 @@ func (ac *ansiCommand) String() string {
// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. // See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html.
func isAnsiCommandChar(b byte) bool { func isAnsiCommandChar(b byte) bool {
switch { switch {
case ANSI_COMMAND_FIRST <= b && b <= ANSI_COMMAND_LAST && b != ANSI_ESCAPE_SECONDARY: case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY:
return true return true
case b == ANSI_CMD_G1 || b == ANSI_CMD_OSC || b == ANSI_CMD_DECPAM || b == ANSI_CMD_DECPNM: case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM:
// non-CSI escape sequence terminator // non-CSI escape sequence terminator
return true return true
case b == ANSI_CMD_STR_TERM || b == ANSI_BEL: case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL:
// String escape sequence terminator // String escape sequence terminator
return true return true
} }
...@@ -132,11 +132,11 @@ func isAnsiCommandChar(b byte) bool { ...@@ -132,11 +132,11 @@ func isAnsiCommandChar(b byte) bool {
} }
func isXtermOscSequence(command []byte, current byte) bool { func isXtermOscSequence(command []byte, current byte) bool {
return (len(command) >= 2 && command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_CMD_OSC && current != ANSI_BEL) return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL)
} }
func isCharacterSelectionCmdChar(b byte) bool { func isCharacterSelectionCmdChar(b byte) bool {
return (b == ANSI_CMD_G0 || b == ANSI_CMD_G1 || b == ANSI_CMD_G2 || b == ANSI_CMD_G3) return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3)
} }
// bytesToHex converts a slice of bytes to a human-readable string. // bytesToHex converts a slice of bytes to a human-readable string.
...@@ -150,7 +150,7 @@ func bytesToHex(b []byte) string { ...@@ -150,7 +150,7 @@ func bytesToHex(b []byte) string {
// ensureInRange adjusts the passed value, if necessary, to ensure it is within // ensureInRange adjusts the passed value, if necessary, to ensure it is within
// the passed min / max range. // the passed min / max range.
func ensureInRange(n SHORT, min SHORT, max SHORT) SHORT { func ensureInRange(n int16, min int16, max int16) int16 {
if n < min { if n < min {
return min return min
} else if n > max { } else if n > max {
......
...@@ -66,21 +66,21 @@ const ( ...@@ -66,21 +66,21 @@ const (
// -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan). // -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan).
// Clearing all foreground or background colors results in black; setting all creates white. // Clearing all foreground or background colors results in black; setting all creates white.
// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes.
FOREGROUND_BLUE WORD = 0x0001 FOREGROUND_BLUE uint16 = 0x0001
FOREGROUND_GREEN WORD = 0x0002 FOREGROUND_GREEN uint16 = 0x0002
FOREGROUND_RED WORD = 0x0004 FOREGROUND_RED uint16 = 0x0004
FOREGROUND_INTENSITY WORD = 0x0008 FOREGROUND_INTENSITY uint16 = 0x0008
FOREGROUND_MASK WORD = 0x000F FOREGROUND_MASK uint16 = 0x000F
BACKGROUND_BLUE WORD = 0x0010 BACKGROUND_BLUE uint16 = 0x0010
BACKGROUND_GREEN WORD = 0x0020 BACKGROUND_GREEN uint16 = 0x0020
BACKGROUND_RED WORD = 0x0040 BACKGROUND_RED uint16 = 0x0040
BACKGROUND_INTENSITY WORD = 0x0080 BACKGROUND_INTENSITY uint16 = 0x0080
BACKGROUND_MASK WORD = 0x00F0 BACKGROUND_MASK uint16 = 0x00F0
COMMON_LVB_MASK WORD = 0xFF00 COMMON_LVB_MASK uint16 = 0xFF00
COMMON_LVB_REVERSE_VIDEO WORD = 0x4000 COMMON_LVB_REVERSE_VIDEO uint16 = 0x4000
COMMON_LVB_UNDERSCORE WORD = 0x8000 COMMON_LVB_UNDERSCORE uint16 = 0x8000
// Input event types // Input event types
// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx.
...@@ -104,60 +104,53 @@ const ( ...@@ -104,60 +104,53 @@ const (
) )
// Windows API Console types // Windows API Console types
// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx for core types (e.g., SHORT)
// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD) // -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD)
// -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment // -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment
type ( type (
SHORT int16
BOOL int32
WORD uint16
WCHAR uint16
DWORD uint32
CHAR_INFO struct { CHAR_INFO struct {
UnicodeChar WCHAR UnicodeChar uint16
Attributes WORD Attributes uint16
} }
CONSOLE_CURSOR_INFO struct { CONSOLE_CURSOR_INFO struct {
Size DWORD Size uint32
Visible BOOL Visible int32
} }
CONSOLE_SCREEN_BUFFER_INFO struct { CONSOLE_SCREEN_BUFFER_INFO struct {
Size COORD Size COORD
CursorPosition COORD CursorPosition COORD
Attributes WORD Attributes uint16
Window SMALL_RECT Window SMALL_RECT
MaximumWindowSize COORD MaximumWindowSize COORD
} }
COORD struct { COORD struct {
X SHORT X int16
Y SHORT Y int16
} }
SMALL_RECT struct { SMALL_RECT struct {
Left SHORT Left int16
Top SHORT Top int16
Right SHORT Right int16
Bottom SHORT Bottom int16
} }
// INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest // INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest
// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx.
INPUT_RECORD struct { INPUT_RECORD struct {
EventType WORD EventType uint16
KeyEvent KEY_EVENT_RECORD KeyEvent KEY_EVENT_RECORD
} }
KEY_EVENT_RECORD struct { KEY_EVENT_RECORD struct {
KeyDown BOOL KeyDown int32
RepeatCount WORD RepeatCount uint16
VirtualKeyCode WORD VirtualKeyCode uint16
VirtualScanCode WORD VirtualScanCode uint16
UnicodeChar WCHAR UnicodeChar uint16
ControlKeyState DWORD ControlKeyState uint32
} }
WINDOW_BUFFER_SIZE struct { WINDOW_BUFFER_SIZE struct {
...@@ -165,12 +158,12 @@ type ( ...@@ -165,12 +158,12 @@ type (
} }
) )
// boolToBOOL converts a Go bool into a Windows BOOL. // boolToBOOL converts a Go bool into a Windows int32.
func boolToBOOL(f bool) BOOL { func boolToBOOL(f bool) int32 {
if f { if f {
return BOOL(1) return int32(1)
} else { } else {
return BOOL(0) return int32(0)
} }
} }
...@@ -242,7 +235,7 @@ func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error { ...@@ -242,7 +235,7 @@ func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error {
// SetConsoleTextAttribute sets the attributes of characters written to the // SetConsoleTextAttribute sets the attributes of characters written to the
// console screen buffer by the WriteFile or WriteConsole function. // console screen buffer by the WriteFile or WriteConsole function.
// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx.
func SetConsoleTextAttribute(handle uintptr, attribute WORD) error { func SetConsoleTextAttribute(handle uintptr, attribute uint16) error {
r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0) r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0)
use(attribute) use(attribute)
return checkError(r1, r2, err) return checkError(r1, r2, err)
...@@ -280,7 +273,7 @@ func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) erro ...@@ -280,7 +273,7 @@ func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) erro
// It returns true if the handle was signaled; false otherwise. // It returns true if the handle was signaled; false otherwise.
// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx. // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx.
func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) { func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) {
r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(DWORD(msWait))) r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(uint32(msWait)))
switch r1 { switch r1 {
case WAIT_ABANDONED, WAIT_TIMEOUT: case WAIT_ABANDONED, WAIT_TIMEOUT:
return false, nil return false, nil
...@@ -320,8 +313,8 @@ func checkError(r1, r2 uintptr, err error) error { ...@@ -320,8 +313,8 @@ func checkError(r1, r2 uintptr, err error) error {
// coordToPointer converts a COORD into a uintptr (by fooling the type system). // coordToPointer converts a COORD into a uintptr (by fooling the type system).
func coordToPointer(c COORD) uintptr { func coordToPointer(c COORD) uintptr {
// Note: This code assumes the two SHORTs are correctly laid out; the "cast" to DWORD is just to get a pointer to pass. // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to uint32 is just to get a pointer to pass.
return uintptr(*((*DWORD)(unsafe.Pointer(&c)))) return uintptr(*((*uint32)(unsafe.Pointer(&c))))
} }
// use is a no-op, but the compiler cannot see that it is. // use is a no-op, but the compiler cannot see that it is.
......
...@@ -2,9 +2,7 @@ ...@@ -2,9 +2,7 @@
package winterm package winterm
import ( import "github.com/Azure/go-ansiterm"
. "github.com/Azure/go-ansiterm"
)
const ( const (
FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
...@@ -13,83 +11,83 @@ const ( ...@@ -13,83 +11,83 @@ const (
// collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the // collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the
// request represented by the passed ANSI mode. // request represented by the passed ANSI mode.
func collectAnsiIntoWindowsAttributes(windowsMode WORD, inverted bool, baseMode WORD, ansiMode SHORT) (WORD, bool) { func collectAnsiIntoWindowsAttributes(windowsMode uint16, inverted bool, baseMode uint16, ansiMode int16) (uint16, bool) {
switch ansiMode { switch ansiMode {
// Mode styles // Mode styles
case ANSI_SGR_BOLD: case ansiterm.ANSI_SGR_BOLD:
windowsMode = windowsMode | FOREGROUND_INTENSITY windowsMode = windowsMode | FOREGROUND_INTENSITY
case ANSI_SGR_DIM, ANSI_SGR_BOLD_DIM_OFF: case ansiterm.ANSI_SGR_DIM, ansiterm.ANSI_SGR_BOLD_DIM_OFF:
windowsMode &^= FOREGROUND_INTENSITY windowsMode &^= FOREGROUND_INTENSITY
case ANSI_SGR_UNDERLINE: case ansiterm.ANSI_SGR_UNDERLINE:
windowsMode = windowsMode | COMMON_LVB_UNDERSCORE windowsMode = windowsMode | COMMON_LVB_UNDERSCORE
case ANSI_SGR_REVERSE: case ansiterm.ANSI_SGR_REVERSE:
inverted = true inverted = true
case ANSI_SGR_REVERSE_OFF: case ansiterm.ANSI_SGR_REVERSE_OFF:
inverted = false inverted = false
case ANSI_SGR_UNDERLINE_OFF: case ansiterm.ANSI_SGR_UNDERLINE_OFF:
windowsMode &^= COMMON_LVB_UNDERSCORE windowsMode &^= COMMON_LVB_UNDERSCORE
// Foreground colors // Foreground colors
case ANSI_SGR_FOREGROUND_DEFAULT: case ansiterm.ANSI_SGR_FOREGROUND_DEFAULT:
windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK) windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK)
case ANSI_SGR_FOREGROUND_BLACK: case ansiterm.ANSI_SGR_FOREGROUND_BLACK:
windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK)
case ANSI_SGR_FOREGROUND_RED: case ansiterm.ANSI_SGR_FOREGROUND_RED:
windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED
case ANSI_SGR_FOREGROUND_GREEN: case ansiterm.ANSI_SGR_FOREGROUND_GREEN:
windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN
case ANSI_SGR_FOREGROUND_YELLOW: case ansiterm.ANSI_SGR_FOREGROUND_YELLOW:
windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN
case ANSI_SGR_FOREGROUND_BLUE: case ansiterm.ANSI_SGR_FOREGROUND_BLUE:
windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE
case ANSI_SGR_FOREGROUND_MAGENTA: case ansiterm.ANSI_SGR_FOREGROUND_MAGENTA:
windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE
case ANSI_SGR_FOREGROUND_CYAN: case ansiterm.ANSI_SGR_FOREGROUND_CYAN:
windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE
case ANSI_SGR_FOREGROUND_WHITE: case ansiterm.ANSI_SGR_FOREGROUND_WHITE:
windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
// Background colors // Background colors
case ANSI_SGR_BACKGROUND_DEFAULT: case ansiterm.ANSI_SGR_BACKGROUND_DEFAULT:
// Black with no intensity // Black with no intensity
windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK) windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK)
case ANSI_SGR_BACKGROUND_BLACK: case ansiterm.ANSI_SGR_BACKGROUND_BLACK:
windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK)
case ANSI_SGR_BACKGROUND_RED: case ansiterm.ANSI_SGR_BACKGROUND_RED:
windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED
case ANSI_SGR_BACKGROUND_GREEN: case ansiterm.ANSI_SGR_BACKGROUND_GREEN:
windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN
case ANSI_SGR_BACKGROUND_YELLOW: case ansiterm.ANSI_SGR_BACKGROUND_YELLOW:
windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN
case ANSI_SGR_BACKGROUND_BLUE: case ansiterm.ANSI_SGR_BACKGROUND_BLUE:
windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE
case ANSI_SGR_BACKGROUND_MAGENTA: case ansiterm.ANSI_SGR_BACKGROUND_MAGENTA:
windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE
case ANSI_SGR_BACKGROUND_CYAN: case ansiterm.ANSI_SGR_BACKGROUND_CYAN:
windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE
case ANSI_SGR_BACKGROUND_WHITE: case ansiterm.ANSI_SGR_BACKGROUND_WHITE:
windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
} }
...@@ -97,6 +95,6 @@ func collectAnsiIntoWindowsAttributes(windowsMode WORD, inverted bool, baseMode ...@@ -97,6 +95,6 @@ func collectAnsiIntoWindowsAttributes(windowsMode WORD, inverted bool, baseMode
} }
// invertAttributes inverts the foreground and background colors of a Windows attributes value // invertAttributes inverts the foreground and background colors of a Windows attributes value
func invertAttributes(windowsMode WORD) WORD { func invertAttributes(windowsMode uint16) uint16 {
return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4) return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4)
} }
...@@ -3,11 +3,11 @@ ...@@ -3,11 +3,11 @@
package winterm package winterm
const ( const (
Horizontal = iota horizontal = iota
Vertical vertical
) )
func (h *WindowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT { func (h *windowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT {
if h.originMode { if h.originMode {
sr := h.effectiveSr(info.Window) sr := h.effectiveSr(info.Window)
return SMALL_RECT{ return SMALL_RECT{
...@@ -27,7 +27,7 @@ func (h *WindowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_IN ...@@ -27,7 +27,7 @@ func (h *WindowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_IN
} }
// setCursorPosition sets the cursor to the specified position, bounded to the screen size // setCursorPosition sets the cursor to the specified position, bounded to the screen size
func (h *WindowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error { func (h *windowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error {
position.X = ensureInRange(position.X, window.Left, window.Right) position.X = ensureInRange(position.X, window.Left, window.Right)
position.Y = ensureInRange(position.Y, window.Top, window.Bottom) position.Y = ensureInRange(position.Y, window.Top, window.Bottom)
err := SetConsoleCursorPosition(h.fd, position) err := SetConsoleCursorPosition(h.fd, position)
...@@ -38,15 +38,15 @@ func (h *WindowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL ...@@ -38,15 +38,15 @@ func (h *WindowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL
return err return err
} }
func (h *WindowsAnsiEventHandler) moveCursorVertical(param int) error { func (h *windowsAnsiEventHandler) moveCursorVertical(param int) error {
return h.moveCursor(Vertical, param) return h.moveCursor(vertical, param)
} }
func (h *WindowsAnsiEventHandler) moveCursorHorizontal(param int) error { func (h *windowsAnsiEventHandler) moveCursorHorizontal(param int) error {
return h.moveCursor(Horizontal, param) return h.moveCursor(horizontal, param)
} }
func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error { func (h *windowsAnsiEventHandler) moveCursor(moveMode int, param int) error {
info, err := GetConsoleScreenBufferInfo(h.fd) info, err := GetConsoleScreenBufferInfo(h.fd)
if err != nil { if err != nil {
return err return err
...@@ -54,10 +54,10 @@ func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error { ...@@ -54,10 +54,10 @@ func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error {
position := info.CursorPosition position := info.CursorPosition
switch moveMode { switch moveMode {
case Horizontal: case horizontal:
position.X += SHORT(param) position.X += int16(param)
case Vertical: case vertical:
position.Y += SHORT(param) position.Y += int16(param)
} }
if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil {
...@@ -67,7 +67,7 @@ func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error { ...@@ -67,7 +67,7 @@ func (h *WindowsAnsiEventHandler) moveCursor(moveMode int, param int) error {
return nil return nil
} }
func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error { func (h *windowsAnsiEventHandler) moveCursorLine(param int) error {
info, err := GetConsoleScreenBufferInfo(h.fd) info, err := GetConsoleScreenBufferInfo(h.fd)
if err != nil { if err != nil {
return err return err
...@@ -75,7 +75,7 @@ func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error { ...@@ -75,7 +75,7 @@ func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error {
position := info.CursorPosition position := info.CursorPosition
position.X = 0 position.X = 0
position.Y += SHORT(param) position.Y += int16(param)
if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil {
return err return err
...@@ -84,14 +84,14 @@ func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error { ...@@ -84,14 +84,14 @@ func (h *WindowsAnsiEventHandler) moveCursorLine(param int) error {
return nil return nil
} }
func (h *WindowsAnsiEventHandler) moveCursorColumn(param int) error { func (h *windowsAnsiEventHandler) moveCursorColumn(param int) error {
info, err := GetConsoleScreenBufferInfo(h.fd) info, err := GetConsoleScreenBufferInfo(h.fd)
if err != nil { if err != nil {
return err return err
} }
position := info.CursorPosition position := info.CursorPosition
position.X = SHORT(param) - 1 position.X = int16(param) - 1
if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil {
return err return err
......
...@@ -2,11 +2,9 @@ ...@@ -2,11 +2,9 @@
package winterm package winterm
import ( import "github.com/Azure/go-ansiterm"
. "github.com/Azure/go-ansiterm"
)
func (h *WindowsAnsiEventHandler) clearRange(attributes WORD, fromCoord COORD, toCoord COORD) error { func (h *windowsAnsiEventHandler) clearRange(attributes uint16, fromCoord COORD, toCoord COORD) error {
// Ignore an invalid (negative area) request // Ignore an invalid (negative area) request
if toCoord.Y < fromCoord.Y { if toCoord.Y < fromCoord.Y {
return nil return nil
...@@ -60,7 +58,7 @@ func (h *WindowsAnsiEventHandler) clearRange(attributes WORD, fromCoord COORD, t ...@@ -60,7 +58,7 @@ func (h *WindowsAnsiEventHandler) clearRange(attributes WORD, fromCoord COORD, t
return nil return nil
} }
func (h *WindowsAnsiEventHandler) clearRect(attributes WORD, fromCoord COORD, toCoord COORD) error { func (h *windowsAnsiEventHandler) clearRect(attributes uint16, fromCoord COORD, toCoord COORD) error {
region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X} region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X}
width := toCoord.X - fromCoord.X + 1 width := toCoord.X - fromCoord.X + 1
height := toCoord.Y - fromCoord.Y + 1 height := toCoord.Y - fromCoord.Y + 1
...@@ -72,7 +70,7 @@ func (h *WindowsAnsiEventHandler) clearRect(attributes WORD, fromCoord COORD, to ...@@ -72,7 +70,7 @@ func (h *WindowsAnsiEventHandler) clearRect(attributes WORD, fromCoord COORD, to
buffer := make([]CHAR_INFO, size) buffer := make([]CHAR_INFO, size)
char := CHAR_INFO{WCHAR(FILL_CHARACTER), attributes} char := CHAR_INFO{ansiterm.FILL_CHARACTER, attributes}
for i := 0; i < int(size); i++ { for i := 0; i < int(size); i++ {
buffer[i] = char buffer[i] = char
} }
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
package winterm package winterm
// effectiveSr gets the current effective scroll region in buffer coordinates // effectiveSr gets the current effective scroll region in buffer coordinates
func (h *WindowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { func (h *windowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion {
top := AddInRange(window.Top, h.sr.top, window.Top, window.Bottom) top := addInRange(window.Top, h.sr.top, window.Top, window.Bottom)
bottom := AddInRange(window.Top, h.sr.bottom, window.Top, window.Bottom) bottom := addInRange(window.Top, h.sr.bottom, window.Top, window.Bottom)
if top >= bottom { if top >= bottom {
top = window.Top top = window.Top
bottom = window.Bottom bottom = window.Bottom
...@@ -13,7 +13,7 @@ func (h *WindowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { ...@@ -13,7 +13,7 @@ func (h *WindowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion {
return scrollRegion{top: top, bottom: bottom} return scrollRegion{top: top, bottom: bottom}
} }
func (h *WindowsAnsiEventHandler) scrollUp(param int) error { func (h *windowsAnsiEventHandler) scrollUp(param int) error {
info, err := GetConsoleScreenBufferInfo(h.fd) info, err := GetConsoleScreenBufferInfo(h.fd)
if err != nil { if err != nil {
return err return err
...@@ -23,11 +23,11 @@ func (h *WindowsAnsiEventHandler) scrollUp(param int) error { ...@@ -23,11 +23,11 @@ func (h *WindowsAnsiEventHandler) scrollUp(param int) error {
return h.scroll(param, sr, info) return h.scroll(param, sr, info)
} }
func (h *WindowsAnsiEventHandler) scrollDown(param int) error { func (h *windowsAnsiEventHandler) scrollDown(param int) error {
return h.scrollUp(-param) return h.scrollUp(-param)
} }
func (h *WindowsAnsiEventHandler) deleteLines(param int) error { func (h *windowsAnsiEventHandler) deleteLines(param int) error {
info, err := GetConsoleScreenBufferInfo(h.fd) info, err := GetConsoleScreenBufferInfo(h.fd)
if err != nil { if err != nil {
return err return err
...@@ -44,12 +44,12 @@ func (h *WindowsAnsiEventHandler) deleteLines(param int) error { ...@@ -44,12 +44,12 @@ func (h *WindowsAnsiEventHandler) deleteLines(param int) error {
} }
} }
func (h *WindowsAnsiEventHandler) insertLines(param int) error { func (h *windowsAnsiEventHandler) insertLines(param int) error {
return h.deleteLines(-param) return h.deleteLines(-param)
} }
// scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates. // scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates.
func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error { func (h *windowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error {
logger.Infof("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom) logger.Infof("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom)
logger.Infof("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom) logger.Infof("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom)
...@@ -64,7 +64,7 @@ func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSO ...@@ -64,7 +64,7 @@ func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSO
// Origin to which area should be copied // Origin to which area should be copied
destOrigin := COORD{ destOrigin := COORD{
X: 0, X: 0,
Y: sr.top - SHORT(param), Y: sr.top - int16(param),
} }
char := CHAR_INFO{ char := CHAR_INFO{
...@@ -78,7 +78,7 @@ func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSO ...@@ -78,7 +78,7 @@ func (h *WindowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSO
return nil return nil
} }
func (h *WindowsAnsiEventHandler) deleteCharacters(param int) error { func (h *windowsAnsiEventHandler) deleteCharacters(param int) error {
info, err := GetConsoleScreenBufferInfo(h.fd) info, err := GetConsoleScreenBufferInfo(h.fd)
if err != nil { if err != nil {
return err return err
...@@ -86,12 +86,12 @@ func (h *WindowsAnsiEventHandler) deleteCharacters(param int) error { ...@@ -86,12 +86,12 @@ func (h *WindowsAnsiEventHandler) deleteCharacters(param int) error {
return h.scrollLine(param, info.CursorPosition, info) return h.scrollLine(param, info.CursorPosition, info)
} }
func (h *WindowsAnsiEventHandler) insertCharacters(param int) error { func (h *windowsAnsiEventHandler) insertCharacters(param int) error {
return h.deleteCharacters(-param) return h.deleteCharacters(-param)
} }
// scrollLine scrolls a line horizontally starting at the provided position by a number of columns. // scrollLine scrolls a line horizontally starting at the provided position by a number of columns.
func (h *WindowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error { func (h *windowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error {
// Copy from and clip to the scroll region (full buffer width) // Copy from and clip to the scroll region (full buffer width)
scrollRect := SMALL_RECT{ scrollRect := SMALL_RECT{
Top: position.Y, Top: position.Y,
...@@ -102,7 +102,7 @@ func (h *WindowsAnsiEventHandler) scrollLine(columns int, position COORD, info * ...@@ -102,7 +102,7 @@ func (h *WindowsAnsiEventHandler) scrollLine(columns int, position COORD, info *
// Origin to which area should be copied // Origin to which area should be copied
destOrigin := COORD{ destOrigin := COORD{
X: position.X - SHORT(columns), X: position.X - int16(columns),
Y: position.Y, Y: position.Y,
} }
......
...@@ -4,6 +4,6 @@ package winterm ...@@ -4,6 +4,6 @@ package winterm
// AddInRange increments a value by the passed quantity while ensuring the values // AddInRange increments a value by the passed quantity while ensuring the values
// always remain within the supplied min / max range. // always remain within the supplied min / max range.
func AddInRange(n SHORT, increment SHORT, min SHORT, max SHORT) SHORT { func addInRange(n int16, increment int16, min int16, max int16) int16 {
return ensureInRange(n+increment, min, max) return ensureInRange(n+increment, min, max)
} }
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"autorest.go",
"client.go",
"error.go",
"preparer.go",
"responder.go",
"sender.go",
"utility.go",
"version.go",
],
tags = ["automanaged"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//vendor/github.com/Azure/go-autorest/autorest/azure:all-srcs",
"//vendor/github.com/Azure/go-autorest/autorest/date:all-srcs",
"//vendor/github.com/Azure/go-autorest/autorest/to:all-srcs",
"//vendor/github.com/Azure/go-autorest/autorest/validation:all-srcs",
],
tags = ["automanaged"],
)
...@@ -16,6 +16,7 @@ and Responding. A typical pattern is: ...@@ -16,6 +16,7 @@ and Responding. A typical pattern is:
DoRetryForAttempts(5, time.Second)) DoRetryForAttempts(5, time.Second))
err = Respond(resp, err = Respond(resp,
ByDiscardingBody(),
ByClosing()) ByClosing())
Each phase relies on decorators to modify and / or manage processing. Decorators may first modify Each phase relies on decorators to modify and / or manage processing. Decorators may first modify
......
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"async.go",
"azure.go",
"config.go",
"devicetoken.go",
"environments.go",
"persist.go",
"token.go",
],
tags = ["automanaged"],
deps = [
"//vendor/github.com/Azure/go-autorest/autorest:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/date:go_default_library",
"//vendor/github.com/dgrijalva/jwt-go:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
...@@ -3,12 +3,13 @@ package azure ...@@ -3,12 +3,13 @@ package azure
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/date"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings" "strings"
"time" "time"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/date"
) )
const ( const (
...@@ -16,12 +17,6 @@ const ( ...@@ -16,12 +17,6 @@ const (
) )
const ( const (
methodDelete = "DELETE"
methodPatch = "PATCH"
methodPost = "POST"
methodPut = "PUT"
methodGet = "GET"
operationInProgress string = "InProgress" operationInProgress string = "InProgress"
operationCanceled string = "Canceled" operationCanceled string = "Canceled"
operationFailed string = "Failed" operationFailed string = "Failed"
...@@ -225,7 +220,7 @@ func updatePollingState(resp *http.Response, ps *pollingState) error { ...@@ -225,7 +220,7 @@ func updatePollingState(resp *http.Response, ps *pollingState) error {
// Lastly, requests against an existing resource, use the last request URI // Lastly, requests against an existing resource, use the last request URI
if ps.uri == "" { if ps.uri == "" {
m := strings.ToUpper(req.Method) m := strings.ToUpper(req.Method)
if m == methodPatch || m == methodPut || m == methodGet { if m == http.MethodPatch || m == http.MethodPut || m == http.MethodGet {
ps.uri = req.URL.String() ps.uri = req.URL.String()
} }
} }
......
package azure
import (
"net/url"
)
// OAuthConfig represents the endpoints needed
// in OAuth operations
type OAuthConfig struct {
AuthorizeEndpoint url.URL
TokenEndpoint url.URL
DeviceCodeEndpoint url.URL
}
package azure
/*
This file is largely based on rjw57/oauth2device's code, with the follow differences:
* scope -> resource, and only allow a single one
* receive "Message" in the DeviceCode struct and show it to users as the prompt
* azure-xplat-cli has the following behavior that this emulates:
- does not send client_secret during the token exchange
- sends resource again in the token exchange request
*/
import (
"fmt"
"net/http"
"net/url"
"time"
"github.com/Azure/go-autorest/autorest"
)
const (
logPrefix = "autorest/azure/devicetoken:"
)
var (
// ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow
ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix)
// ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow
ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix)
// ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow
ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix)
// ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow
ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix)
// ErrDeviceSlowDown represents the service telling us we're polling too often during device flow
ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix)
errCodeSendingFails = "Error occurred while sending request for Device Authorization Code"
errCodeHandlingFails = "Error occurred while handling response from the Device Endpoint"
errTokenSendingFails = "Error occurred while sending request with device code for a token"
errTokenHandlingFails = "Error occurred while handling response from the Token Endpoint (during device flow)"
)
// DeviceCode is the object returned by the device auth endpoint
// It contains information to instruct the user to complete the auth flow
type DeviceCode struct {
DeviceCode *string `json:"device_code,omitempty"`
UserCode *string `json:"user_code,omitempty"`
VerificationURL *string `json:"verification_url,omitempty"`
ExpiresIn *int64 `json:"expires_in,string,omitempty"`
Interval *int64 `json:"interval,string,omitempty"`
Message *string `json:"message"` // Azure specific
Resource string // store the following, stored when initiating, used when exchanging
OAuthConfig OAuthConfig
ClientID string
}
// TokenError is the object returned by the token exchange endpoint
// when something is amiss
type TokenError struct {
Error *string `json:"error,omitempty"`
ErrorCodes []int `json:"error_codes,omitempty"`
ErrorDescription *string `json:"error_description,omitempty"`
Timestamp *string `json:"timestamp,omitempty"`
TraceID *string `json:"trace_id,omitempty"`
}
// DeviceToken is the object return by the token exchange endpoint
// It can either look like a Token or an ErrorToken, so put both here
// and check for presence of "Error" to know if we are in error state
type deviceToken struct {
Token
TokenError
}
// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode
// that can be used with CheckForUserCompletion or WaitForUserCompletion.
func InitiateDeviceAuth(client *autorest.Client, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) {
req, _ := autorest.Prepare(
&http.Request{},
autorest.AsPost(),
autorest.AsFormURLEncoded(),
autorest.WithBaseURL(oauthConfig.DeviceCodeEndpoint.String()),
autorest.WithFormData(url.Values{
"client_id": []string{clientID},
"resource": []string{resource},
}),
)
resp, err := autorest.SendWithSender(client, req)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err)
}
var code DeviceCode
err = autorest.Respond(
resp,
autorest.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&code),
autorest.ByClosing())
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err)
}
code.ClientID = clientID
code.Resource = resource
code.OAuthConfig = oauthConfig
return &code, nil
}
// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint
// to see if the device flow has: been completed, timed out, or otherwise failed
func CheckForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error) {
req, _ := autorest.Prepare(
&http.Request{},
autorest.AsPost(),
autorest.AsFormURLEncoded(),
autorest.WithBaseURL(code.OAuthConfig.TokenEndpoint.String()),
autorest.WithFormData(url.Values{
"client_id": []string{code.ClientID},
"code": []string{*code.DeviceCode},
"grant_type": []string{OAuthGrantTypeDeviceCode},
"resource": []string{code.Resource},
}),
)
resp, err := autorest.SendWithSender(client, req)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err)
}
var token deviceToken
err = autorest.Respond(
resp,
autorest.WithErrorUnlessStatusCode(http.StatusOK, http.StatusBadRequest),
autorest.ByUnmarshallingJSON(&token),
autorest.ByClosing())
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err)
}
if token.Error == nil {
return &token.Token, nil
}
switch *token.Error {
case "authorization_pending":
return nil, ErrDeviceAuthorizationPending
case "slow_down":
return nil, ErrDeviceSlowDown
case "access_denied":
return nil, ErrDeviceAccessDenied
case "code_expired":
return nil, ErrDeviceCodeExpired
default:
return nil, ErrDeviceGeneric
}
}
// WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs.
// This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'.
func WaitForUserCompletion(client *autorest.Client, code *DeviceCode) (*Token, error) {
intervalDuration := time.Duration(*code.Interval) * time.Second
waitDuration := intervalDuration
for {
token, err := CheckForUserCompletion(client, code)
if err == nil {
return token, nil
}
switch err {
case ErrDeviceSlowDown:
waitDuration += waitDuration
case ErrDeviceAuthorizationPending:
// noop
default: // everything else is "fatal" to us
return nil, err
}
if waitDuration > (intervalDuration * 3) {
return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix)
}
time.Sleep(waitDuration)
}
}
...@@ -2,14 +2,9 @@ package azure ...@@ -2,14 +2,9 @@ package azure
import ( import (
"fmt" "fmt"
"net/url"
"strings" "strings"
) )
const (
activeDirectoryAPIVersion = "1.0"
)
var environments = map[string]Environment{ var environments = map[string]Environment{
"AZURECHINACLOUD": ChinaCloud, "AZURECHINACLOUD": ChinaCloud,
"AZUREGERMANCLOUD": GermanCloud, "AZUREGERMANCLOUD": GermanCloud,
...@@ -35,6 +30,7 @@ type Environment struct { ...@@ -35,6 +30,7 @@ type Environment struct {
ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"`
ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"`
ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"`
ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"`
} }
var ( var (
...@@ -56,6 +52,7 @@ var ( ...@@ -56,6 +52,7 @@ var (
ServiceBusEndpointSuffix: "servicebus.azure.com", ServiceBusEndpointSuffix: "servicebus.azure.com",
ServiceManagementVMDNSSuffix: "cloudapp.net", ServiceManagementVMDNSSuffix: "cloudapp.net",
ResourceManagerVMDNSSuffix: "cloudapp.azure.com", ResourceManagerVMDNSSuffix: "cloudapp.azure.com",
ContainerRegistryDNSSuffix: "azurecr.io",
} }
// USGovernmentCloud is the cloud environment for the US Government // USGovernmentCloud is the cloud environment for the US Government
...@@ -76,6 +73,7 @@ var ( ...@@ -76,6 +73,7 @@ var (
ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net",
ServiceManagementVMDNSSuffix: "usgovcloudapp.net", ServiceManagementVMDNSSuffix: "usgovcloudapp.net",
ResourceManagerVMDNSSuffix: "cloudapp.windowsazure.us", ResourceManagerVMDNSSuffix: "cloudapp.windowsazure.us",
ContainerRegistryDNSSuffix: "azurecr.io",
} }
// ChinaCloud is the cloud environment operated in China // ChinaCloud is the cloud environment operated in China
...@@ -85,7 +83,7 @@ var ( ...@@ -85,7 +83,7 @@ var (
PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index",
ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/",
ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", ResourceManagerEndpoint: "https://management.chinacloudapi.cn/",
ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/?api-version=1.0", ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/",
GalleryEndpoint: "https://gallery.chinacloudapi.cn/", GalleryEndpoint: "https://gallery.chinacloudapi.cn/",
KeyVaultEndpoint: "https://vault.azure.cn/", KeyVaultEndpoint: "https://vault.azure.cn/",
GraphEndpoint: "https://graph.chinacloudapi.cn/", GraphEndpoint: "https://graph.chinacloudapi.cn/",
...@@ -96,6 +94,7 @@ var ( ...@@ -96,6 +94,7 @@ var (
ServiceBusEndpointSuffix: "servicebus.chinacloudapi.net", ServiceBusEndpointSuffix: "servicebus.chinacloudapi.net",
ServiceManagementVMDNSSuffix: "chinacloudapp.cn", ServiceManagementVMDNSSuffix: "chinacloudapp.cn",
ResourceManagerVMDNSSuffix: "cloudapp.azure.cn", ResourceManagerVMDNSSuffix: "cloudapp.azure.cn",
ContainerRegistryDNSSuffix: "azurecr.io",
} }
// GermanCloud is the cloud environment operated in Germany // GermanCloud is the cloud environment operated in Germany
...@@ -116,6 +115,7 @@ var ( ...@@ -116,6 +115,7 @@ var (
ServiceBusEndpointSuffix: "servicebus.cloudapi.de", ServiceBusEndpointSuffix: "servicebus.cloudapi.de",
ServiceManagementVMDNSSuffix: "azurecloudapp.de", ServiceManagementVMDNSSuffix: "azurecloudapp.de",
ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de", ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de",
ContainerRegistryDNSSuffix: "azurecr.io",
} }
) )
...@@ -128,35 +128,3 @@ func EnvironmentFromName(name string) (Environment, error) { ...@@ -128,35 +128,3 @@ func EnvironmentFromName(name string) (Environment, error) {
} }
return env, nil return env, nil
} }
// OAuthConfigForTenant returns an OAuthConfig with tenant specific urls
func (env Environment) OAuthConfigForTenant(tenantID string) (*OAuthConfig, error) {
return OAuthConfigForTenant(env.ActiveDirectoryEndpoint, tenantID)
}
// OAuthConfigForTenant returns an OAuthConfig with tenant specific urls for target cloud auth endpoint
func OAuthConfigForTenant(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) {
template := "%s/oauth2/%s?api-version=%s"
u, err := url.Parse(activeDirectoryEndpoint)
if err != nil {
return nil, err
}
authorizeURL, err := u.Parse(fmt.Sprintf(template, tenantID, "authorize", activeDirectoryAPIVersion))
if err != nil {
return nil, err
}
tokenURL, err := u.Parse(fmt.Sprintf(template, tenantID, "token", activeDirectoryAPIVersion))
if err != nil {
return nil, err
}
deviceCodeURL, err := u.Parse(fmt.Sprintf(template, tenantID, "devicecode", activeDirectoryAPIVersion))
if err != nil {
return nil, err
}
return &OAuthConfig{
AuthorizeEndpoint: *authorizeURL,
TokenEndpoint: *tokenURL,
DeviceCodeEndpoint: *deviceCodeURL,
}, nil
}
package azure
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
// LoadToken restores a Token object from a file located at 'path'.
func LoadToken(path string) (*Token, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
}
defer file.Close()
var token Token
dec := json.NewDecoder(file)
if err = dec.Decode(&token); err != nil {
return nil, fmt.Errorf("failed to decode contents of file (%s) into Token representation: %v", path, err)
}
return &token, nil
}
// SaveToken persists an oauth token at the given location on disk.
// It moves the new file into place so it can safely be used to replace an existing file
// that maybe accessed by multiple processes.
func SaveToken(path string, mode os.FileMode, token Token) error {
dir := filepath.Dir(path)
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to create directory (%s) to store token in: %v", dir, err)
}
newFile, err := ioutil.TempFile(dir, "token")
if err != nil {
return fmt.Errorf("failed to create the temp file to write the token: %v", err)
}
tempPath := newFile.Name()
if err := json.NewEncoder(newFile).Encode(token); err != nil {
return fmt.Errorf("failed to encode token to file (%s) while saving token: %v", tempPath, err)
}
if err := newFile.Close(); err != nil {
return fmt.Errorf("failed to close temp file %s: %v", tempPath, err)
}
// Atomic replace to avoid multi-writer file corruptions
if err := os.Rename(tempPath, path); err != nil {
return fmt.Errorf("failed to move temporary token to desired output location. src=%s dst=%s: %v", tempPath, path, err)
}
if err := os.Chmod(path, mode); err != nil {
return fmt.Errorf("failed to chmod the token file %s: %v", path, err)
}
return nil
}
...@@ -8,6 +8,7 @@ import ( ...@@ -8,6 +8,7 @@ import (
"log" "log"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
"runtime"
"time" "time"
) )
...@@ -22,13 +23,24 @@ const ( ...@@ -22,13 +23,24 @@ const (
DefaultRetryAttempts = 3 DefaultRetryAttempts = 3
) )
var statusCodesForRetry = []int{ var (
http.StatusRequestTimeout, // 408 // defaultUserAgent builds a string containing the Go version, system archityecture and OS,
http.StatusInternalServerError, // 500 // and the go-autorest version.
http.StatusBadGateway, // 502 defaultUserAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s",
http.StatusServiceUnavailable, // 503 runtime.Version(),
http.StatusGatewayTimeout, // 504 runtime.GOARCH,
} runtime.GOOS,
Version(),
)
statusCodesForRetry = []int{
http.StatusRequestTimeout, // 408
http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout, // 504
}
)
const ( const (
requestFormat = `HTTP Request Begin =================================================== requestFormat = `HTTP Request Begin ===================================================
...@@ -140,13 +152,24 @@ type Client struct { ...@@ -140,13 +152,24 @@ type Client struct {
// NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed // NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed
// string. // string.
func NewClientWithUserAgent(ua string) Client { func NewClientWithUserAgent(ua string) Client {
return Client{ c := Client{
PollingDelay: DefaultPollingDelay, PollingDelay: DefaultPollingDelay,
PollingDuration: DefaultPollingDuration, PollingDuration: DefaultPollingDuration,
RetryAttempts: DefaultRetryAttempts, RetryAttempts: DefaultRetryAttempts,
RetryDuration: 30 * time.Second, RetryDuration: 30 * time.Second,
UserAgent: ua, UserAgent: defaultUserAgent,
}
c.AddToUserAgent(ua)
return c
}
// AddToUserAgent adds an extension to the current user agent
func (c *Client) AddToUserAgent(extension string) error {
if extension != "" {
c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension)
return nil
} }
return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent)
} }
// Do implements the Sender interface by invoking the active Sender after applying authorization. // Do implements the Sender interface by invoking the active Sender after applying authorization.
......
package(default_visibility = ["//visibility:public"])
licenses(["notice"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"date.go",
"time.go",
"timerfc1123.go",
"utility.go",
],
tags = ["automanaged"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
)
...@@ -183,6 +183,16 @@ func WithBaseURL(baseURL string) PrepareDecorator { ...@@ -183,6 +183,16 @@ func WithBaseURL(baseURL string) PrepareDecorator {
} }
} }
// WithCustomBaseURL returns a PrepareDecorator that replaces brace-enclosed keys within the
// request base URL (i.e., http.Request.URL) with the corresponding values from the passed map.
func WithCustomBaseURL(baseURL string, urlParameters map[string]interface{}) PrepareDecorator {
parameters := ensureValueStrings(urlParameters)
for key, value := range parameters {
baseURL = strings.Replace(baseURL, "{"+key+"}", value, -1)
}
return WithBaseURL(baseURL)
}
// WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the // WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the
// http.Request body. // http.Request body.
func WithFormData(v url.Values) PrepareDecorator { func WithFormData(v url.Values) PrepareDecorator {
...@@ -416,18 +426,3 @@ func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorato ...@@ -416,18 +426,3 @@ func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorato
}) })
} }
} }
// Authorizer is the interface that provides a PrepareDecorator used to supply request
// authorization. Most often, the Authorizer decorator runs last so it has access to the full
// state of the formed HTTP request.
type Authorizer interface {
WithAuthorization() PrepareDecorator
}
// NullAuthorizer implements a default, "do nothing" Authorizer.
type NullAuthorizer struct{}
// WithAuthorization returns a PrepareDecorator that does nothing.
func (na NullAuthorizer) WithAuthorization() PrepareDecorator {
return WithNothing()
}
...@@ -5,6 +5,7 @@ import ( ...@@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"io"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings" "strings"
...@@ -87,6 +88,24 @@ func ByCopying(b *bytes.Buffer) RespondDecorator { ...@@ -87,6 +88,24 @@ func ByCopying(b *bytes.Buffer) RespondDecorator {
} }
} }
// ByDiscardingBody returns a RespondDecorator that first invokes the passed Responder after which
// it copies the remaining bytes (if any) in the response body to ioutil.Discard. Since the passed
// Responder is invoked prior to discarding the response body, the decorator may occur anywhere
// within the set.
func ByDiscardingBody() RespondDecorator {
return func(r Responder) Responder {
return ResponderFunc(func(resp *http.Response) error {
err := r.Respond(resp)
if err == nil && resp != nil && resp.Body != nil {
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
return fmt.Errorf("Error discarding the response body: %v", err)
}
}
return err
})
}
}
// ByClosing returns a RespondDecorator that first invokes the passed Responder after which it // ByClosing returns a RespondDecorator that first invokes the passed Responder after which it
// closes the response body. Since the passed Responder is invoked prior to closing the response // closes the response body. Since the passed Responder is invoked prior to closing the response
// body, the decorator may occur anywhere within the set. // body, the decorator may occur anywhere within the set.
...@@ -128,6 +147,8 @@ func ByUnmarshallingJSON(v interface{}) RespondDecorator { ...@@ -128,6 +147,8 @@ func ByUnmarshallingJSON(v interface{}) RespondDecorator {
err := r.Respond(resp) err := r.Respond(resp)
if err == nil { if err == nil {
b, errInner := ioutil.ReadAll(resp.Body) b, errInner := ioutil.ReadAll(resp.Body)
// Some responses might include a BOM, remove for successful unmarshalling
b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf"))
if errInner != nil { if errInner != nil {
err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner)
} else if len(strings.Trim(string(b), " ")) > 0 { } else if len(strings.Trim(string(b), " ")) > 0 {
......
...@@ -97,7 +97,7 @@ func DoCloseIfError() SendDecorator { ...@@ -97,7 +97,7 @@ func DoCloseIfError() SendDecorator {
return SenderFunc(func(r *http.Request) (*http.Response, error) { return SenderFunc(func(r *http.Request) (*http.Response, error) {
resp, err := s.Do(r) resp, err := s.Do(r)
if err != nil { if err != nil {
Respond(resp, ByClosing()) Respond(resp, ByDiscardingBody(), ByClosing())
} }
return resp, err return resp, err
}) })
...@@ -156,6 +156,7 @@ func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ... ...@@ -156,6 +156,7 @@ func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ...
for err == nil && ResponseHasStatusCode(resp, codes...) { for err == nil && ResponseHasStatusCode(resp, codes...) {
Respond(resp, Respond(resp,
ByDiscardingBody(),
ByClosing()) ByClosing())
resp, err = SendWithSender(s, r, resp, err = SendWithSender(s, r,
AfterDelay(GetRetryAfter(resp, delay))) AfterDelay(GetRetryAfter(resp, delay)))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment