<commit_before>package gform

import (
    "github.com/AllenDang/w32"
    "github.com/AllenDang/w32/shell32"
    "github.com/AllenDang/w32/user32"
)

func genMouseEventArg(wparam, lparam uintptr) *MouseEventData {
    var data MouseEventData
    data.Button = int(wparam)
    data.X = int(w32.LOWORD(uint(lparam)))
    data.Y = int(w32.HIWORD(uint(lparam)))

    return &data
}

func genDropFilesEventArg(wparam uintptr) *DropFilesEventData {
    hDrop := w32.HDROP(wparam)

    var data DropFilesEventData
    _, fileCount := shell32.DragQueryFile(hDrop, 0xFFFFFFFF)
    data.Files = make([]string, fileCount)

    var i uint
    for i = 0; i < fileCount; i++ {
        data.Files[i], _ = shell32.DragQueryFile(hDrop, i)
    }

    data.X, data.Y, _ = shell32.DragQueryPoint(hDrop)

    shell32.DragFinish(hDrop)

    return &data
}

func generalWndProc(hwnd w32.HWND, msg uint, wparam, lparam uintptr) uintptr {
    if msg == w32.WM_INITDIALOG && gDialogWaiting != nil {
        gDialogWaiting.hwnd = hwnd
        RegMsgHandler(gDialogWaiting)
    }

    if msgHandler := GetMsgHandler(hwnd); msgHandler != nil {
        ret := msgHandler.WndProc(msg, wparam, lparam)
        if controller, ok := msgHandler.(Controller); ok {
            switch msg {
            case w32.WM_CLOSE:
                controller.OnClose().Fire(NewEventArg(controller, nil))
            case w32.WM_KILLFOCUS:
                controller.OnKillFocus().Fire(NewEventArg(controller, nil))
            case w32.WM_SETFOCUS:
                controller.OnSetFocus().Fire(NewEventArg(controller, nil))
            case w32.WM_DROPFILES:
                controller.OnDropFiles().Fire(NewEventArg(controller, genDropFilesEventArg(wparam)))
            case w32.WM_LBUTTONDOWN:
                controller.OnLBDown().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_LBUTTONUP:
                controller.OnLBUp().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_MBUTTONDOWN:
                controller.OnMBDown().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_MBUTTONUP:
                controller.OnMBUp().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_RBUTTONDOWN:
                controller.OnRBDown().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_RBUTTONUP:
                controller.OnRBUp().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_PAINT:
                canvas := NewCanvasFromHwnd(hwnd)
                controller.OnPaint().Fire(NewEventArg(controller, &PaintEventData{Canvas: canvas}))
                canvas.Dispose()
            case w32.WM_KEYUP:
                controller.OnKeyUp().Fire(NewEventArg(controller, &KeyUpEventData{int(wparam), int(lparam)}))
            }
        }
        return ret
    }

    return user32.DefWindowProc(hwnd, msg, wparam, lparam)
}
<commit_msg>Reflect WM_NOTIFY and WM_COMMAND to child control.<commit_after>package gform

import (
    "github.com/AllenDang/w32"
    "github.com/AllenDang/w32/shell32"
    "github.com/AllenDang/w32/user32"
    "unsafe"
)

func genMouseEventArg(wparam, lparam uintptr) *MouseEventData {
    var data MouseEventData
    data.Button = int(wparam)
    data.X = int(w32.LOWORD(uint(lparam)))
    data.Y = int(w32.HIWORD(uint(lparam)))

    return &data
}

func genDropFilesEventArg(wparam uintptr) *DropFilesEventData {
    hDrop := w32.HDROP(wparam)

    var data DropFilesEventData
    _, fileCount := shell32.DragQueryFile(hDrop, 0xFFFFFFFF)
    data.Files = make([]string, fileCount)

    var i uint
    for i = 0; i < fileCount; i++ {
        data.Files[i], _ = shell32.DragQueryFile(hDrop, i)
    }

    data.X, data.Y, _ = shell32.DragQueryPoint(hDrop)

    shell32.DragFinish(hDrop)

    return &data
}

func generalWndProc(hwnd w32.HWND, msg uint, wparam, lparam uintptr) uintptr {
    if msg == w32.WM_INITDIALOG && gDialogWaiting != nil {
        gDialogWaiting.hwnd = hwnd
        RegMsgHandler(gDialogWaiting)
    }

    if msgHandler := GetMsgHandler(hwnd); msgHandler != nil {
        ret := msgHandler.WndProc(msg, wparam, lparam)
        if controller, ok := msgHandler.(Controller); ok {
            switch msg {
            case w32.WM_NOTIFY: //Reflect notification to control
                nm := (*w32.NMHDR)(unsafe.Pointer(lparam))
                if msgHandler := GetMsgHandler(nm.HwndFrom); msgHandler != nil {
                    ret := msgHandler.WndProc(msg, wparam, lparam)
                    if ret != 0 {
                        user32.SetWindowLong(hwnd, w32.DWL_MSGRESULT, uint32(ret))
                        return w32.TRUE
                    }
                }
            case w32.WM_COMMAND:
                if lparam != 0 { //Reflect message to control
                    h := w32.HWND(lparam)
                    if msgHandler := GetMsgHandler(h); msgHandler != nil {
                        ret := msgHandler.WndProc(msg, wparam, lparam)
                        if ret != 0 {
                            user32.SetWindowLong(hwnd, w32.DWL_MSGRESULT, uint32(ret))
                            return w32.TRUE
                        }
                    }
                }
            case w32.WM_CLOSE:
                controller.OnClose().Fire(NewEventArg(controller, nil))
            case w32.WM_KILLFOCUS:
                controller.OnKillFocus().Fire(NewEventArg(controller, nil))
            case w32.WM_SETFOCUS:
                controller.OnSetFocus().Fire(NewEventArg(controller, nil))
            case w32.WM_DROPFILES:
                controller.OnDropFiles().Fire(NewEventArg(controller, genDropFilesEventArg(wparam)))
            case w32.WM_LBUTTONDOWN:
                controller.OnLBDown().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_LBUTTONUP:
                controller.OnLBUp().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_MBUTTONDOWN:
                controller.OnMBDown().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_MBUTTONUP:
                controller.OnMBUp().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_RBUTTONDOWN:
                controller.OnRBDown().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_RBUTTONUP:
                controller.OnRBUp().Fire(NewEventArg(controller, genMouseEventArg(wparam, lparam)))
            case w32.WM_PAINT:
                canvas := NewCanvasFromHwnd(hwnd)
                controller.OnPaint().Fire(NewEventArg(controller, &PaintEventData{Canvas: canvas}))
                canvas.Dispose()
            case w32.WM_KEYUP:
                controller.OnKeyUp().Fire(NewEventArg(controller, &KeyUpEventData{int(wparam), int(lparam)}))
            }
        }
        return ret
    }

    return user32.DefWindowProc(hwnd, msg, wparam, lparam)
}
<|endoftext|>


<commit_before>/*
   Nging is a toolbox for webmasters
   Copyright (C) 2018-present  Wenhui Shen <swh@admpub.com>

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published
   by the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

package navigate

//Item 操作
type Item struct {
	DisplayOnMenu bool
	Name          string
	Action        string
	Icon          string
	Target        string
	Children      List
}

//List 操作列表
type List []*Item

func (a *List) Remove(index int) List {
	if index < 0 {
		*a = (*a)[0:0]
		return *a
	}
	size := len(*a)
	if size > index {
		if size > index+1 {
			*a = append((*a)[0:index], (*a)[index+1:]...)
		} else {
			*a = (*a)[0:index]
		}
	}
	return *a
}

func (a *List) Set(index int, list ...*Item) List {
	if len(list) == 0 {
		return *a
	}
	if index < 0 {
		*a = append(*a, list...)
		return *a
	}
	size := len(*a)
	if size > index {
		(*a)[index] = list[0]
		if len(list) > 1 {
			a.Set(index+1, list[1:]...)
		}
		return *a
	}
	for start := size; start < index; start++ {
		*a = append(*a, nil)
	}
	*a = append(*a, list...)
	return *a
}

//Add 添加列表项
func (a *List) Add(index int, list ...*Item) List {
	if len(list) == 0 {
		return *a
	}
	if index < 0 {
		*a = append(*a, list...)
		return *a
	}
	size := len(*a)
	if size > index {
		list = append(list, (*a)[index])
		(*a)[index] = list[0]
		if len(list) > 1 {
			a.Add(index+1, list[1:]...)
		}
		return *a
	}
	for start := size; start < index; start++ {
		*a = append(*a, nil)
	}
	*a = append(*a, list...)
	return *a
}
<commit_msg>update<commit_after>/*
   Nging is a toolbox for webmasters
   Copyright (C) 2018-present  Wenhui Shen <swh@admpub.com>

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU Affero General Public License as published
   by the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

package navigate

//Item 操作
type Item struct {
	DisplayOnMenu bool   //是否在菜单三显示
	Name          string //名称
	Action        string //操作(一般为网址)
	Icon          string //图标
	Target        string //打开方式
	Unlimited     bool   //是否不限制权限
	Children      List
}

//List 操作列表
type List []*Item

//Remove 删除元素
func (a *List) Remove(index int) List {
	if index < 0 {
		*a = (*a)[0:0]
		return *a
	}
	size := len(*a)
	if size > index {
		if size > index+1 {
			*a = append((*a)[0:index], (*a)[index+1:]...)
		} else {
			*a = (*a)[0:index]
		}
	}
	return *a
}

//Set 设置元素
func (a *List) Set(index int, list ...*Item) List {
	if len(list) == 0 {
		return *a
	}
	if index < 0 {
		*a = append(*a, list...)
		return *a
	}
	size := len(*a)
	if size > index {
		(*a)[index] = list[0]
		if len(list) > 1 {
			a.Set(index+1, list[1:]...)
		}
		return *a
	}
	for start := size; start < index; start++ {
		*a = append(*a, nil)
	}
	*a = append(*a, list...)
	return *a
}

//Add 添加列表项
func (a *List) Add(index int, list ...*Item) List {
	if len(list) == 0 {
		return *a
	}
	if index < 0 {
		*a = append(*a, list...)
		return *a
	}
	size := len(*a)
	if size > index {
		list = append(list, (*a)[index])
		(*a)[index] = list[0]
		if len(list) > 1 {
			a.Add(index+1, list[1:]...)
		}
		return *a
	}
	for start := size; start < index; start++ {
		*a = append(*a, nil)
	}
	*a = append(*a, list...)
	return *a
}
<|endoftext|>


<commit_before>// Package endpointcreds provides support for retrieving credentials from an
// arbitrary HTTP endpoint.
//
// The credentials endpoint Provider can receive both static and refreshable
// credentials that will expire. Credentials are static when an "Expiration"
// value is not provided in the endpoint's response.
//
// Static credentials will never expire once they have been retrieved. The format
// of the static credentials response:
//    {
//        "AccessKeyId" : "MUA...",
//        "SecretAccessKey" : "/7PC5om....",
//    }
//
// Refreshable credentials will expire within the "ExpiryWindow" of the Expiration
// value in the response. The format of the refreshable credentials response:
//    {
//        "AccessKeyId" : "MUA...",
//        "SecretAccessKey" : "/7PC5om....",
//        "Token" : "AQoDY....=",
//        "Expiration" : "2016-02-25T06:03:31Z"
//    }
//
// Errors should be returned in the following format and only returned with 400
// or 500 HTTP status codes.
//    {
//        "code": "ErrorCode",
//        "message": "Helpful error message."
//    }
package endpointcreds

import (
	"encoding/json"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/client"
	"github.com/aws/aws-sdk-go/aws/client/metadata"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
)

// ProviderName is the name of the credentials provider.
const ProviderName = `CredentialsEndpointProvider`

// Provider satisfies the credentials.Provider interface, and is a client to
// retrieve credentials from an arbitrary endpoint.
type Provider struct {
	staticCreds bool
	credentials.Expiry

	// Requires a AWS Client to make HTTP requests to the endpoint with.
	// the Endpoint the request will be made to is provided by the aws.Config's
	// Endpoint value.
	Client *client.Client

	// ExpiryWindow will allow the credentials to trigger refreshing prior to
	// the credentials actually expiring. This is beneficial so race conditions
	// with expiring credentials do not cause request to fail unexpectedly
	// due to ExpiredTokenException exceptions.
	//
	// So a ExpiryWindow of 10s would cause calls to IsExpired() to return true
	// 10 seconds before the credentials are actually expired.
	//
	// If ExpiryWindow is 0 or less it will be ignored.
	ExpiryWindow time.Duration

	// Optional authorization token value if set will be used as the value of
	// the Authorization header of the endpoint credential request.
	AuthorizationToken string
}

// NewProviderClient returns a credentials Provider for retrieving AWS credentials
// from arbitrary endpoint.
func NewProviderClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) credentials.Provider {
	p := &Provider{
		Client: client.New(
			cfg,
			metadata.ClientInfo{
				ServiceName: "CredentialsEndpoint",
				Endpoint:    endpoint,
			},
			handlers,
		),
	}

	p.Client.Handlers.Unmarshal.PushBack(unmarshalHandler)
	p.Client.Handlers.UnmarshalError.PushBack(unmarshalError)
	p.Client.Handlers.Validate.Clear()
	p.Client.Handlers.Validate.PushBack(validateEndpointHandler)

	for _, option := range options {
		option(p)
	}

	return p
}

// NewCredentialsClient returns a Credentials wrapper for retrieving credentials
// from an arbitrary endpoint concurrently. The client will request the
func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials {
	return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...))
}

// IsExpired returns true if the credentials retrieved are expired, or not yet
// retrieved.
func (p *Provider) IsExpired() bool {
	if p.staticCreds {
		return false
	}
	return p.Expiry.IsExpired()
}

// Retrieve will attempt to request the credentials from the endpoint the Provider
// was configured for. And error will be returned if the retrieval fails.
func (p *Provider) Retrieve() (credentials.Value, error) {
	resp, err := p.getCredentials()
	if err != nil {
		return credentials.Value{ProviderName: ProviderName},
			awserr.New("CredentialsEndpointError", "failed to load credentials", err)
	}

	if resp.Expiration != nil {
		p.SetExpiration(*resp.Expiration, p.ExpiryWindow)
	} else {
		p.staticCreds = true
	}

	return credentials.Value{
		AccessKeyID:     resp.AccessKeyID,
		SecretAccessKey: resp.SecretAccessKey,
		SessionToken:    resp.Token,
		ProviderName:    ProviderName,
	}, nil
}

type getCredentialsOutput struct {
	Expiration      *time.Time
	AccessKeyID     string
	SecretAccessKey string
	Token           string
}

type errorOutput struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

func (p *Provider) getCredentials() (*getCredentialsOutput, error) {
	op := &request.Operation{
		Name:       "GetCredentials",
		HTTPMethod: "GET",
	}

	out := &getCredentialsOutput{}
	req := p.Client.NewRequest(op, nil, out)
	req.HTTPRequest.Header.Set("Accept", "application/json")
	if authToken := p.AuthorizationToken; len(authToken) != 0 {
		req.HTTPRequest.Header.Set("Authorization", authToken)
	}

	return out, req.Send()
}

func validateEndpointHandler(r *request.Request) {
	if len(r.ClientInfo.Endpoint) == 0 {
		r.Error = aws.ErrMissingEndpoint
	}
}

func unmarshalHandler(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	out := r.Data.(*getCredentialsOutput)
	if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&out); err != nil {
		r.Error = awserr.New(request.ErrCodeSerialization,
			"failed to decode endpoint credentials",
			err,
		)
	}
}

func unmarshalError(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	var errOut errorOutput
	err := jsonutil.UnmarshalJSONError(&errOut, r.HTTPResponse.Body)
	if err != nil {
		r.Error = awserr.NewRequestFailure(
			awserr.New(request.ErrCodeSerialization,
				"failed to decode error message", err),
			r.HTTPResponse.StatusCode,
			r.RequestID,
		)
		return
	}

	// Response body format is not consistent between metadata endpoints.
	// Grab the error message as a string and include that as the source error
	r.Error = awserr.New(errOut.Code, errOut.Message, nil)
}
<commit_msg>aws/credentials/endpointcreds: Update NewCredentialsClient docstring (#2771)<commit_after>// Package endpointcreds provides support for retrieving credentials from an
// arbitrary HTTP endpoint.
//
// The credentials endpoint Provider can receive both static and refreshable
// credentials that will expire. Credentials are static when an "Expiration"
// value is not provided in the endpoint's response.
//
// Static credentials will never expire once they have been retrieved. The format
// of the static credentials response:
//    {
//        "AccessKeyId" : "MUA...",
//        "SecretAccessKey" : "/7PC5om....",
//    }
//
// Refreshable credentials will expire within the "ExpiryWindow" of the Expiration
// value in the response. The format of the refreshable credentials response:
//    {
//        "AccessKeyId" : "MUA...",
//        "SecretAccessKey" : "/7PC5om....",
//        "Token" : "AQoDY....=",
//        "Expiration" : "2016-02-25T06:03:31Z"
//    }
//
// Errors should be returned in the following format and only returned with 400
// or 500 HTTP status codes.
//    {
//        "code": "ErrorCode",
//        "message": "Helpful error message."
//    }
package endpointcreds

import (
	"encoding/json"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/client"
	"github.com/aws/aws-sdk-go/aws/client/metadata"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
)

// ProviderName is the name of the credentials provider.
const ProviderName = `CredentialsEndpointProvider`

// Provider satisfies the credentials.Provider interface, and is a client to
// retrieve credentials from an arbitrary endpoint.
type Provider struct {
	staticCreds bool
	credentials.Expiry

	// Requires a AWS Client to make HTTP requests to the endpoint with.
	// the Endpoint the request will be made to is provided by the aws.Config's
	// Endpoint value.
	Client *client.Client

	// ExpiryWindow will allow the credentials to trigger refreshing prior to
	// the credentials actually expiring. This is beneficial so race conditions
	// with expiring credentials do not cause request to fail unexpectedly
	// due to ExpiredTokenException exceptions.
	//
	// So a ExpiryWindow of 10s would cause calls to IsExpired() to return true
	// 10 seconds before the credentials are actually expired.
	//
	// If ExpiryWindow is 0 or less it will be ignored.
	ExpiryWindow time.Duration

	// Optional authorization token value if set will be used as the value of
	// the Authorization header of the endpoint credential request.
	AuthorizationToken string
}

// NewProviderClient returns a credentials Provider for retrieving AWS credentials
// from arbitrary endpoint.
func NewProviderClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) credentials.Provider {
	p := &Provider{
		Client: client.New(
			cfg,
			metadata.ClientInfo{
				ServiceName: "CredentialsEndpoint",
				Endpoint:    endpoint,
			},
			handlers,
		),
	}

	p.Client.Handlers.Unmarshal.PushBack(unmarshalHandler)
	p.Client.Handlers.UnmarshalError.PushBack(unmarshalError)
	p.Client.Handlers.Validate.Clear()
	p.Client.Handlers.Validate.PushBack(validateEndpointHandler)

	for _, option := range options {
		option(p)
	}

	return p
}

// NewCredentialsClient returns a pointer to a new Credentials object
// wrapping the endpoint credentials Provider.
func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials {
	return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...))
}

// IsExpired returns true if the credentials retrieved are expired, or not yet
// retrieved.
func (p *Provider) IsExpired() bool {
	if p.staticCreds {
		return false
	}
	return p.Expiry.IsExpired()
}

// Retrieve will attempt to request the credentials from the endpoint the Provider
// was configured for. And error will be returned if the retrieval fails.
func (p *Provider) Retrieve() (credentials.Value, error) {
	resp, err := p.getCredentials()
	if err != nil {
		return credentials.Value{ProviderName: ProviderName},
			awserr.New("CredentialsEndpointError", "failed to load credentials", err)
	}

	if resp.Expiration != nil {
		p.SetExpiration(*resp.Expiration, p.ExpiryWindow)
	} else {
		p.staticCreds = true
	}

	return credentials.Value{
		AccessKeyID:     resp.AccessKeyID,
		SecretAccessKey: resp.SecretAccessKey,
		SessionToken:    resp.Token,
		ProviderName:    ProviderName,
	}, nil
}

type getCredentialsOutput struct {
	Expiration      *time.Time
	AccessKeyID     string
	SecretAccessKey string
	Token           string
}

type errorOutput struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

func (p *Provider) getCredentials() (*getCredentialsOutput, error) {
	op := &request.Operation{
		Name:       "GetCredentials",
		HTTPMethod: "GET",
	}

	out := &getCredentialsOutput{}
	req := p.Client.NewRequest(op, nil, out)
	req.HTTPRequest.Header.Set("Accept", "application/json")
	if authToken := p.AuthorizationToken; len(authToken) != 0 {
		req.HTTPRequest.Header.Set("Authorization", authToken)
	}

	return out, req.Send()
}

func validateEndpointHandler(r *request.Request) {
	if len(r.ClientInfo.Endpoint) == 0 {
		r.Error = aws.ErrMissingEndpoint
	}
}

func unmarshalHandler(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	out := r.Data.(*getCredentialsOutput)
	if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&out); err != nil {
		r.Error = awserr.New(request.ErrCodeSerialization,
			"failed to decode endpoint credentials",
			err,
		)
	}
}

func unmarshalError(r *request.Request) {
	defer r.HTTPResponse.Body.Close()

	var errOut errorOutput
	err := jsonutil.UnmarshalJSONError(&errOut, r.HTTPResponse.Body)
	if err != nil {
		r.Error = awserr.NewRequestFailure(
			awserr.New(request.ErrCodeSerialization,
				"failed to decode error message", err),
			r.HTTPResponse.StatusCode,
			r.RequestID,
		)
		return
	}

	// Response body format is not consistent between metadata endpoints.
	// Grab the error message as a string and include that as the source error
	r.Error = awserr.New(errOut.Code, errOut.Message, nil)
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"log"
	"regexp"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ssoadmin"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
	"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"
)

func dataSourceAwsSsoPermissionSet() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsSsoPermissionSetRead,

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"created_date": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"instance_arn": {
				Type:     schema.TypeString,
				Required: true,
				ValidateFunc: validation.All(
					validation.StringLenBetween(10, 1224),
					validation.StringMatch(regexp.MustCompile(`^arn:aws(-[a-z]+)*:sso:::instance/(sso)?ins-[a-zA-Z0-9-.]{16}$`), "must match arn:aws(-[a-z]+)*:sso:::instance/(sso)?ins-[a-zA-Z0-9-.]{16}"),
				),
			},

			"name": {
				Type:     schema.TypeString,
				Required: true,
				ValidateFunc: validation.All(
					validation.StringLenBetween(1, 32),
					validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]+$`), "must match [\\w+=,.@-]"),
				),
			},

			"description": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"session_duration": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"relay_state": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"inline_policy": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"managed_policy_arns": {
				Type:     schema.TypeSet,
				Computed: true,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
			},

			"tags": tagsSchemaComputed(),
		},
	}
}

func dataSourceAwsSsoPermissionSetRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ssoadminconn
	ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig

	instanceArn := d.Get("instance_arn").(string)
	name := d.Get("name").(string)

	log.Printf("[DEBUG] Reading AWS SSO Permission Sets")

	var permissionSetArn string
	var permissionSet *ssoadmin.PermissionSet
	var permissionSetErr error

	req := &ssoadmin.ListPermissionSetsInput{
		InstanceArn: aws.String(instanceArn),
	}
	err := conn.ListPermissionSetsPages(req, func(page *ssoadmin.ListPermissionSetsOutput, lastPage bool) bool {
		if page != nil && len(page.PermissionSets) != 0 {
			for _, ps := range page.PermissionSets {
				permissionSetArn = aws.StringValue(ps)
				log.Printf("[DEBUG] Reading AWS SSO Permission Set: %v", permissionSetArn)
				var permissionSetResp *ssoadmin.DescribePermissionSetOutput
				permissionSetResp, permissionSetErr = conn.DescribePermissionSet(&ssoadmin.DescribePermissionSetInput{
					InstanceArn:      aws.String(instanceArn),
					PermissionSetArn: aws.String(permissionSetArn),
				})
				if permissionSetErr != nil {
					return false
				}
				if aws.StringValue(permissionSetResp.PermissionSet.Name) == name {
					permissionSet = permissionSetResp.PermissionSet
					return false
				}
			}
		}
		return !lastPage
	})

	if err != nil {
		return fmt.Errorf("Error getting AWS SSO Permission Sets: %s", err)
	}

	if permissionSetErr != nil {
		return fmt.Errorf("Error getting AWS SSO Permission Set: %s", permissionSetErr)
	}

	if permissionSet == nil {
		return fmt.Errorf("AWS SSO Permission Set %s not found", name)
	}

	log.Printf("[DEBUG] Found AWS SSO Permission Set: %s", permissionSet)

	log.Printf("[DEBUG] Getting Inline Policy for AWS SSO Permission Set")
	inlinePolicyResp, inlinePolicyErr := conn.GetInlinePolicyForPermissionSet(&ssoadmin.GetInlinePolicyForPermissionSetInput{
		InstanceArn:      aws.String(instanceArn),
		PermissionSetArn: aws.String(permissionSetArn),
	})
	if inlinePolicyErr != nil {
		return fmt.Errorf("Error getting Inline Policy for AWS SSO Permission Set: %s", inlinePolicyErr)
	}

	log.Printf("[DEBUG] Getting Managed Policies for AWS SSO Permission Set")
	var managedPolicyArns []string
	managedPoliciesReq := &ssoadmin.ListManagedPoliciesInPermissionSetInput{
		InstanceArn:      aws.String(instanceArn),
		PermissionSetArn: aws.String(permissionSetArn),
	}
	managedPoliciesErr := conn.ListManagedPoliciesInPermissionSetPages(managedPoliciesReq, func(page *ssoadmin.ListManagedPoliciesInPermissionSetOutput, lastPage bool) bool {
		for _, managedPolicy := range page.AttachedManagedPolicies {
			managedPolicyArns = append(managedPolicyArns, aws.StringValue(managedPolicy.Arn))
		}
		return !lastPage
	})
	if managedPoliciesErr != nil {
		return fmt.Errorf("Error getting Managed Policies for AWS SSO Permission Set: %s", managedPoliciesErr)
	}

	tags, tagsErr := keyvaluetags.SsoListTags(conn, permissionSetArn, instanceArn)
	if tagsErr != nil {
		return fmt.Errorf("Error listing tags for AWS SSO Permission Set (%s): %s", permissionSetArn, tagsErr)
	}

	d.SetId(permissionSetArn)
	d.Set("arn", permissionSetArn)
	d.Set("created_date", permissionSet.CreatedDate.Format(time.RFC3339))
	d.Set("instance_arn", instanceArn)
	d.Set("name", permissionSet.Name)
	d.Set("description", permissionSet.Description)
	d.Set("session_duration", permissionSet.SessionDuration)
	d.Set("relay_state", permissionSet.RelayState)
	d.Set("inline_policy", inlinePolicyResp.InlinePolicy)
	d.Set("managed_policy_arns", managedPolicyArns)
	tagsMapErr := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map())
	if tagsMapErr != nil {
		return fmt.Errorf("Error setting tags: %s", tagsMapErr)
	}

	return nil
}
<commit_msg>Update aws/data_source_aws_sso_permission_set.go<commit_after>package aws

import (
	"fmt"
	"log"
	"regexp"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ssoadmin"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
	"github.com/terraform-providers/terraform-provider-aws/aws/internal/keyvaluetags"
)

func dataSourceAwsSsoPermissionSet() *schema.Resource {
	return &schema.Resource{
		Read: dataSourceAwsSsoPermissionSetRead,

		Schema: map[string]*schema.Schema{
			"arn": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"created_date": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"instance_arn": {
				Type:     schema.TypeString,
				Required: true,
				ValidateFunc: validation.All(
					validation.StringLenBetween(10, 1224),
					validation.StringMatch(regexp.MustCompile(`^arn:aws(-[a-z]+)*:sso:::instance/(sso)?ins-[a-zA-Z0-9-.]{16}$`), "must match arn:aws(-[a-z]+)*:sso:::instance/(sso)?ins-[a-zA-Z0-9-.]{16}"),
				),
			},

			"name": {
				Type:     schema.TypeString,
				Required: true,
				ValidateFunc: validation.All(
					validation.StringLenBetween(1, 32),
					validation.StringMatch(regexp.MustCompile(`^[\w+=,.@-]+$`), "must match [\\w+=,.@-]"),
				),
			},

			"description": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"session_duration": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"relay_state": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"inline_policy": {
				Type:     schema.TypeString,
				Computed: true,
			},

			"managed_policy_arns": {
				Type:     schema.TypeSet,
				Computed: true,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
			},

			"tags": tagsSchemaComputed(),
		},
	}
}

func dataSourceAwsSsoPermissionSetRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).ssoadminconn
	ignoreTagsConfig := meta.(*AWSClient).IgnoreTagsConfig

	instanceArn := d.Get("instance_arn").(string)
	name := d.Get("name").(string)

	log.Printf("[DEBUG] Reading AWS SSO Permission Sets")

	var permissionSetArn string
	var permissionSet *ssoadmin.PermissionSet
	var permissionSetErr error

	req := &ssoadmin.ListPermissionSetsInput{
		InstanceArn: aws.String(instanceArn),
	}
	err := conn.ListPermissionSetsPages(req, func(page *ssoadmin.ListPermissionSetsOutput, lastPage bool) bool {
		if page != nil && len(page.PermissionSets) != 0 {
			for _, ps := range page.PermissionSets {
				permissionSetArn = aws.StringValue(ps)
				log.Printf("[DEBUG] Reading AWS SSO Permission Set: %v", permissionSetArn)
				var permissionSetResp *ssoadmin.DescribePermissionSetOutput
				permissionSetResp, permissionSetErr = conn.DescribePermissionSet(&ssoadmin.DescribePermissionSetInput{
					InstanceArn:      aws.String(instanceArn),
					PermissionSetArn: aws.String(permissionSetArn),
				})
				if permissionSetErr != nil {
					return false
				}
				if aws.StringValue(permissionSetResp.PermissionSet.Name) == name {
					permissionSet = permissionSetResp.PermissionSet
					return false
				}
			}
		}
		return !lastPage
	})

	if err != nil {
		return fmt.Errorf("Error getting AWS SSO Permission Sets: %w", err)
	}

	if permissionSetErr != nil {
		return fmt.Errorf("Error getting AWS SSO Permission Set: %s", permissionSetErr)
	}

	if permissionSet == nil {
		return fmt.Errorf("AWS SSO Permission Set %s not found", name)
	}

	log.Printf("[DEBUG] Found AWS SSO Permission Set: %s", permissionSet)

	log.Printf("[DEBUG] Getting Inline Policy for AWS SSO Permission Set")
	inlinePolicyResp, inlinePolicyErr := conn.GetInlinePolicyForPermissionSet(&ssoadmin.GetInlinePolicyForPermissionSetInput{
		InstanceArn:      aws.String(instanceArn),
		PermissionSetArn: aws.String(permissionSetArn),
	})
	if inlinePolicyErr != nil {
		return fmt.Errorf("Error getting Inline Policy for AWS SSO Permission Set: %s", inlinePolicyErr)
	}

	log.Printf("[DEBUG] Getting Managed Policies for AWS SSO Permission Set")
	var managedPolicyArns []string
	managedPoliciesReq := &ssoadmin.ListManagedPoliciesInPermissionSetInput{
		InstanceArn:      aws.String(instanceArn),
		PermissionSetArn: aws.String(permissionSetArn),
	}
	managedPoliciesErr := conn.ListManagedPoliciesInPermissionSetPages(managedPoliciesReq, func(page *ssoadmin.ListManagedPoliciesInPermissionSetOutput, lastPage bool) bool {
		for _, managedPolicy := range page.AttachedManagedPolicies {
			managedPolicyArns = append(managedPolicyArns, aws.StringValue(managedPolicy.Arn))
		}
		return !lastPage
	})
	if managedPoliciesErr != nil {
		return fmt.Errorf("Error getting Managed Policies for AWS SSO Permission Set: %s", managedPoliciesErr)
	}

	tags, tagsErr := keyvaluetags.SsoListTags(conn, permissionSetArn, instanceArn)
	if tagsErr != nil {
		return fmt.Errorf("Error listing tags for AWS SSO Permission Set (%s): %s", permissionSetArn, tagsErr)
	}

	d.SetId(permissionSetArn)
	d.Set("arn", permissionSetArn)
	d.Set("created_date", permissionSet.CreatedDate.Format(time.RFC3339))
	d.Set("instance_arn", instanceArn)
	d.Set("name", permissionSet.Name)
	d.Set("description", permissionSet.Description)
	d.Set("session_duration", permissionSet.SessionDuration)
	d.Set("relay_state", permissionSet.RelayState)
	d.Set("inline_policy", inlinePolicyResp.InlinePolicy)
	d.Set("managed_policy_arns", managedPolicyArns)
	tagsMapErr := d.Set("tags", tags.IgnoreAws().IgnoreConfig(ignoreTagsConfig).Map())
	if tagsMapErr != nil {
		return fmt.Errorf("Error setting tags: %s", tagsMapErr)
	}

	return nil
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/guardduty"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func testAccAwsGuardDutyFilter_basic(t *testing.T) {
	resourceName := "aws_guardduty_filter.test"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsGuardDutyFilterDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccGuardDutyFilterConfig_full(),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsGuardDutyFilterExists(resourceName),
					resource.TestCheckResourceAttrPair(resourceName, "detector_id", "aws_guardduty_detector.test", "id"),
					resource.TestCheckResourceAttr(resourceName, "name", "test-filter"),
					resource.TestCheckResourceAttr(resourceName, "action", "ARCHIVE"),
					resource.TestCheckResourceAttr(resourceName, "rank", "1"),
					resource.TestCheckResourceAttrSet(resourceName, "finding_criteria"),
				),
			},
			{
				Config: testAccGuardDutyFilterConfigNoop_full(),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsGuardDutyFilterExists(resourceName),
					resource.TestCheckResourceAttrPair(resourceName, "detector_id", "aws_guardduty_detector.test", "id"),
					resource.TestCheckResourceAttr(resourceName, "name", "test-filter"),
					resource.TestCheckResourceAttr(resourceName, "action", "NOOP"),
					resource.TestCheckResourceAttr(resourceName, "rank", "1"),
					resource.TestCheckResourceAttrSet(resourceName, "finding_criteria"),
				),
			},
		},
	})
}

func testAccAwsGuardDutyFilter_import(t *testing.T) {
	resourceName := "aws_guardduty_filter.test"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsGuardDutyFilterDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccGuardDutyFilterConfig_full(),
			},

			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func testAccCheckAwsGuardDutyFilterDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).guarddutyconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_guardduty_filter" {
			continue
		}

		detectorID, filterName, err := parseImportedId(rs.Primary.ID)
		if err != nil {
			return err
		}

		input := &guardduty.GetFilterInput{
			DetectorId: aws.String(detectorID),
			FilterName: aws.String(filterName),
		}

		_, err = conn.GetFilter(input)
		if err != nil {
			if isAWSErr(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") {
				return nil
			}
			return err
		}

		return fmt.Errorf("Expected GuardDuty Filter to be destroyed, %s found", rs.Primary.Attributes["filter_name"])
	}

	return nil
}

func testAccCheckAwsGuardDutyFilterExists(name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		_, ok := s.RootModule().Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		return nil
	}
}

func testAccGuardDutyFilterConfig_full() string {
	return `
resource "aws_guardduty_filter" "test" {
  detector_id = "${aws_guardduty_detector.test.id}"
	name        = "test-filter"
	action      = "ARCHIVE"
	rank        = 1

  finding_criteria {
    criterion {
      field     = "region"
      values    = ["eu-west-1"]
      condition = "equals"
    }

    criterion {
      field     = "service.additionalInfo.threatListName"
      values    = ["some-threat", "another-threat"]
      condition = "not_equals"
    }

    criterion {
      field     = "updatedAt"
      values    = ["1570744740000"]
      condition = "less_than"
    }

    criterion {
      field     = "updatedAt"
      values    = ["1570744240000"]
      condition = "greater_than"
    }
  }
}

resource "aws_guardduty_detector" "test" {
  enable = true
}`
}

func testAccGuardDutyFilterConfigNoop_full() string {
	return `
resource "aws_guardduty_filter" "test" {
  detector_id = "${aws_guardduty_detector.test.id}"
	name        = "test-filter"
	action      = "NOOP"
	rank        = 1

  finding_criteria {
    criterion {
      field     = "region"
      values    = ["eu-west-1"]
      condition = "equals"
    }

    criterion {
      field     = "service.additionalInfo.threatListName"
      values    = ["some-threat", "another-threat"]
      condition = "not_equals"
    }

    criterion {
      field     = "updatedAt"
      values    = ["1570744740000"]
      condition = "less_than"
    }

    criterion {
      field     = "updatedAt"
      values    = ["1570744240000"]
      condition = "greater_than"
    }
  }
}

resource "aws_guardduty_detector" "test" {
  enable = true
}`
}
<commit_msg>Add a variable detectorResourceName<commit_after>package aws

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/guardduty"
	"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/terraform"
)

func testAccAwsGuardDutyFilter_basic(t *testing.T) {
	resourceName := "aws_guardduty_filter.test"
	detectorResourceName := "aws_guardduty_detector.test"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsGuardDutyFilterDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccGuardDutyFilterConfig_full(),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsGuardDutyFilterExists(resourceName),
					resource.TestCheckResourceAttrPair(resourceName, "detector_id", detectorResourceName, "id"),
					resource.TestCheckResourceAttr(resourceName, "name", "test-filter"),
					resource.TestCheckResourceAttr(resourceName, "action", "ARCHIVE"),
					resource.TestCheckResourceAttr(resourceName, "rank", "1"),
					resource.TestCheckResourceAttrSet(resourceName, "finding_criteria"),
				),
			},
			{
				Config: testAccGuardDutyFilterConfigNoop_full(),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsGuardDutyFilterExists(resourceName),
					resource.TestCheckResourceAttrPair(resourceName, "detector_id", detectorResourceName, "id"),
					resource.TestCheckResourceAttr(resourceName, "name", "test-filter"),
					resource.TestCheckResourceAttr(resourceName, "action", "NOOP"),
					resource.TestCheckResourceAttr(resourceName, "rank", "1"),
					resource.TestCheckResourceAttrSet(resourceName, "finding_criteria"),
				),
			},
		},
	})
}

func testAccAwsGuardDutyFilter_import(t *testing.T) {
	resourceName := "aws_guardduty_filter.test"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsGuardDutyFilterDestroy,
		Steps: []resource.TestStep{
			{
				Config: testAccGuardDutyFilterConfig_full(),
			},

			{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

func testAccCheckAwsGuardDutyFilterDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).guarddutyconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_guardduty_filter" {
			continue
		}

		detectorID, filterName, err := parseImportedId(rs.Primary.ID)
		if err != nil {
			return err
		}

		input := &guardduty.GetFilterInput{
			DetectorId: aws.String(detectorID),
			FilterName: aws.String(filterName),
		}

		_, err = conn.GetFilter(input)
		if err != nil {
			if isAWSErr(err, guardduty.ErrCodeBadRequestException, "The request is rejected because the input detectorId is not owned by the current account.") {
				return nil
			}
			return err
		}

		return fmt.Errorf("Expected GuardDuty Filter to be destroyed, %s found", rs.Primary.Attributes["filter_name"])
	}

	return nil
}

func testAccCheckAwsGuardDutyFilterExists(name string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		_, ok := s.RootModule().Resources[name]
		if !ok {
			return fmt.Errorf("Not found: %s", name)
		}

		return nil
	}
}

func testAccGuardDutyFilterConfig_full() string {
	return `
resource "aws_guardduty_filter" "test" {
  detector_id = "${aws_guardduty_detector.test.id}"
	name        = "test-filter"
	action      = "ARCHIVE"
	rank        = 1

  finding_criteria {
    criterion {
      field     = "region"
      values    = ["eu-west-1"]
      condition = "equals"
    }

    criterion {
      field     = "service.additionalInfo.threatListName"
      values    = ["some-threat", "another-threat"]
      condition = "not_equals"
    }

    criterion {
      field     = "updatedAt"
      values    = ["1570744740000"]
      condition = "less_than"
    }

    criterion {
      field     = "updatedAt"
      values    = ["1570744240000"]
      condition = "greater_than"
    }
  }
}

resource "aws_guardduty_detector" "test" {
  enable = true
}`
}

func testAccGuardDutyFilterConfigNoop_full() string {
	return `
resource "aws_guardduty_filter" "test" {
  detector_id = "${aws_guardduty_detector.test.id}"
	name        = "test-filter"
	action      = "NOOP"
	rank        = 1

  finding_criteria {
    criterion {
      field     = "region"
      values    = ["eu-west-1"]
      condition = "equals"
    }

    criterion {
      field     = "service.additionalInfo.threatListName"
      values    = ["some-threat", "another-threat"]
      condition = "not_equals"
    }

    criterion {
      field     = "updatedAt"
      values    = ["1570744740000"]
      condition = "less_than"
    }

    criterion {
      field     = "updatedAt"
      values    = ["1570744240000"]
      condition = "greater_than"
    }
  }
}

resource "aws_guardduty_detector" "test" {
  enable = true
}`
}
<|endoftext|>


<commit_before>// Copyright 2011 The GoGL Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE.mkd file.

package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

func MakeSpecDocUrl(vendor, extension string) string {
	return fmt.Sprintf("http://www.opengl.org/registry/specs/%s/%s.txt", vendor, extension)
}

func GeneratePackages(packages Packages, typeMap TypeMap) error {
	for packageName, pak := range packages {
		//fmt.Printf("Generating %s ...\n",  packageName);
		if err := generatePackage(packageName, pak, typeMap); err != nil {
			return err
		}
	}
	return nil
}

func generatePackage(packageName string, pak *Package, typeMap TypeMap) error {
	absPath, err := filepath.Abs(packageName)
	if err != nil {
		return err
	}
	err = os.MkdirAll(absPath, 0755)
	if err != nil {
		return err
	}
	w, err := os.Create(filepath.Join(absPath, fmt.Sprintf("%s.go", packageName)))
	if err != nil {
		return err
	}
	defer w.Close()
	return writePackage(w, packageName, pak, typeMap);
}

func writePackage(w io.Writer, packageName string, pak *Package, typeMap TypeMap) error {
	fmt.Fprintf(w, "// OpenGL.\n")
	fmt.Fprintf(w, "// \n")
	fmt.Fprintf(w, "//  %s \n", MakeSpecDocUrl("ARB", "multisample"))
	fmt.Fprintf(w, "package %s\n", packageName)

	fmt.Fprintf(w, "\n/*\n")
	fmt.Fprintf(w, "#cgo darwin  LDFLAGS: -framework OpenGL\n")
	fmt.Fprintf(w, "#cgo linux   LDFLAGS: -lGL\n")
	fmt.Fprintf(w, "#cgo windows LDFLAGS: -lopengl32\n")
	fmt.Fprintf(w, "\n")
	fmt.Fprintf(w, "#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)\n")
	fmt.Fprintf(w, "#define WIN32_LEAN_AND_MEAN 1\n")
	fmt.Fprintf(w, "#include <windows.h>\n")
	fmt.Fprintf(w, "#endif\n")
	fmt.Fprintf(w, "#ifndef APIENTRY\n")
	fmt.Fprintf(w, "#define APIENTRY\n")
	fmt.Fprintf(w, "#endif\n")
	fmt.Fprintf(w, "#ifndef APIENTRYP\n")
	fmt.Fprintf(w, "#define APIENTRYP APIENTRY *\n")
	fmt.Fprintf(w, "#endif\n")
	fmt.Fprintf(w, "#ifndef GLAPI\n")
	fmt.Fprintf(w, "#define GLAPI extern\n")
	fmt.Fprintf(w, "#endif\n\n")

	fmt.Fprintf(w, "typedef unsigned int GLenum;\n")
	fmt.Fprintf(w, "typedef unsigned char GLboolean;\n")
	fmt.Fprintf(w, "typedef unsigned int GLbitfield;\n")
	fmt.Fprintf(w, "typedef signed char GLbyte;\n")
	fmt.Fprintf(w, "typedef short GLshort;\n")
	fmt.Fprintf(w, "typedef int GLint;\n")
	fmt.Fprintf(w, "typedef int GLsizei;\n")
	fmt.Fprintf(w, "typedef unsigned char GLubyte;\n")
	fmt.Fprintf(w, "typedef unsigned short GLushort;\n")
	fmt.Fprintf(w, "typedef unsigned int GLuint;\n")
	fmt.Fprintf(w, "typedef unsigned short GLhalf;\n")
	fmt.Fprintf(w, "typedef float GLfloat;\n")
	fmt.Fprintf(w, "typedef float GLclampf;\n")
	fmt.Fprintf(w, "typedef double GLdouble;\n")
	fmt.Fprintf(w, "typedef double GLclampd;\n")
	fmt.Fprintf(w, "typedef void GLvoid;\n\n")

	//write

	fmt.Fprintf(w, "*/\n")
	fmt.Fprintf(w, "import \"C\"\n")

	// write passthru

	return nil
}

func generate(fname string, enums EnumCategories, functions FunctionCategories, typeMap TypeMap) error {
	w, err := os.Create(fname)
	if err != nil {
		return err
	}
	defer w.Close()

	writeCFuncPtrDefinitions(functions, w)
	writeCFunctionDeclarations(functions, w)
	writeGetProcAddrsDeclarations(functions, w)
	fmt.Fprintf(w, "import \"C\"\n\n")

	//writeGoEnumDefinitions(enums, w)
	//writeGoFunctionDefinitions(functions, w)

	fmt.Fprintf(w, "// EOF\n")
	return nil
}

func writeGoEnumDefinitions(enums EnumCategories, w io.Writer) {
	fmt.Fprintf(w, "const (\n")
	for name, enums := range enums {
		fmt.Fprintf(w, "\t// %s:\n", name)
		for _, e := range enums {
			fmt.Fprintf(w, "\t%s = %s\n", e.Name, e.Value)
		}
	}
	fmt.Fprintf(w, ")\n")
}

func writeGoFunctionDefinitions(functions FunctionCategories, w io.Writer) {
	for cat, fs := range functions {
		fmt.Fprintf(w, "// %s\n", cat)
		for _, f := range fs {
			fmt.Fprintf(w, "func %s(", f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s %s", f.Parameters[p].Name, f.Parameters[p].Type)
				} else {
					fmt.Fprintf(w, "%s %s, ", f.Parameters[p].Name, f.Parameters[p].Type)
				}
			}
			fmt.Fprintf(w, ") {\n")
			fmt.Fprintf(w, "\tC.gogl%s(", f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s", f.Parameters[p].Name)
				} else {
					fmt.Fprintf(w, "%s, ", f.Parameters[p].Name)
				}
			}
			fmt.Fprintf(w, ")\n}\n")
		}
	}
}

func writeCFuncPtrDefinitions(functions FunctionCategories, w io.Writer) {
	fmt.Fprintf(w, "// /* function pointers: */\n")
	for cat, fs := range functions {
		fmt.Fprintf(w, "// /* %s */  \n", cat)
		for _, f := range fs {
			fmt.Fprintf(w, "// %s (*ptrgogl%s)(", f.Return, f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s %s", f.Parameters[p].Type, f.Parameters[p].Name)
				} else {
					fmt.Fprintf(w, "%s %s, ", f.Parameters[p].Type, f.Parameters[p].Name)
				}
			}
			fmt.Fprintf(w, ");\n")
		}
	}
	fmt.Fprintf(w, "// \n")
}

func writeCFunctionDeclarations(functions FunctionCategories, w io.Writer) {
	fmt.Fprintf(w, "// /* function declarations */\n")
	for cat, fs := range functions {
		fmt.Fprintf(w, "// /* %s */  \n", cat)
		for _, f := range fs {
			fmt.Fprintf(w, "// %s gogl%s(", f.Return, f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s %s", f.Parameters[p].Type, f.Parameters[p].Name)
				} else {
					fmt.Fprintf(w, "%s %s, ", f.Parameters[p].Type, f.Parameters[p].Name)
				}
			}
			fmt.Fprintf(w, ") {\n")
			fmt.Fprintf(w, "// \tptrgogl%s(", f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s", f.Parameters[p].Name)
				} else {
					fmt.Fprintf(w, "%s, ", f.Parameters[p].Name)
				}
			}
			fmt.Fprintf(w, ")\n// }\n")
		}
	}
}

func writeGetProcAddrsDeclarations(functions FunctionCategories, w io.Writer) {
	fmt.Fprintf(w, "// /* extension loading */\n")
	fmt.Fprintf(w, "// void* goglGetProcAddress(const char* name) { \n")
	fmt.Fprintf(w, "// #ifdef __APPLE__\n")
	fmt.Fprintf(w, "// \treturn NULL;\n")
	fmt.Fprintf(w, "// #elif WIN32\n")
	fmt.Fprintf(w, "// \treturn wglGetProcAddress((LPCSTR)name);\n")
	fmt.Fprintf(w, "// #else\n")
	fmt.Fprintf(w, "// \treturn glXGetProcddress((const GLubyte*)name);\n")
	fmt.Fprintf(w, "// #endif\n")
	fmt.Fprintf(w, "// }\n")
	for cat, fs := range functions {
		fmt.Fprintf(w, "// int init_%s() {\n", cat)
		for _, f := range fs {
			// TODO: Windows, Linux, ...
			fmt.Fprintf(w, "//\tptrgogl%s = goglGetProcAddress(\"gl%s\");\n", f.Name, f.Name)
		}
		fmt.Fprintf(w, "//\treturn 1;\n")
		fmt.Fprintf(w, "// }\n")
	}
}
<commit_msg>More generator code: function typedefs<commit_after>// Copyright 2011 The GoGL Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE.mkd file.

package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

func MakeSpecDocUrl(vendor, extension string) string {
	return fmt.Sprintf("http://www.opengl.org/registry/specs/%s/%s.txt", vendor, extension)
}

func GeneratePackages(packages Packages, typeMap TypeMap) error {
	for packageName, pak := range packages {
		//fmt.Printf("Generating %s ...\n",  packageName);
		if err := generatePackage(packageName, pak, typeMap); err != nil {
			return err
		}
	}
	return nil
}

func generatePackage(packageName string, pak *Package, typeMap TypeMap) error {
	absPath, err := filepath.Abs(packageName)
	if err != nil {
		return err
	}
	err = os.MkdirAll(absPath, 0755)
	if err != nil {
		return err
	}
	w, err := os.Create(filepath.Join(absPath, fmt.Sprintf("%s.go", packageName)))
	if err != nil {
		return err
	}
	defer w.Close()
	return writePackage(w, packageName, pak, typeMap);
}

func writePackage(w io.Writer, packageName string, pak *Package, typeMap TypeMap) error {
	fmt.Fprintf(w, "// OpenGL.\n")
	fmt.Fprintf(w, "package %s\n", packageName)

	fmt.Fprintf(w, "\n/*\n")

	fmt.Fprintf(w, "#cgo darwin  LDFLAGS: -framework OpenGL\n")
	fmt.Fprintf(w, "#cgo linux   LDFLAGS: -lGL\n")
	fmt.Fprintf(w, "#cgo windows LDFLAGS: -lopengl32\n\n")

	fmt.Fprintf(w, "#ifdef __APPLE__\n")
	fmt.Fprintf(w, "// TODO: add context header\n")
	fmt.Fprintf(w, "#elif defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)\n")
	fmt.Fprintf(w, "#define WIN32_LEAN_AND_MEAN 1\n")
	fmt.Fprintf(w, "#include <windows.h> // for wglGetProcAddress\n")
	fmt.Fprintf(w, "#else\n")
	fmt.Fprintf(w, "#include <X11/Xlib.h> // for glXGetProcAddress\n")
	fmt.Fprintf(w, "#include <GL/glx.h> \n")
	fmt.Fprintf(w, "#endif\n\n")

	fmt.Fprintf(w, "#ifndef APIENTRY\n")
	fmt.Fprintf(w, "#define APIENTRY\n")
	fmt.Fprintf(w, "#endif\n")
	fmt.Fprintf(w, "#ifndef APIENTRYP\n")
	fmt.Fprintf(w, "#define APIENTRYP APIENTRY *\n")
	fmt.Fprintf(w, "#endif\n")
	fmt.Fprintf(w, "#ifndef GLAPI\n")
	fmt.Fprintf(w, "#define GLAPI extern\n")
	fmt.Fprintf(w, "#endif\n\n")

	fmt.Fprintf(w, "typedef unsigned int GLenum;\n")
	fmt.Fprintf(w, "typedef unsigned char GLboolean;\n")
	fmt.Fprintf(w, "typedef unsigned int GLbitfield;\n")
	fmt.Fprintf(w, "typedef signed char GLbyte;\n")
	fmt.Fprintf(w, "typedef short GLshort;\n")
	fmt.Fprintf(w, "typedef int GLint;\n")
	fmt.Fprintf(w, "typedef int GLsizei;\n")
	fmt.Fprintf(w, "typedef unsigned char GLubyte;\n")
	fmt.Fprintf(w, "typedef unsigned short GLushort;\n")
	fmt.Fprintf(w, "typedef unsigned int GLuint;\n")
	fmt.Fprintf(w, "typedef unsigned short GLhalf;\n")
	fmt.Fprintf(w, "typedef float GLfloat;\n")
	fmt.Fprintf(w, "typedef float GLclampf;\n")
	fmt.Fprintf(w, "typedef double GLdouble;\n")
	fmt.Fprintf(w, "typedef double GLclampd;\n")
	fmt.Fprintf(w, "typedef void GLvoid;\n\n")

	// TODO: Write passthru defs from gl.spec

	fmt.Fprintf(w, "void* goglGetProcAddress(const char* name) { \n")
	fmt.Fprintf(w, "#ifdef __APPLE__\n")
	fmt.Fprintf(w, "	return NULL; // TODO: Add get proc addr for Mac.\n")
	fmt.Fprintf(w, "#elif _WIN32\n")
	fmt.Fprintf(w, "	return wglGetProcAddress((LPCSTR)name); // TODO: Not tested\n")
	fmt.Fprintf(w, "#else\n")
	fmt.Fprintf(w, "	return glXGetProcAddress((const GLubyte*)name);\n")
	fmt.Fprintf(w, "#endif\n")
	fmt.Fprintf(w, "}\n\n")

	writeCFuncTypeDefs(w, pak.Functions, typeMap)

	fmt.Fprintf(w, "*/\n")
	fmt.Fprintf(w, "import \"C\"\n\n")

	fmt.Fprintf(w, "// EOF")
	return nil
}

func writeCFuncTypeDefs(w io.Writer, functions FunctionCategories, typeMap TypeMap) {
	for cat, fs := range functions {
		fmt.Fprintf(w, "//  %s\n", cat)
		for _, f := range fs {
			if f.Return == "void" {
				fmt.Fprintf(w, "typedef void (APIENTRYP ptrgogl%s)(", f.Name)
			} else {
				fmt.Fprintf(w, "typedef %s (APIENTRYP ptrgogl%s)(", typeMap[f.Return], f.Name)
			}
			for p := 0; p < len(f.Parameters); p++ {
				if f.Parameters[p].InArray {
					fmt.Fprintf(w, "%s *%s", typeMap[f.Parameters[p].Type], f.Parameters[p].Name)
				} else {
					fmt.Fprintf(w, "%s %s", typeMap[f.Parameters[p].Type], f.Parameters[p].Name)
				}
				if p < len(f.Parameters)-1 {
					fmt.Fprintf(w, ", ")
				}
			}
			fmt.Fprintf(w, ");\n")
		}
	}
	fmt.Fprintf(w, "\n")
}

func writeGoEnumDefinitions(enums EnumCategories, w io.Writer) {
	fmt.Fprintf(w, "const (\n")
	for name, enums := range enums {
		fmt.Fprintf(w, "\t// %s:\n", name)
		for _, e := range enums {
			fmt.Fprintf(w, "\t%s = %s\n", e.Name, e.Value)
		}
	}
	fmt.Fprintf(w, ")\n")
}

func writeGoFunctionDefinitions(functions FunctionCategories, w io.Writer) {
	for cat, fs := range functions {
		fmt.Fprintf(w, "// %s\n", cat)
		for _, f := range fs {
			fmt.Fprintf(w, "func %s(", f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s %s", f.Parameters[p].Name, f.Parameters[p].Type)
				} else {
					fmt.Fprintf(w, "%s %s, ", f.Parameters[p].Name, f.Parameters[p].Type)
				}
			}
			fmt.Fprintf(w, ") {\n")
			fmt.Fprintf(w, "\tC.gogl%s(", f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s", f.Parameters[p].Name)
				} else {
					fmt.Fprintf(w, "%s, ", f.Parameters[p].Name)
				}
			}
			fmt.Fprintf(w, ")\n}\n")
		}
	}
}

func writeCFunctionDeclarations(functions FunctionCategories, w io.Writer) {
	fmt.Fprintf(w, "// /* function declarations */\n")
	for cat, fs := range functions {
		fmt.Fprintf(w, "// /* %s */  \n", cat)
		for _, f := range fs {
			fmt.Fprintf(w, "// %s gogl%s(", f.Return, f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s %s", f.Parameters[p].Type, f.Parameters[p].Name)
				} else {
					fmt.Fprintf(w, "%s %s, ", f.Parameters[p].Type, f.Parameters[p].Name)
				}
			}
			fmt.Fprintf(w, ") {\n")
			fmt.Fprintf(w, "// \tptrgogl%s(", f.Name)
			for p := 0; p < len(f.Parameters); p++ {
				if p == len(f.Parameters)-1 {
					fmt.Fprintf(w, "%s", f.Parameters[p].Name)
				} else {
					fmt.Fprintf(w, "%s, ", f.Parameters[p].Name)
				}
			}
			fmt.Fprintf(w, ")\n// }\n")
		}
	}
}

func writeGetProcAddrsDeclarations(functions FunctionCategories, w io.Writer) {

	for cat, fs := range functions {
		fmt.Fprintf(w, "// int init_%s() {\n", cat)
		for _, f := range fs {
			// TODO: Windows, Linux, ...
			fmt.Fprintf(w, "//\tptrgogl%s = goglGetProcAddress(\"gl%s\");\n", f.Name, f.Name)
		}
		fmt.Fprintf(w, "//\treturn 1;\n")
		fmt.Fprintf(w, "// }\n")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"go/printer"
	"go/types"
	"strings"
)

type structConfig struct {
	StructName       string
	StructText       string
	QueryBuilderName string
}

type Generator struct {
	buf    *bytes.Buffer
	name   string
	parser *Parser
	config structConfig
}

func NewGenerator() *Generator {
	return &Generator{
		buf: new(bytes.Buffer),
	}
}

func (g *Generator) init() {
	g.generateImports()
}

func (g *Generator) buildConfig() {
	structName := strings.TrimSuffix(g.name, "Schema")
	structTextBuf := new(bytes.Buffer)
	printer.Fprint(structTextBuf, g.parser.fileSet, g.parser.GetTypeByName(g.name))
	g.config = structConfig{
		StructName:       structName,
		StructText:       structTextBuf.String(),
		QueryBuilderName: fmt.Sprintf("%sQueryBuilder", structName),
	}
}

func (g *Generator) generateImports() {
	importStatments.Execute(g.buf, nil)
}

func (g *Generator) generateMainStruct() {
	templateMainStruct.Execute(g.buf, g.config)
}

func (g *Generator) generateQueryBuilder() {
	templateQueryBuilder.Execute(g.buf, g.config)
}

func (g *Generator) generateFieldSpecificTemplates() {

	obj := g.parser.defs[g.parser.GetIdentByName(g.name)]
	if obj == nil {
		panic("SHOULDN'T HAPPEN")
	}

	fieldToColumn := make(map[string]string)
	structType := obj.Type().Underlying().(*types.Struct)
	for i := 0; i < structType.NumFields(); i++ {
		field := structType.Field(i)
		fieldToColumn[field.Name()] = field.Name()
	}

	for i := 0; i < structType.NumFields(); i++ {
		f := structType.Field(i)
		fieldCnf := struct {
			FieldToColumn    map[string]string
			QueryBuilderName string
			FieldName        string
			FieldType        string
			Titelize         func(string) string
		}{
			FieldName:        f.Name(),
			FieldType:        f.Type().String(),
			FieldToColumn:    fieldToColumn,
			QueryBuilderName: g.config.QueryBuilderName,
			Titelize:         strings.Title,
		}
		templateWhereFunction.Execute(g.buf, fieldCnf)
		templateOrderByFunction.Execute(g.buf, fieldCnf)
	}
}

func (g *Generator) Generate(parser *Parser, name string) {
	g.name = name
	g.parser = parser
	g.buildConfig()
	g.generateMainStruct()
	g.generateQueryBuilder()
	g.generateFieldSpecificTemplates()
}

func (g *Generator) Flush() {
	fmt.Println(g.buf.String())
}
<commit_msg>Fixing the qualifier of the types<commit_after>package main

import (
	"bytes"
	"fmt"
	"go/printer"
	"go/types"
	"strings"
)

type structConfig struct {
	StructName       string
	StructText       string
	QueryBuilderName string
}

type Generator struct {
	buf    *bytes.Buffer
	name   string
	parser *Parser
	config structConfig
}

func NewGenerator() *Generator {
	return &Generator{
		buf: new(bytes.Buffer),
	}
}

func (g *Generator) init() {
	g.generateImports()
}

func (g *Generator) buildConfig() {
	structName := strings.TrimSuffix(g.name, "Schema")
	structTextBuf := new(bytes.Buffer)
	printer.Fprint(structTextBuf, g.parser.fileSet, g.parser.GetTypeByName(g.name))
	g.config = structConfig{
		StructName:       structName,
		StructText:       structTextBuf.String(),
		QueryBuilderName: fmt.Sprintf("%sQueryBuilder", structName),
	}
}

func (g *Generator) generateImports() {
	importStatments.Execute(g.buf, nil)
}

func (g *Generator) generateMainStruct() {
	templateMainStruct.Execute(g.buf, g.config)
}

func (g *Generator) generateQueryBuilder() {
	templateQueryBuilder.Execute(g.buf, g.config)
}

func (g *Generator) generateFieldSpecificTemplates() {

	obj := g.parser.defs[g.parser.GetIdentByName(g.name)]
	if obj == nil {
		panic("SHOULDN'T HAPPEN")
	}

	fieldToColumn := make(map[string]string)
	structType := obj.Type().Underlying().(*types.Struct)
	for i := 0; i < structType.NumFields(); i++ {
		field := structType.Field(i)
		fieldToColumn[field.Name()] = field.Name()
	}

	for i := 0; i < structType.NumFields(); i++ {
		f := structType.Field(i)
		fieldCnf := struct {
			FieldToColumn    map[string]string
			QueryBuilderName string
			FieldName        string
			FieldType        string
			Titelize         func(string) string
		}{
			FieldName:        f.Name(),
			FieldType:        types.TypeString(f.Type(), func(p *types.Package) string { return p.Name() }),
			FieldToColumn:    fieldToColumn,
			QueryBuilderName: g.config.QueryBuilderName,
			Titelize:         strings.Title,
		}
		templateWhereFunction.Execute(g.buf, fieldCnf)
		templateOrderByFunction.Execute(g.buf, fieldCnf)
	}
}

func (g *Generator) Generate(parser *Parser, name string) {
	g.name = name
	g.parser = parser
	g.buildConfig()
	g.generateMainStruct()
	g.generateQueryBuilder()
	g.generateFieldSpecificTemplates()
}

func (g *Generator) Flush() {
	fmt.Println(g.buf.String())
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"go/ast"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/RobotsAndPencils/go-swaggerLite/markup"
	"github.com/RobotsAndPencils/go-swaggerLite/parser"
)

const (
	AVAILABLE_FORMATS = "go|markdown"
)

var apiPackage = flag.String("apiPackage", "", "The package that implements the API controllers, relative to $GOPATH/src")
var mainApiFile = flag.String("mainApiFile", "", "The file that contains the general API annotations, relative to $GOPATH/src")
var basePath = flag.String("basePath", "", "Web service base path")
var outputFormat = flag.String("format", "go", "Output format type for the generated files: "+AVAILABLE_FORMATS)
var output = flag.String("output", "generatedSwaggerSpec.go", "The opitonal name of the output file to be generated")
var generatedPackage = flag.String("package", "main", "The opitonal package name of the output file to be generated")

var generatedFileTemplate = `package {{generagedPackage}}
//This file is generated automatically. Do not edit it manually.

import (
	"net/http"
	"strings"
)

func SwaggerApiHandler(prefix string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		resource := strings.TrimPrefix(r.URL.Path, prefix)
		resource = strings.Trim(resource, "/")

		if r.Method == "OPTIONS" {
			w.Header().Set("Access-Control-Allow-Origin", "*")
			w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
			w.Header().Set("Access-Control-Allow-Headers", "accept, authorization, content-type")
			w.Header().Set("Access-Control-Max-Age", "1800")
			w.WriteHeader(204)
			return
		}

		w.Header().Set("Access-Control-Allow-Origin", "*")

		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET")

		if resource == "" {
			w.Write([]byte(swaggerResourceListing))
			return
		}

		if json, ok := swaggerApiDescriptions[resource]; ok {
			w.Write([]byte(json))
		} else {
			w.WriteHeader(http.StatusNotFound)
		}
	}
}

var swaggerResourceListing = {{resourceListing}}
var swaggerApiDescriptions = {{apiDescriptions}}
`

// It must return true if funcDeclaration is controller. We will try to parse only comments before controllers
// Stubbed out for now
func IsController(funcDeclaration *ast.FuncDecl) bool {
	return true
}

func generateSwaggerDocs(parser *parser.Parser) {
	fd, err := os.Create(path.Join("./", *output))
	if err != nil {
		log.Fatalf("Can not create document file: %v\n", err)
	}
	defer fd.Close()

	var apiDescriptions bytes.Buffer
	for apiKey, apiDescription := range parser.TopLevelApis {
		apiDescriptions.WriteString("\"" + apiKey + "\":")

		apiDescriptions.WriteString("`")
		json, err := json.MarshalIndent(apiDescription, "", "    ")
		if err != nil {
			log.Fatalf("Can not serialise []ApiDescription to JSON: %v\n", err)
		}
		apiDescriptions.Write(json)
		apiDescriptions.WriteString("`,")
	}

	doc := strings.Replace(generatedFileTemplate, "{{resourceListing}}", "`"+string(getResourceListingJson(parser.Listing))+"`", -1)
	doc = strings.Replace(doc, "{{apiDescriptions}}", "map[string]string{"+apiDescriptions.String()+"}", -1)
	doc = strings.Replace(doc, "{{generagedPackage}}", *generatedPackage, -1)

	fd.WriteString(doc)
}

func InitParser() *parser.Parser {
	parser := parser.NewParser()

	parser.BasePath = *basePath
	parser.IsController = IsController

	parser.TypesImplementingMarshalInterface["NullString"] = "string"
	parser.TypesImplementingMarshalInterface["NullInt64"] = "int"
	parser.TypesImplementingMarshalInterface["NullFloat64"] = "float"
	parser.TypesImplementingMarshalInterface["NullBool"] = "bool"

	return parser
}

func main() {
	flag.Parse()

	if *mainApiFile == "" {
		*mainApiFile = *apiPackage + "/main.go"
	}
	if *apiPackage == "" {
		flag.PrintDefaults()
		return
	}

	parser := InitParser()
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		log.Fatalf("Please, set $GOPATH environment variable\n")
	}

	log.Println("Start parsing")
	gopaths := filepath.SplitList(gopath)
	var err error
	var errs string
	for _, gop := range gopaths {
		err = parser.ParseGeneralAPIInfo(path.Join(gop, "src", *mainApiFile))
		if err != nil {
			errs += fmt.Sprintf("    %s\n", err)
		} else {
			break
		}
	}
	if err != nil {
		log.Fatalf("Error locating main API File:\n%s", errs)
	}
	parser.ParseApi(*apiPackage)
	log.Println("Finish parsing")

	format := strings.ToLower(*outputFormat)
	switch format {
	case "go":
		generateSwaggerDocs(parser)
		log.Println("Doc file generated")
	case "markdown":
		markup.GenerateMarkup(parser, new(markup.MarkupMarkDown), output, ".md")
		log.Println("MarkDown file generated")
	default:
		log.Fatalf("Invalid -format specified. Must be one of %v.", AVAILABLE_FORMATS)
	}

}

func getResourceListingJson(listing *parser.ResourceListing) []byte {
	json, err := json.MarshalIndent(listing, "", "    ")
	if err != nil {
		log.Fatalf("Can not serialise ResourceListing to JSON: %v\n", err)
	}
	return json
}
<commit_msg>ApiDeclarations is a map and since a Go map item order is random, the generatedSwaggerSpec.go was likely to be different on each run of the tool even if the api being analyzed did not contain material changes. Annoying if the generated file is in source control. Loop through declarations is now alpha-sorted by map key.<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"go/ast"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/RobotsAndPencils/go-swaggerLite/markup"
	"github.com/RobotsAndPencils/go-swaggerLite/parser"
)

const (
	AVAILABLE_FORMATS = "go|markdown"
)

var apiPackage = flag.String("apiPackage", "", "The package that implements the API controllers, relative to $GOPATH/src")
var mainApiFile = flag.String("mainApiFile", "", "The file that contains the general API annotations, relative to $GOPATH/src")
var basePath = flag.String("basePath", "", "Web service base path")
var outputFormat = flag.String("format", "go", "Output format type for the generated files: "+AVAILABLE_FORMATS)
var output = flag.String("output", "generatedSwaggerSpec.go", "The opitonal name of the output file to be generated")
var generatedPackage = flag.String("package", "main", "The opitonal package name of the output file to be generated")

var generatedFileTemplate = `package {{generagedPackage}}
//This file is generated automatically. Do not edit it manually.

import (
	"net/http"
	"strings"
)

func SwaggerApiHandler(prefix string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		resource := strings.TrimPrefix(r.URL.Path, prefix)
		resource = strings.Trim(resource, "/")

		if r.Method == "OPTIONS" {
			w.Header().Set("Access-Control-Allow-Origin", "*")
			w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
			w.Header().Set("Access-Control-Allow-Headers", "accept, authorization, content-type")
			w.Header().Set("Access-Control-Max-Age", "1800")
			w.WriteHeader(204)
			return
		}

		w.Header().Set("Access-Control-Allow-Origin", "*")

		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET")

		if resource == "" {
			w.Write([]byte(swaggerResourceListing))
			return
		}

		if json, ok := swaggerApiDescriptions[resource]; ok {
			w.Write([]byte(json))
		} else {
			w.WriteHeader(http.StatusNotFound)
		}
	}
}

var swaggerResourceListing = {{resourceListing}}
var swaggerApiDescriptions = {{apiDescriptions}}
`

// It must return true if funcDeclaration is controller. We will try to parse only comments before controllers
// Stubbed out for now
func IsController(funcDeclaration *ast.FuncDecl) bool {
	return true
}

func generateSwaggerDocs(parser *parser.Parser) {
	fd, err := os.Create(path.Join("./", *output))
	if err != nil {
		log.Fatalf("Can not create document file: %v\n", err)
	}
	defer fd.Close()

	var apiDescriptions bytes.Buffer
	for _, apiKey := range sortedApiDeclarationKeys(parser.TopLevelApis) {
		apiDescriptions.WriteString("\"" + apiKey + "\":")

		apiDescriptions.WriteString("`")
		json, err := json.MarshalIndent(parser.TopLevelApis[apiKey], "", "    ")
		if err != nil {
			log.Fatalf("Can not serialise []ApiDescription to JSON: %v\n", err)
		}
		apiDescriptions.Write(json)
		apiDescriptions.WriteString("`,")
	}

	doc := strings.Replace(generatedFileTemplate, "{{resourceListing}}", "`"+string(getResourceListingJson(parser.Listing))+"`", -1)
	doc = strings.Replace(doc, "{{apiDescriptions}}", "map[string]string{"+apiDescriptions.String()+"}", -1)
	doc = strings.Replace(doc, "{{generagedPackage}}", *generatedPackage, -1)

	fd.WriteString(doc)
}

func InitParser() *parser.Parser {
	parser := parser.NewParser()

	parser.BasePath = *basePath
	parser.IsController = IsController

	parser.TypesImplementingMarshalInterface["NullString"] = "string"
	parser.TypesImplementingMarshalInterface["NullInt64"] = "int"
	parser.TypesImplementingMarshalInterface["NullFloat64"] = "float"
	parser.TypesImplementingMarshalInterface["NullBool"] = "bool"

	return parser
}

func main() {
	flag.Parse()

	if *mainApiFile == "" {
		*mainApiFile = *apiPackage + "/main.go"
	}
	if *apiPackage == "" {
		flag.PrintDefaults()
		return
	}

	parser := InitParser()
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		log.Fatalf("Please, set $GOPATH environment variable\n")
	}

	log.Println("Start parsing")
	gopaths := filepath.SplitList(gopath)
	var err error
	var errs string
	for _, gop := range gopaths {
		err = parser.ParseGeneralAPIInfo(path.Join(gop, "src", *mainApiFile))
		if err != nil {
			errs += fmt.Sprintf("    %s\n", err)
		} else {
			break
		}
	}
	if err != nil {
		log.Fatalf("Error locating main API File:\n%s", errs)
	}
	parser.ParseApi(*apiPackage)
	log.Println("Finish parsing")

	format := strings.ToLower(*outputFormat)
	switch format {
	case "go":
		generateSwaggerDocs(parser)
		log.Println("Doc file generated")
	case "markdown":
		markup.GenerateMarkup(parser, new(markup.MarkupMarkDown), output, ".md")
		log.Println("MarkDown file generated")
	default:
		log.Fatalf("Invalid -format specified. Must be one of %v.", AVAILABLE_FORMATS)
	}

}

func getResourceListingJson(listing *parser.ResourceListing) []byte {
	json, err := json.MarshalIndent(listing, "", "    ")
	if err != nil {
		log.Fatalf("Can not serialise ResourceListing to JSON: %v\n", err)
	}
	return json
}

// returns sorted map keys, used for looping items in the map
func sortedApiDeclarationKeys(m map[string]*parser.ApiDeclaration) []string {
	keys := make([]string, len(m))
	i := 0
	for key, _ := range m {
		keys[i] = key
		i++
	}
	sort.Strings(keys)
	return keys
}
<|endoftext|>


<commit_before>package decomp

import (
	"errors"
	"fmt"

	"github.com/go-math/linal/lapack"
	"github.com/go-math/linal/matrix"
)

// SymEig performs the eigendecomposition assuming that the matrix is
// symmetric:
//
//     A = Q * diag(lambda) * transpose(Q)
//
// where
//
//     A is a symmetric m-by-m matrix,
//     Q is an orthogonal m-by-m matrix of the eigenvectors of A, and
//     lambda is an m-element vector of the eigenvalues of A.
//
// https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix#Real_symmetric_matrices
func SymEig(A *matrix.Matrix) (Q *matrix.Matrix, lambda *matrix.Matrix, err error) {
	if !A.IsSquare() {
		return nil, nil, errors.New("the matrix should be square")
	}

	m := A.Rows

	// TODO: Only the upper triangular matrix is actually needed; however,
	// copying only that part might not be optimal for performance. Check!
	Q = A.Copy()

	lambda = matrix.Zero(m, 1)

	// The size of the temporary array should have at least 3*m-1.
	temp := make([]float64, 4*m)
	flag := 0

	lapack.DSYEV('N', 'U', int(m), Q.Data, int(m), lambda.Data, temp, len(temp), &flag)

	if flag != 0 {
		return nil, nil, fmt.Errorf("LAPACK failed with code %v", flag)
	}

	return Q, lambda, nil
}
<commit_msg>Fixed a typo in eig; green now<commit_after>package decomp

import (
	"errors"
	"fmt"

	"github.com/go-math/linal/lapack"
	"github.com/go-math/linal/matrix"
)

// SymEig performs the eigendecomposition assuming that the matrix is
// symmetric:
//
//     A = Q * diag(lambda) * transpose(Q)
//
// where
//
//     A is a symmetric m-by-m matrix,
//     Q is an orthogonal m-by-m matrix of the eigenvectors of A, and
//     lambda is an m-element vector of the eigenvalues of A.
//
// https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix#Real_symmetric_matrices
func SymEig(A *matrix.Matrix) (Q *matrix.Matrix, lambda *matrix.Matrix, err error) {
	if !A.IsSquare() {
		return nil, nil, errors.New("the matrix should be square")
	}

	m := A.Rows

	// TODO: Only the upper triangular matrix is actually needed; however,
	// copying only that part might not be optimal for performance. Check!
	Q = A.Copy()

	lambda = matrix.Zero(m, 1)

	// The size of the temporary array should have at least 3*m-1.
	temp := make([]float64, 4*m)
	flag := 0

	lapack.DSYEV('V', 'U', int(m), Q.Data, int(m), lambda.Data, temp, len(temp), &flag)

	if flag != 0 {
		return nil, nil, fmt.Errorf("LAPACK failed with code %v", flag)
	}

	return Q, lambda, nil
}
<|endoftext|>


<commit_before>package response_agent

import (
	"bytes"
	"net"
	"testing"

	"github.com/mark-rushakoff/go_tftpd/safe_packets"
	"github.com/mark-rushakoff/go_tftpd/test_helpers"
)

func TestNewResponseAgent(t *testing.T) {
	agent := NewResponseAgent(nil, nil)
	if agent == nil {
		t.Errorf("Unable to create agent")
	}
}

func TestAckSerializes(t *testing.T) {
	expectedPacketOut := []byte{0, 4, 4, 210}
	agent, conn, addr := buildAgentThatWrites(expectedPacketOut)
	ack := safe_packets.NewSafeAck(1234)
	agent.SendAck(ack)

	lastPacketOut, lastAddr, ok := conn.LastPacketOut()
	if !ok {
		t.Errorf("Expected a packet to be sent but no packets were sent")
	}

	if addr != lastAddr {
		t.Errorf("Expected agent to send to addr %v, but sent to %v", addr, lastAddr)
	}

	if !bytes.Equal(expectedPacketOut, lastPacketOut) {
		t.Errorf("Expected outgoing packet %v, received %v", expectedPacketOut, lastPacketOut)
	}
}

func TestErrorSerializes(t *testing.T) {
	// opcode 5, error code 1, string "File not found"
	expectedPacketOut := []byte{0, 5, 0, 1, 0x46, 0x69, 0x6c, 0x65, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0}
	agent, conn, addr := buildAgentThatWrites(expectedPacketOut)
	errorPacket := safe_packets.NewFileNotFoundError()
	agent.SendErrorPacket(errorPacket)

	lastPacketOut, lastAddr, ok := conn.LastPacketOut()
	if !ok {
		t.Errorf("Expected a packet to be sent but no packets were sent")
	}

	if addr != lastAddr {
		t.Errorf("Expected agent to send to addr %v, but sent to %v", addr, lastAddr)
	}

	if !bytes.Equal(expectedPacketOut, lastPacketOut) {
		t.Errorf("Expected outgoing packet %v, received %v", expectedPacketOut, lastPacketOut)
	}
}

func TestDataSerializes(t *testing.T) {
	// opcode 3, block number 1234, string "foo"
	expectedPacketOut := []byte{0, 3, 4, 210, 102, 111, 111}
	agent, conn, addr := buildAgentThatWrites(expectedPacketOut)
	data := safe_packets.NewSafeData(1234, []byte("foo"))
	agent.SendData(data)

	lastPacketOut, lastAddr, ok := conn.LastPacketOut()
	if !ok {
		t.Errorf("Expected a packet to be sent but no packets were sent")
	}

	if addr != lastAddr {
		t.Errorf("Expected agent to send to addr %v, but sent to %v", addr, lastAddr)
	}

	if !bytes.Equal(expectedPacketOut, lastPacketOut) {
		t.Errorf("Expected outgoing packet %v, received %v", expectedPacketOut, lastPacketOut)
	}
}

func buildAgentThatWrites(b []byte) (agent *ResponseAgent, conn *test_helpers.MockPacketConn, addr net.Addr) {
	conn = &test_helpers.MockPacketConn{
		WriteToFunc: func(b []byte, a net.Addr) (int, error) {
			return len(b), nil
		},
	}
	addr = &test_helpers.MockAddr{}
	agent = NewResponseAgent(conn, addr)

	return
}
<commit_msg>Fix test<commit_after>package response_agent

import (
	"bytes"
	"net"
	"testing"

	"github.com/mark-rushakoff/go_tftpd/safe_packets"
	"github.com/mark-rushakoff/go_tftpd/test_helpers"
)

func TestNewResponseAgent(t *testing.T) {
	agent := NewResponseAgent(nil, nil)
	if agent == nil {
		t.Errorf("Unable to create agent")
	}
}

func TestAckSerializes(t *testing.T) {
	expectedPacketOut := []byte{0, 4, 4, 210}
	agent, conn, addr := buildAgentThatWrites(expectedPacketOut)
	ack := safe_packets.NewSafeAck(1234)
	agent.SendAck(ack)

	lastPacketOut, lastAddr, ok := conn.LastPacketOut()
	if !ok {
		t.Errorf("Expected a packet to be sent but no packets were sent")
	}

	if addr != lastAddr {
		t.Errorf("Expected agent to send to addr %v, but sent to %v", addr, lastAddr)
	}

	if !bytes.Equal(expectedPacketOut, lastPacketOut) {
		t.Errorf("Expected outgoing packet %v, received %v", expectedPacketOut, lastPacketOut)
	}
}

func TestErrorSerializes(t *testing.T) {
	// opcode 5, error code 1, string "File not found"
	expectedPacketOut := []byte{0, 5, 0, 1, 0x46, 0x69, 0x6c, 0x65, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0}
	agent, conn, addr := buildAgentThatWrites(expectedPacketOut)
	errorPacket := safe_packets.NewFileNotFoundError()
	agent.SendError(errorPacket)

	lastPacketOut, lastAddr, ok := conn.LastPacketOut()
	if !ok {
		t.Errorf("Expected a packet to be sent but no packets were sent")
	}

	if addr != lastAddr {
		t.Errorf("Expected agent to send to addr %v, but sent to %v", addr, lastAddr)
	}

	if !bytes.Equal(expectedPacketOut, lastPacketOut) {
		t.Errorf("Expected outgoing packet %v, received %v", expectedPacketOut, lastPacketOut)
	}
}

func TestDataSerializes(t *testing.T) {
	// opcode 3, block number 1234, string "foo"
	expectedPacketOut := []byte{0, 3, 4, 210, 102, 111, 111}
	agent, conn, addr := buildAgentThatWrites(expectedPacketOut)
	data := safe_packets.NewSafeData(1234, []byte("foo"))
	agent.SendData(data)

	lastPacketOut, lastAddr, ok := conn.LastPacketOut()
	if !ok {
		t.Errorf("Expected a packet to be sent but no packets were sent")
	}

	if addr != lastAddr {
		t.Errorf("Expected agent to send to addr %v, but sent to %v", addr, lastAddr)
	}

	if !bytes.Equal(expectedPacketOut, lastPacketOut) {
		t.Errorf("Expected outgoing packet %v, received %v", expectedPacketOut, lastPacketOut)
	}
}

func buildAgentThatWrites(b []byte) (agent *ResponseAgent, conn *test_helpers.MockPacketConn, addr net.Addr) {
	conn = &test_helpers.MockPacketConn{
		WriteToFunc: func(b []byte, a net.Addr) (int, error) {
			return len(b), nil
		},
	}
	addr = &test_helpers.MockAddr{}
	agent = NewResponseAgent(conn, addr)

	return
}
<|endoftext|>


<commit_before>package nail

import (
	"github.com/antihax/evedata/internal/datapackages"

	"github.com/antihax/evedata/internal/gobcoder"
	nsq "github.com/nsqio/go-nsq"
)

func init() {
	AddHandler("structure", func(s *Nail, consumer *nsq.Consumer) {
		consumer.AddHandler(s.wait(nsq.HandlerFunc(s.structureHandler)))
	})
}

func (s *Nail) structureHandler(message *nsq.Message) error {
	b := datapackages.Structure{}
	err := gobcoder.GobDecoder(message.Body, &b)
	if err != nil {
		return err
	}

	// Push into the denormalized table. This table is volatile.
	err = s.doSQL(`INSERT INTO staStations
		(stationID, solarSystemID, corporationID, stationName, x, y, z, constellationID, regionID)
		VALUES(?,?,?,?,?,?,?,evedata.constellationIDBySolarSystem(solarSystemID),evedata.regionIDBySolarSystem(solarSystemID))
		ON DUPLICATE KEY UPDATE stationName=VALUES(stationName),solarSystemID=VALUES(solarSystemID),corporationID=VALUES(corporationID),
		x=VALUES(x),y=VALUES(y),z=VALUES(z),constellationID=evedata.constellationIDBySolarSystem(VALUES(solarSystemID)),regionID=evedata.regionIDBySolarSystem(VALUES(solarSystemID));`,
		b.StructureID, b.Structure.SolarSystemId, b.Structure.OwnerId, b.Structure.Name, b.Structure.Position.X, b.Structure.Position.Y, b.Structure.Position.Z)
	if err != nil {
		return err
	}

	// Insert into our table for tracking.
	err = s.doSQL(`INSERT INTO evedata.structures
		(stationID, solarSystemID, stationName, x, y, z, ownerID, typeID, updated)
		VALUES(?,?,?,?,?,?,?,?, UTC_TIMESTAMP())
		ON DUPLICATE KEY UPDATE stationName=VALUES(stationName),solarSystemID=VALUES(solarSystemID),ownerID=VALUES(ownerID),typeID=VALUES(typeID),
		x=VALUES(x),y=VALUES(y),z=VALUES(z),updated=UTC_TIMESTAMP();`,
		b.StructureID, b.Structure.SolarSystemId, b.Structure.Name,
		b.Structure.Position.X, b.Structure.Position.Y, b.Structure.Position.Z,
		b.Structure.OwnerId, b.Structure.TypeId)

	return err
}
<commit_msg>tick updated<commit_after>package nail

import (
	"github.com/antihax/evedata/internal/datapackages"

	"github.com/antihax/evedata/internal/gobcoder"
	nsq "github.com/nsqio/go-nsq"
)

func init() {
	AddHandler("structure", func(s *Nail, consumer *nsq.Consumer) {
		consumer.AddConcurrentHandlers(s.wait(nsq.HandlerFunc(s.structureHandler)), 10)
	})
}

func (s *Nail) structureHandler(message *nsq.Message) error {
	b := datapackages.Structure{}
	err := gobcoder.GobDecoder(message.Body, &b)
	if err != nil {
		return err
	}

	// Push into the denormalized table. This table is volatile.
	err = s.doSQL(`INSERT INTO staStations
		(stationID, solarSystemID, corporationID, stationName, x, y, z, constellationID, regionID)
		VALUES(?,?,?,?,?,?,?,evedata.constellationIDBySolarSystem(solarSystemID),evedata.regionIDBySolarSystem(solarSystemID))
		ON DUPLICATE KEY UPDATE stationName=VALUES(stationName),solarSystemID=VALUES(solarSystemID),corporationID=VALUES(corporationID),
		x=VALUES(x),y=VALUES(y),z=VALUES(z),constellationID=evedata.constellationIDBySolarSystem(VALUES(solarSystemID)),regionID=evedata.regionIDBySolarSystem(VALUES(solarSystemID));`,
		b.StructureID, b.Structure.SolarSystemId, b.Structure.OwnerId, b.Structure.Name, b.Structure.Position.X, b.Structure.Position.Y, b.Structure.Position.Z)
	if err != nil {
		return err
	}

	// Insert into our table for tracking.
	err = s.doSQL(`INSERT INTO evedata.structures
		(stationID, solarSystemID, stationName, x, y, z, ownerID, typeID, updated)
		VALUES(?,?,?,?,?,?,?,?, UTC_TIMESTAMP())
		ON DUPLICATE KEY UPDATE stationName=VALUES(stationName),solarSystemID=VALUES(solarSystemID),ownerID=VALUES(ownerID),typeID=VALUES(typeID),
		x=VALUES(x),y=VALUES(y),z=VALUES(z),updated=VALUES(updated);`,
		b.StructureID, b.Structure.SolarSystemId, b.Structure.Name,
		b.Structure.Position.X, b.Structure.Position.Y, b.Structure.Position.Z,
		b.Structure.OwnerId, b.Structure.TypeId)

	return err
}
<|endoftext|>