<commit_before>//
// Copyright 2017, Sander van Harmelen, Michael Lihs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package gitlab

import (
	"fmt"
	"net/url"
)

// ProtectedBranchesService handles communication with the protected branch
// related methods of the GitLab API.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protected-branches-api
type ProtectedBranchesService struct {
	client *Client
}

// BranchAccessDescription represents the access description for a protected
// branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protected-branches-api
type BranchAccessDescription struct {
	AccessLevel            *AccessLevelValue `json:"access_level,omitempty"`
	AccessLevelDescription string            `json:"access_level_description"`
	GroupId                *int              `json:"group_id,omitempty"`
	UserId                 *int              `json:"user_id,omitempty"`
}

// ProtectedBranch represents a protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
type ProtectedBranch struct {
	ID                        int                        `json:"id"`
	Name                      string                     `json:"name"`
	PushAccessLevels          []*BranchAccessDescription `json:"push_access_levels"`
	MergeAccessLevels         []*BranchAccessDescription `json:"merge_access_levels"`
	UnprotectAccessLevels     []*BranchAccessDescription `json:"unprotect_access_levels"`
	CodeOwnerApprovalRequired bool                       `json:"code_owner_approval_required"`
}

// ListProtectedBranchesOptions represents the available ListProtectedBranches()
// options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
type ListProtectedBranchesOptions ListOptions

// ListProtectedBranches gets a list of protected branches from a project.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
func (s *ProtectedBranchesService) ListProtectedBranches(pid interface{}, opt *ListProtectedBranchesOptions, options ...RequestOptionFunc) ([]*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches", pathEscape(project))

	req, err := s.client.NewRequest("GET", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	var p []*ProtectedBranch
	resp, err := s.client.Do(req, &p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// GetProtectedBranch gets a single protected branch or wildcard protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#get-a-single-protected-branch-or-wildcard-protected-branch
func (s *ProtectedBranchesService) GetProtectedBranch(pid interface{}, branch string, options ...RequestOptionFunc) (*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest("GET", u, nil, options)
	if err != nil {
		return nil, nil, err
	}

	p := new(ProtectedBranch)
	resp, err := s.client.Do(req, p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// ProtectRepositoryBranchesOptions represents the available
// ProtectRepositoryBranches() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protect-repository-branches
type ProtectRepositoryBranchesOptions struct {
	Name                      *string                    `url:"name,omitempty" json:"name,omitempty"`
	PushAccessLevel           *AccessLevelValue          `url:"push_access_level,omitempty" json:"push_access_level,omitempty"`
	MergeAccessLevel          *AccessLevelValue          `url:"merge_access_level,omitempty" json:"merge_access_level,omitempty"`
	UnprotectAccessLevel      *AccessLevelValue          `url:"unprotect_access_level,omitempty" json:"unprotect_access_level,omitempty"`
	AllowedToMerge            *[]ProtectBranchPermission `url:"allowed_to_merge,omitempty" json:"allowed_to_merge,omitempty"`
	AllowedToPush             *[]ProtectBranchPermission `url:"allowed_to_push,omitempty" json:"allowed_to_push,omitempty"`
	AllowedToUnprotect        *[]ProtectBranchPermission `url:"allowed_to_unprotect,omitempty" json:"allowed_to_unprotect,omitempty"`
	CodeOwnerApprovalRequired *bool                      `url:"code_owner_approval_required,omitempty" json:"code_owner_approval_required,omitempty"`
}

// ProtectBranchPermission represents a user_id, group_id,
// or access_level to grant access to.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#example-with-user--group-level-access-starter
type ProtectBranchPermission struct {
	UserId      *int              `url:"user_id,omitempty" json:"user_id,omitempty"`
	GroupId     *int              `url:"group_id,omitempty" json:"group_id,omitempty"`
	AccessLevel *AccessLevelValue `url:"access_level,omitempty" json:"access_level,omitempty"`
}

// ProtectRepositoryBranches protects a single repository branch or several
// project repository branches using a wildcard protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protect-repository-branches
func (s *ProtectedBranchesService) ProtectRepositoryBranches(pid interface{}, opt *ProtectRepositoryBranchesOptions, options ...RequestOptionFunc) (*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches", pathEscape(project))

	req, err := s.client.NewRequest("POST", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	p := new(ProtectedBranch)
	resp, err := s.client.Do(req, p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// UnprotectRepositoryBranches unprotects the given protected branch or wildcard
// protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#unprotect-repository-branches
func (s *ProtectedBranchesService) UnprotectRepositoryBranches(pid interface{}, branch string, options ...RequestOptionFunc) (*Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest("DELETE", u, nil, options)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}

// RequireCodeOwnerApprovalsOptions represents the available
// RequireCodeOwnerApprovals() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ee/api/protected_branches.html#require-code-owner-approvals-for-a-single-branch
type RequireCodeOwnerApprovalsOptions struct {
	CodeOwnerApprovalRequired *bool `url:"code_owner_approval_required,omitempty" json:"code_owner_approval_required,omitempty"`
}

// RequireCodeOwnerApprovals updates the code owner approval.
//
// Gitlab API docs:
// https://docs.gitlab.com/ee/api/protected_branches.html#require-code-owner-approvals-for-a-single-branch
func (s *ProtectedBranchesService) RequireCodeOwnerApprovals(pid interface{}, branch string, opt *RequireCodeOwnerApprovalsOptions, options ...RequestOptionFunc) (*Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest("PATCH", u, opt, options)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}
<commit_msg>Making tweaks per reviewer feedback.<commit_after>//
// Copyright 2017, Sander van Harmelen, Michael Lihs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package gitlab

import (
	"fmt"
	"net/url"
)

// ProtectedBranchesService handles communication with the protected branch
// related methods of the GitLab API.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protected-branches-api
type ProtectedBranchesService struct {
	client *Client
}

// BranchAccessDescription represents the access description for a protected
// branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protected-branches-api
type BranchAccessDescription struct {
	AccessLevel            AccessLevelValue `json:"access_level"`
	UserID                 int              `json:"user_id,omitempty"`
	GroupID                int              `json:"group_id,omitempty"`
	AccessLevelDescription string           `json:"access_level_description"`
}

// ProtectedBranch represents a protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
type ProtectedBranch struct {
	ID                        int                        `json:"id"`
	Name                      string                     `json:"name"`
	PushAccessLevels          []*BranchAccessDescription `json:"push_access_levels"`
	MergeAccessLevels         []*BranchAccessDescription `json:"merge_access_levels"`
	UnprotectAccessLevels     []*BranchAccessDescription `json:"unprotect_access_levels"`
	CodeOwnerApprovalRequired bool                       `json:"code_owner_approval_required"`
}

// ListProtectedBranchesOptions represents the available ListProtectedBranches()
// options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
type ListProtectedBranchesOptions ListOptions

// ListProtectedBranches gets a list of protected branches from a project.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#list-protected-branches
func (s *ProtectedBranchesService) ListProtectedBranches(pid interface{}, opt *ListProtectedBranchesOptions, options ...RequestOptionFunc) ([]*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches", pathEscape(project))

	req, err := s.client.NewRequest("GET", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	var p []*ProtectedBranch
	resp, err := s.client.Do(req, &p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// GetProtectedBranch gets a single protected branch or wildcard protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#get-a-single-protected-branch-or-wildcard-protected-branch
func (s *ProtectedBranchesService) GetProtectedBranch(pid interface{}, branch string, options ...RequestOptionFunc) (*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest("GET", u, nil, options)
	if err != nil {
		return nil, nil, err
	}

	p := new(ProtectedBranch)
	resp, err := s.client.Do(req, p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// ProtectRepositoryBranchesOptions represents the available
// ProtectRepositoryBranches() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protect-repository-branches
type ProtectRepositoryBranchesOptions struct {
	Name                      *string                           `url:"name,omitempty" json:"name,omitempty"`
	PushAccessLevel           *AccessLevelValue                 `url:"push_access_level,omitempty" json:"push_access_level,omitempty"`
	MergeAccessLevel          *AccessLevelValue                 `url:"merge_access_level,omitempty" json:"merge_access_level,omitempty"`
	UnprotectAccessLevel      *AccessLevelValue                 `url:"unprotect_access_level,omitempty" json:"unprotect_access_level,omitempty"`
	AllowedToPush             []*ProtectBranchPermissionOptions `url:"allowed_to_push,omitempty" json:"allowed_to_push,omitempty"`
	AllowedToMerge            []*ProtectBranchPermissionOptions `url:"allowed_to_merge,omitempty" json:"allowed_to_merge,omitempty"`
	AllowedToUnprotect        []*ProtectBranchPermissionOptions `url:"allowed_to_unprotect,omitempty" json:"allowed_to_unprotect,omitempty"`
	CodeOwnerApprovalRequired *bool                             `url:"code_owner_approval_required,omitempty" json:"code_owner_approval_required,omitempty"`
}

// ProtectBranchPermissionOptions represents a branch permission option.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protect-repository-branches
type ProtectBranchPermissionOptions struct {
	UserID      *int              `url:"user_id,omitempty" json:"user_id,omitempty"`
	GroupID     *int              `url:"group_id,omitempty" json:"group_id,omitempty"`
	AccessLevel *AccessLevelValue `url:"access_level,omitempty" json:"access_level,omitempty"`
}

// ProtectRepositoryBranches protects a single repository branch or several
// project repository branches using a wildcard protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#protect-repository-branches
func (s *ProtectedBranchesService) ProtectRepositoryBranches(pid interface{}, opt *ProtectRepositoryBranchesOptions, options ...RequestOptionFunc) (*ProtectedBranch, *Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches", pathEscape(project))

	req, err := s.client.NewRequest("POST", u, opt, options)
	if err != nil {
		return nil, nil, err
	}

	p := new(ProtectedBranch)
	resp, err := s.client.Do(req, p)
	if err != nil {
		return nil, resp, err
	}

	return p, resp, err
}

// UnprotectRepositoryBranches unprotects the given protected branch or wildcard
// protected branch.
//
// GitLab API docs:
// https://docs.gitlab.com/ce/api/protected_branches.html#unprotect-repository-branches
func (s *ProtectedBranchesService) UnprotectRepositoryBranches(pid interface{}, branch string, options ...RequestOptionFunc) (*Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest("DELETE", u, nil, options)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}

// RequireCodeOwnerApprovalsOptions represents the available
// RequireCodeOwnerApprovals() options.
//
// GitLab API docs:
// https://docs.gitlab.com/ee/api/protected_branches.html#require-code-owner-approvals-for-a-single-branch
type RequireCodeOwnerApprovalsOptions struct {
	CodeOwnerApprovalRequired *bool `url:"code_owner_approval_required,omitempty" json:"code_owner_approval_required,omitempty"`
}

// RequireCodeOwnerApprovals updates the code owner approval.
//
// Gitlab API docs:
// https://docs.gitlab.com/ee/api/protected_branches.html#require-code-owner-approvals-for-a-single-branch
func (s *ProtectedBranchesService) RequireCodeOwnerApprovals(pid interface{}, branch string, opt *RequireCodeOwnerApprovalsOptions, options ...RequestOptionFunc) (*Response, error) {
	project, err := parseID(pid)
	if err != nil {
		return nil, err
	}
	u := fmt.Sprintf("projects/%s/protected_branches/%s", pathEscape(project), url.PathEscape(branch))

	req, err := s.client.NewRequest("PATCH", u, opt, options)
	if err != nil {
		return nil, err
	}

	return s.client.Do(req, nil)
}
<|endoftext|>


<commit_before>package render

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestRegisterDecoder(t *testing.T) {
	assert.NotNil(t, RegisterDecoder("too long", nil))
	short := "s"
	assert.NotNil(t, RegisterDecoder(short, nil))
	assert.NotNil(t, RegisterDecoder(".png", nil))
	assert.Nil(t, RegisterDecoder(".new", nil))
}
<commit_msg>Update decoder tests for more lenient extension registration<commit_after>package render

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestRegisterDecoder(t *testing.T) {
	assert.NotNil(t, RegisterDecoder(".png", nil))
	assert.Nil(t, RegisterDecoder(".new", nil))
}
<|endoftext|>


<commit_before>package proxmox

import (
	"encoding/json"
	"fmt"
	"io"
	"strconv"
	"strings"
)

// LXC options for the Proxmox API
type ConfigLxc struct {
	Ostemplate         string      `json:"ostemplate"`
	Arch               string      `json:"arch"`
	BWLimit            int         `json:"bwlimit,omitempty"`
	CMode              string      `json:"cmode"`
	Console            bool        `json:"console"`
	Cores              int         `json:"cores,omitempty"`
	CPULimit           int         `json:"cpulimit"`
	CPUUnits           int         `json:"cpuunits"`
	Description        string      `json:"description,omitempty"`
	Features           QemuDevice  `json:"features,omitempty"`
	Force              bool        `json:"force,omitempty"`
	Hookscript         string      `json:"hookscript,omitempty"`
	Hostname           string      `json:"hostname,omitempty"`
	IgnoreUnpackErrors bool        `json:"ignore-unpack-errors,omitempty"`
	Lock               string      `json:"lock,omitempty"`
	Memory             int         `json:"memory"`
	Mountpoints        QemuDevices `json:"mountpoints,omitempty"`
	Nameserver         string      `json:"nameserver,omitempty"`
	Networks           QemuDevices `json:"networks,omitempty"`
	OnBoot             bool        `json:"onboot"`
	OsType             string      `json:"ostype,omitempty"`
	Password           string      `json:"password,omitempty"`
	Pool               string      `json:"pool,omitempty"`
	Protection         bool        `json:"protection"`
	Restore            bool        `json:"restore,omitempty"`
	RootFs             QemuDevice  `json:"rootfs,omitempty"`
	SearchDomain       string      `json:"searchdomain,omitempty"`
	SSHPublicKeys      string      `json:"ssh-public-keys,omitempty"`
	Start              bool        `json:"start"`
	Startup            string      `json:"startup,omitempty"`
	Storage            string      `json:"storage"`
	Swap               int         `json:"swap"`
	Template           bool        `json:"template,omitempty"`
	Tty                int         `json:"tty"`
	Unique             bool        `json:"unique,omitempty"`
	Unprivileged       bool        `json:"unprivileged"`
	Tags               string      `json:"tags"`
	Unused             []string    `json:"unused,omitempty"`
}

func NewConfigLxc() ConfigLxc {
	return ConfigLxc{
		Arch:         "amd64",
		CMode:        "tty",
		Console:      true,
		CPULimit:     0,
		CPUUnits:     1024,
		Memory:       512,
		OnBoot:       false,
		Protection:   false,
		Start:        false,
		Storage:      "local",
		Swap:         512,
		Template:     false,
		Tty:          2,
		Unprivileged: false,
	}
}

func NewConfigLxcFromJson(io io.Reader) (config ConfigLxc, err error) {
	config = NewConfigLxc()
	err = json.NewDecoder(io).Decode(config)
	return config, err
}

func NewConfigLxcFromApi(vmr *VmRef, client *Client) (config *ConfigLxc, err error) {
	// prepare json map to receive the information from the api
	var lxcConfig map[string]interface{}
	lxcConfig, err = client.GetVmConfig(vmr)
	if err != nil {
		return nil, err
	}

	// prepare a new lxc config to store and return\
	// the information from api
	newConfig := NewConfigLxc()
	config = &newConfig

	arch := ""
	if _, isSet := lxcConfig["arch"]; isSet {
		arch = lxcConfig["arch"].(string)
	}
	cmode := ""
	if _, isSet := lxcConfig["cmode"]; isSet {
		cmode = lxcConfig["cmode"].(string)
	}
	console := true
	if _, isSet := lxcConfig["console"]; isSet {
		console = Itob(int(lxcConfig["console"].(float64)))
	}
	cores := 0
	if _, isSet := lxcConfig["cores"]; isSet {
		cores = int(lxcConfig["cores"].(float64))
	}
	cpulimit := 0
	if _, isSet := lxcConfig["cpulimit"]; isSet {
		cpulimit, _ = strconv.Atoi(lxcConfig["cpulimit"].(string))
	}
	cpuunits := 1024
	if _, isSet := lxcConfig["cpuunits"]; isSet {
		cpuunits = int(lxcConfig["cpuunits"].(float64))
	}
	description := ""
	if _, isSet := lxcConfig["description"]; isSet {
		description = lxcConfig["description"].(string)
	}

	// add features, if any
	if features, isSet := lxcConfig["features"]; isSet {
		featureList := strings.Split(features.(string), ",")

		// create new device map to store features
		featureMap := QemuDevice{}
		// add all features to device map
		featureMap.readDeviceConfig(featureList)
		// prepare empty feature map
		if config.Features == nil {
			config.Features = QemuDevice{}
		}
		// and device config to networks
		if len(featureMap) > 0 {
			config.Features = featureMap
		}
	}

	hookscript := ""
	if _, isSet := lxcConfig["hookscript"]; isSet {
		hookscript = lxcConfig["hookscript"].(string)
	}
	hostname := ""
	if _, isSet := lxcConfig["hostname"]; isSet {
		hostname = lxcConfig["hostname"].(string)
	}
	lock := ""
	if _, isSet := lxcConfig["lock"]; isSet {
		lock = lxcConfig["lock"].(string)
	}
	memory := 512
	if _, isSet := lxcConfig["memory"]; isSet {
		memory = int(lxcConfig["memory"].(float64))
	}

	// add rootfs
	rootfs := QemuDevice{}
	if rootfsStr, isSet := lxcConfig["rootfs"]; isSet {
		rootfs = ParsePMConf(rootfsStr.(string), "volume")
	}

	// add mountpoints
	mpNames := []string{}

	for k, _ := range lxcConfig {
		if mpName := rxMpName.FindStringSubmatch(k); len(mpName) > 0 {
			mpNames = append(mpNames, mpName[0])
		}
	}

	for _, mpName := range mpNames {
		mpConfStr := lxcConfig[mpName].(string)
		mpConfMap := ParseLxcDisk(mpConfStr)

		// add mp id
		id := rxDeviceID.FindStringSubmatch(mpName)
		mpID, _ := strconv.Atoi(id[0])
		mpConfMap["slot"] = mpID

		// prepare empty mountpoint map
		if config.Mountpoints == nil {
			config.Mountpoints = QemuDevices{}
		}
		// and device config to mountpoints
		if len(mpConfMap) > 0 {
			config.Mountpoints[mpID] = mpConfMap
		}
	}

	nameserver := ""
	if _, isSet := lxcConfig["nameserver"]; isSet {
		nameserver = lxcConfig["nameserver"].(string)
	}

	// add networks
	nicNames := []string{}

	for k, _ := range lxcConfig {
		if nicName := rxNicName.FindStringSubmatch(k); len(nicName) > 0 {
			nicNames = append(nicNames, nicName[0])
		}
	}

	for _, nicName := range nicNames {
		nicConfStr := lxcConfig[nicName]
		nicConfList := strings.Split(nicConfStr.(string), ",")

		id := rxDeviceID.FindStringSubmatch(nicName)
		nicID, _ := strconv.Atoi(id[0])
		// add nic id
		nicConfMap := QemuDevice{
			"id": nicID,
		}
		// add rest of device config
		nicConfMap.readDeviceConfig(nicConfList)

		if nicConfMap["firewall"] == 1 {
			nicConfMap["firewall"] = true
		} else if nicConfMap["firewall"] == 0 {
			nicConfMap["firewall"] = false
		}

		// prepare empty network map
		if config.Networks == nil {
			config.Networks = QemuDevices{}
		}
		// and device config to networks
		if len(nicConfMap) > 0 {
			config.Networks[nicID] = nicConfMap
		}
	}

	onboot := false
	if _, isSet := lxcConfig["onboot"]; isSet {
		onboot = Itob(int(lxcConfig["onboot"].(float64)))
	}
	ostype := ""
	if _, isSet := lxcConfig["ostype"]; isSet {
		ostype = lxcConfig["ostype"].(string)
	}
	protection := false
	if _, isSet := lxcConfig["protection"]; isSet {
		protection = Itob(int(lxcConfig["protection"].(float64)))
	}
	searchdomain := ""
	if _, isSet := lxcConfig["searchdomain"]; isSet {
		searchdomain = lxcConfig["searchdomain"].(string)
	}
	startup := ""
	if _, isSet := lxcConfig["startup"]; isSet {
		startup = lxcConfig["startup"].(string)
	}
	swap := 512
	if _, isSet := lxcConfig["swap"]; isSet {
		swap = int(lxcConfig["swap"].(float64))
	}
	template := false
	if _, isSet := lxcConfig["template"]; isSet {
		template = Itob(int(lxcConfig["template"].(float64)))
	}
	tty := 2
	if _, isSet := lxcConfig["tty"]; isSet {
		tty = int(lxcConfig["tty"].(float64))
	}
	unprivileged := false
	if _, isset := lxcConfig["unprivileged"]; isset {
		unprivileged = Itob(int(lxcConfig["unprivileged"].(float64)))
	}
	tags := ""
	if _, isSet := lxcConfig["tags"]; isSet {
		tags = lxcConfig["tags"].(string)
	}
	var unused []string
	if _, isset := lxcConfig["unused"]; isset {
		unused = lxcConfig["unused"].([]string)
	}

	config.Arch = arch
	config.CMode = cmode
	config.Console = console
	config.Cores = cores
	config.CPULimit = cpulimit
	config.CPUUnits = cpuunits
	config.Description = description
	config.OnBoot = onboot
	config.Hookscript = hookscript
	config.Hostname = hostname
	config.Lock = lock
	config.Memory = memory
	config.Nameserver = nameserver
	config.OnBoot = onboot
	config.OsType = ostype
	config.Protection = protection
	config.RootFs = rootfs
	config.SearchDomain = searchdomain
	config.Startup = startup
	config.Swap = swap
	config.Template = template
	config.Tty = tty
	config.Unprivileged = unprivileged
	config.Unused = unused
	config.Tags = tags

	return
}

// create LXC container using the Proxmox API
func (config ConfigLxc) CreateLxc(vmr *VmRef, client *Client) (err error) {
	vmr.SetVmType("lxc")
	paramMap := config.mapToAPIParams()

	// amend vmid
	paramMap["vmid"] = vmr.vmId

	exitStatus, err := client.CreateLxcContainer(vmr.node, paramMap)
	if err != nil {
		params, _ := json.Marshal(&paramMap)
		return fmt.Errorf("Error creating LXC container: %v, error status: %s (params: %v)", err, exitStatus, string(params))
	}
	return
}

func (config ConfigLxc) UpdateConfig(vmr *VmRef, client *Client) (err error) {
	paramMap := config.mapToAPIParams()

	// delete parameters wich are not supported in updated operations
	delete(paramMap, "pool")
	delete(paramMap, "storage")
	delete(paramMap, "password")
	delete(paramMap, "ostemplate")
	delete(paramMap, "start")

	// even though it is listed as a PUT option in the API documentation
	// we remove it here because "it should not be modified manually";
	// also, error "500 unable to modify read-only option: 'unprivileged'"
	delete(paramMap, "unprivileged")

	_, err = client.SetLxcConfig(vmr, paramMap)
	return err
}

func ParseLxcDisk(diskStr string) QemuDevice {
	disk := ParsePMConf(diskStr, "volume")

	// add features, if any
	if mountoptions, isSet := disk["mountoptions"]; isSet {
		moList := strings.Split(mountoptions.(string), ";")
		moMap := map[string]bool{}
		for _, mo := range moList {
			moMap[mo] = true
		}
		disk["mountoptions"] = moMap
	}

	storageName, fileName := ParseSubConf(disk["volume"].(string), ":")
	disk["storage"] = storageName
	disk["file"] = fileName

	return disk
}

func (config ConfigLxc) mapToAPIParams() map[string]interface{} {
	// convert config to map
	params, _ := json.Marshal(&config)
	var paramMap map[string]interface{}
	json.Unmarshal(params, &paramMap)

	// build list of features
	// add features as parameter list to lxc parameters
	// this overwrites the orginal formatting with a
	// comma separated list of "key=value" pairs
	paramMap["features"] = formatDeviceParam(config.Features)

	// format rootfs params as expected
	if rootfs := config.RootFs; rootfs != nil {
		paramMap["rootfs"] = FormatDiskParam(rootfs)
	}

	// build list of mountpoints
	// this does the same as for the feature list
	// except that there can be multiple of these mountpoint sets
	// and each mountpoint set comes with a new id
	for _, mpConfMap := range config.Mountpoints {
		// add mp to lxc parameters
		mpID := mpConfMap["slot"]
		mpName := fmt.Sprintf("mp%v", mpID)
		paramMap[mpName] = FormatDiskParam(mpConfMap)
	}

	// build list of network parameters
	for nicID, nicConfMap := range config.Networks {
		// add nic to lxc parameters
		nicName := fmt.Sprintf("net%v", nicID)
		paramMap[nicName] = formatDeviceParam(nicConfMap)
	}

	// build list of unused volumes for sake of completeness,
	// even if it is not recommended to change these volumes manually
	for volID, vol := range config.Unused {
		// add volume to lxc parameters
		volName := fmt.Sprintf("unused%v", volID)
		paramMap[volName] = vol
	}

	// now that we concatenated the key value parameter
	// list for the networks, mountpoints and unused volumes,
	// remove the original keys, since the Proxmox API does
	// not know how to handle this key
	delete(paramMap, "networks")
	delete(paramMap, "mountpoints")
	delete(paramMap, "unused")

	return paramMap
}
<commit_msg>First attempt to add HA State support to container<commit_after>package proxmox

import (
	"encoding/json"
	"fmt"
	"io"
	"strconv"
	"strings"
)

// LXC options for the Proxmox API
type ConfigLxc struct {
	Ostemplate         string      `json:"ostemplate"`
	Arch               string      `json:"arch"`
	BWLimit            int         `json:"bwlimit,omitempty"`
	CMode              string      `json:"cmode"`
	Console            bool        `json:"console"`
	Cores              int         `json:"cores,omitempty"`
	CPULimit           int         `json:"cpulimit"`
	CPUUnits           int         `json:"cpuunits"`
	Description        string      `json:"description,omitempty"`
	Features           QemuDevice  `json:"features,omitempty"`
	Force              bool        `json:"force,omitempty"`
	HaState            string      `json:"hastate,omitempty"`
	Hookscript         string      `json:"hookscript,omitempty"`
	Hostname           string      `json:"hostname,omitempty"`
	IgnoreUnpackErrors bool        `json:"ignore-unpack-errors,omitempty"`
	Lock               string      `json:"lock,omitempty"`
	Memory             int         `json:"memory"`
	Mountpoints        QemuDevices `json:"mountpoints,omitempty"`
	Nameserver         string      `json:"nameserver,omitempty"`
	Networks           QemuDevices `json:"networks,omitempty"`
	OnBoot             bool        `json:"onboot"`
	OsType             string      `json:"ostype,omitempty"`
	Password           string      `json:"password,omitempty"`
	Pool               string      `json:"pool,omitempty"`
	Protection         bool        `json:"protection"`
	Restore            bool        `json:"restore,omitempty"`
	RootFs             QemuDevice  `json:"rootfs,omitempty"`
	SearchDomain       string      `json:"searchdomain,omitempty"`
	SSHPublicKeys      string      `json:"ssh-public-keys,omitempty"`
	Start              bool        `json:"start"`
	Startup            string      `json:"startup,omitempty"`
	Storage            string      `json:"storage"`
	Swap               int         `json:"swap"`
	Template           bool        `json:"template,omitempty"`
	Tty                int         `json:"tty"`
	Unique             bool        `json:"unique,omitempty"`
	Unprivileged       bool        `json:"unprivileged"`
	Tags               string      `json:"tags"`
	Unused             []string    `json:"unused,omitempty"`
}

func NewConfigLxc() ConfigLxc {
	return ConfigLxc{
		Arch:         "amd64",
		CMode:        "tty",
		Console:      true,
		CPULimit:     0,
		CPUUnits:     1024,
		Memory:       512,
		OnBoot:       false,
		Protection:   false,
		Start:        false,
		Storage:      "local",
		Swap:         512,
		Template:     false,
		Tty:          2,
		Unprivileged: false,
	}
}

func NewConfigLxcFromJson(io io.Reader) (config ConfigLxc, err error) {
	config = NewConfigLxc()
	err = json.NewDecoder(io).Decode(config)
	return config, err
}

func NewConfigLxcFromApi(vmr *VmRef, client *Client) (config *ConfigLxc, err error) {
	// prepare json map to receive the information from the api
	var lxcConfig map[string]interface{}
	lxcConfig, err = client.GetVmConfig(vmr)
	if err != nil {
		return nil, err
	}

	// prepare a new lxc config to store and return\
	// the information from api
	newConfig := NewConfigLxc()
	config = &newConfig

	arch := ""
	if _, isSet := lxcConfig["arch"]; isSet {
		arch = lxcConfig["arch"].(string)
	}
	cmode := ""
	if _, isSet := lxcConfig["cmode"]; isSet {
		cmode = lxcConfig["cmode"].(string)
	}
	console := true
	if _, isSet := lxcConfig["console"]; isSet {
		console = Itob(int(lxcConfig["console"].(float64)))
	}
	cores := 0
	if _, isSet := lxcConfig["cores"]; isSet {
		cores = int(lxcConfig["cores"].(float64))
	}
	cpulimit := 0
	if _, isSet := lxcConfig["cpulimit"]; isSet {
		cpulimit, _ = strconv.Atoi(lxcConfig["cpulimit"].(string))
	}
	cpuunits := 1024
	if _, isSet := lxcConfig["cpuunits"]; isSet {
		cpuunits = int(lxcConfig["cpuunits"].(float64))
	}
	description := ""
	if _, isSet := lxcConfig["description"]; isSet {
		description = lxcConfig["description"].(string)
	}

	// add features, if any
	if features, isSet := lxcConfig["features"]; isSet {
		featureList := strings.Split(features.(string), ",")

		// create new device map to store features
		featureMap := QemuDevice{}
		// add all features to device map
		featureMap.readDeviceConfig(featureList)
		// prepare empty feature map
		if config.Features == nil {
			config.Features = QemuDevice{}
		}
		// and device config to networks
		if len(featureMap) > 0 {
			config.Features = featureMap
		}
	}

	hastate := ""
	if _, isSet := lxcConfig["hastate"]; isSet {
		hastate = lxcConfig["hastate"].(string)
	}
	hookscript := ""
	if _, isSet := lxcConfig["hookscript"]; isSet {
		hookscript = lxcConfig["hookscript"].(string)
	}
	hostname := ""
	if _, isSet := lxcConfig["hostname"]; isSet {
		hostname = lxcConfig["hostname"].(string)
	}
	lock := ""
	if _, isSet := lxcConfig["lock"]; isSet {
		lock = lxcConfig["lock"].(string)
	}
	memory := 512
	if _, isSet := lxcConfig["memory"]; isSet {
		memory = int(lxcConfig["memory"].(float64))
	}

	// add rootfs
	rootfs := QemuDevice{}
	if rootfsStr, isSet := lxcConfig["rootfs"]; isSet {
		rootfs = ParsePMConf(rootfsStr.(string), "volume")
	}

	// add mountpoints
	mpNames := []string{}

	for k, _ := range lxcConfig {
		if mpName := rxMpName.FindStringSubmatch(k); len(mpName) > 0 {
			mpNames = append(mpNames, mpName[0])
		}
	}

	for _, mpName := range mpNames {
		mpConfStr := lxcConfig[mpName].(string)
		mpConfMap := ParseLxcDisk(mpConfStr)

		// add mp id
		id := rxDeviceID.FindStringSubmatch(mpName)
		mpID, _ := strconv.Atoi(id[0])
		mpConfMap["slot"] = mpID

		// prepare empty mountpoint map
		if config.Mountpoints == nil {
			config.Mountpoints = QemuDevices{}
		}
		// and device config to mountpoints
		if len(mpConfMap) > 0 {
			config.Mountpoints[mpID] = mpConfMap
		}
	}

	nameserver := ""
	if _, isSet := lxcConfig["nameserver"]; isSet {
		nameserver = lxcConfig["nameserver"].(string)
	}

	// add networks
	nicNames := []string{}

	for k, _ := range lxcConfig {
		if nicName := rxNicName.FindStringSubmatch(k); len(nicName) > 0 {
			nicNames = append(nicNames, nicName[0])
		}
	}

	for _, nicName := range nicNames {
		nicConfStr := lxcConfig[nicName]
		nicConfList := strings.Split(nicConfStr.(string), ",")

		id := rxDeviceID.FindStringSubmatch(nicName)
		nicID, _ := strconv.Atoi(id[0])
		// add nic id
		nicConfMap := QemuDevice{
			"id": nicID,
		}
		// add rest of device config
		nicConfMap.readDeviceConfig(nicConfList)

		if nicConfMap["firewall"] == 1 {
			nicConfMap["firewall"] = true
		} else if nicConfMap["firewall"] == 0 {
			nicConfMap["firewall"] = false
		}

		// prepare empty network map
		if config.Networks == nil {
			config.Networks = QemuDevices{}
		}
		// and device config to networks
		if len(nicConfMap) > 0 {
			config.Networks[nicID] = nicConfMap
		}
	}

	onboot := false
	if _, isSet := lxcConfig["onboot"]; isSet {
		onboot = Itob(int(lxcConfig["onboot"].(float64)))
	}
	ostype := ""
	if _, isSet := lxcConfig["ostype"]; isSet {
		ostype = lxcConfig["ostype"].(string)
	}
	protection := false
	if _, isSet := lxcConfig["protection"]; isSet {
		protection = Itob(int(lxcConfig["protection"].(float64)))
	}
	searchdomain := ""
	if _, isSet := lxcConfig["searchdomain"]; isSet {
		searchdomain = lxcConfig["searchdomain"].(string)
	}
	startup := ""
	if _, isSet := lxcConfig["startup"]; isSet {
		startup = lxcConfig["startup"].(string)
	}
	swap := 512
	if _, isSet := lxcConfig["swap"]; isSet {
		swap = int(lxcConfig["swap"].(float64))
	}
	template := false
	if _, isSet := lxcConfig["template"]; isSet {
		template = Itob(int(lxcConfig["template"].(float64)))
	}
	tty := 2
	if _, isSet := lxcConfig["tty"]; isSet {
		tty = int(lxcConfig["tty"].(float64))
	}
	unprivileged := false
	if _, isset := lxcConfig["unprivileged"]; isset {
		unprivileged = Itob(int(lxcConfig["unprivileged"].(float64)))
	}
	tags := ""
	if _, isSet := lxcConfig["tags"]; isSet {
		tags = lxcConfig["tags"].(string)
	}
	var unused []string
	if _, isset := lxcConfig["unused"]; isset {
		unused = lxcConfig["unused"].([]string)
	}

	config.Arch = arch
	config.CMode = cmode
	config.Console = console
	config.Cores = cores
	config.CPULimit = cpulimit
	config.CPUUnits = cpuunits
	config.Description = description
	config.OnBoot = onboot
	config.HaState = hastate
	config.Hookscript = hookscript
	config.Hostname = hostname
	config.Lock = lock
	config.Memory = memory
	config.Nameserver = nameserver
	config.OnBoot = onboot
	config.OsType = ostype
	config.Protection = protection
	config.RootFs = rootfs
	config.SearchDomain = searchdomain
	config.Startup = startup
	config.Swap = swap
	config.Template = template
	config.Tty = tty
	config.Unprivileged = unprivileged
	config.Unused = unused
	config.Tags = tags

	return
}

// create LXC container using the Proxmox API
func (config ConfigLxc) CreateLxc(vmr *VmRef, client *Client) (err error) {
	vmr.SetVmType("lxc")
	paramMap := config.mapToAPIParams()

	// amend vmid
	paramMap["vmid"] = vmr.vmId

	exitStatus, err := client.CreateLxcContainer(vmr.node, paramMap)
	if err != nil {
		params, _ := json.Marshal(&paramMap)
		return fmt.Errorf("Error creating LXC container: %v, error status: %s (params: %v)", err, exitStatus, string(params))
	}

	_, err = client.UpdateVMHA(vmr, config.HaState)
	if err != nil {
		log.Printf("[ERROR] %q", err)
	}

	return
}

func (config ConfigLxc) UpdateConfig(vmr *VmRef, client *Client) (err error) {
	paramMap := config.mapToAPIParams()

	// delete parameters wich are not supported in updated operations
	delete(paramMap, "pool")
	delete(paramMap, "storage")
	delete(paramMap, "password")
	delete(paramMap, "ostemplate")
	delete(paramMap, "start")

	// even though it is listed as a PUT option in the API documentation
	// we remove it here because "it should not be modified manually";
	// also, error "500 unable to modify read-only option: 'unprivileged'"
	delete(paramMap, "unprivileged")

	_, err = client.SetLxcConfig(vmr, paramMap)
	return err

	_, err = client.UpdateVMHA(vmr, config.HaState)
	if err != nil {
		log.Printf("[ERROR] %q", err)
	}
}

func ParseLxcDisk(diskStr string) QemuDevice {
	disk := ParsePMConf(diskStr, "volume")

	// add features, if any
	if mountoptions, isSet := disk["mountoptions"]; isSet {
		moList := strings.Split(mountoptions.(string), ";")
		moMap := map[string]bool{}
		for _, mo := range moList {
			moMap[mo] = true
		}
		disk["mountoptions"] = moMap
	}

	storageName, fileName := ParseSubConf(disk["volume"].(string), ":")
	disk["storage"] = storageName
	disk["file"] = fileName

	return disk
}

func (config ConfigLxc) mapToAPIParams() map[string]interface{} {
	// convert config to map
	params, _ := json.Marshal(&config)
	var paramMap map[string]interface{}
	json.Unmarshal(params, &paramMap)

	// build list of features
	// add features as parameter list to lxc parameters
	// this overwrites the orginal formatting with a
	// comma separated list of "key=value" pairs
	paramMap["features"] = formatDeviceParam(config.Features)

	// format rootfs params as expected
	if rootfs := config.RootFs; rootfs != nil {
		paramMap["rootfs"] = FormatDiskParam(rootfs)
	}

	// build list of mountpoints
	// this does the same as for the feature list
	// except that there can be multiple of these mountpoint sets
	// and each mountpoint set comes with a new id
	for _, mpConfMap := range config.Mountpoints {
		// add mp to lxc parameters
		mpID := mpConfMap["slot"]
		mpName := fmt.Sprintf("mp%v", mpID)
		paramMap[mpName] = FormatDiskParam(mpConfMap)
	}

	// build list of network parameters
	for nicID, nicConfMap := range config.Networks {
		// add nic to lxc parameters
		nicName := fmt.Sprintf("net%v", nicID)
		paramMap[nicName] = formatDeviceParam(nicConfMap)
	}

	// build list of unused volumes for sake of completeness,
	// even if it is not recommended to change these volumes manually
	for volID, vol := range config.Unused {
		// add volume to lxc parameters
		volName := fmt.Sprintf("unused%v", volID)
		paramMap[volName] = vol
	}

	// now that we concatenated the key value parameter
	// list for the networks, mountpoints and unused volumes,
	// remove the original keys, since the Proxmox API does
	// not know how to handle this key
	delete(paramMap, "networks")
	delete(paramMap, "mountpoints")
	delete(paramMap, "unused")

	return paramMap
}
<|endoftext|>


<commit_before>package agent

// You can overridden buildVersion at compile time by using:
//
//  go run -ldflags "-X github.com/buildkite/agent/agent.buildVersion abc" *.go --version
//
// On CI, the binaries are always build with the buildVersion variable set.

var baseVersion string = "3.8.4"
var buildVersion string = ""

func Version() string {
	return baseVersion
}

func BuildVersion() string {
	if buildVersion != "" {
		return buildVersion
	} else {
		return "x"
	}
}
<commit_msg>Bump version to 3.8.5<commit_after>package agent

// You can overridden buildVersion at compile time by using:
//
//  go run -ldflags "-X github.com/buildkite/agent/agent.buildVersion abc" *.go --version
//
// On CI, the binaries are always build with the buildVersion variable set.

var baseVersion string = "3.8.5"
var buildVersion string = ""

func Version() string {
	return baseVersion
}

func BuildVersion() string {
	if buildVersion != "" {
		return buildVersion
	} else {
		return "x"
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2014 Josh Rickmar.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

// Package wk2 provides webkitgtk2 bindings for Go.
package wk2

// #cgo pkg-config: webkit2gtk-3.0
//
// #include <stdint.h>
// #include <stdlib.h>
// #include <string.h>
//
// #include <webkit2.h>
//
// #include "webkit2.go.h"
import "C"
import (
	"runtime"
	"unsafe"

	"github.com/conformal/gotk3/glib"
	"github.com/conformal/gotk3/gtk"
)

func init() {
	tm := []glib.TypeMarshaler{
		// Enums
		{glib.Type(C.webkit_load_event_get_type()), marshalLoadEvent},

		// Objects/Interfaces
		{glib.Type(C.webkit_uri_request_get_type()), marshalURIRequest},
		{glib.Type(C.webkit_web_context_get_type()), marshalWebContext},
		{glib.Type(C.webkit_web_view_get_type()), marshalWebView},
		{glib.Type(C.webkit_web_view_group_get_type()), marshalWebViewGroup},
	}
	glib.RegisterGValueMarshalers(tm)
}

//
// Constants
//

// LoadEvent is a representation of WebKit's WebKitLoadEvent.
type LoadEvent int

const (
	LoadStarted    LoadEvent = C.WEBKIT_LOAD_STARTED
	LoadRedirected LoadEvent = C.WEBKIT_LOAD_REDIRECTED
	LoadCommitted  LoadEvent = C.WEBKIT_LOAD_COMMITTED
	LoadFinished   LoadEvent = C.WEBKIT_LOAD_FINISHED
)

func marshalLoadEvent(p uintptr) (interface{}, error) {
	c := C.g_value_get_enum((*C.GValue)(unsafe.Pointer(p)))
	return LoadEvent(c), nil
}

//
// WebKitURIRequest
//

// URIRequest is a representation of WebKit's WebKitURIRequest.
type URIRequest struct {
	*glib.Object
}

func marshalURIRequest(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	return wrapURIRequest(obj), nil
}

func wrapURIRequest(obj *glib.Object) *URIRequest {
	return &URIRequest{obj}
}

// Native returns a pointer to the underlying WebKitURIRequest.
func (r *URIRequest) Native() *C.WebKitURIRequest {
	if r == nil || r.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(r.GObject)
	return C.toWebKitURIRequest(p)
}

// NewURIRequest is a wrapper around webkit_uri_request_new().
func NewURIRequest(uri string) *URIRequest {
	cstr := C.CString(uri)
	defer C.free(unsafe.Pointer(cstr))
	c := C.webkit_uri_request_new((*C.gchar)(cstr))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapURIRequest(obj)
}

//
// WebKitWebContext
//

// WebContext is a representation of WebKit's WebKitWebContext.
type WebContext struct {
	*glib.Object
}

func marshalWebContext(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	return wrapWebContext(obj), nil
}

func wrapWebContext(obj *glib.Object) *WebContext {
	return &WebContext{obj}
}

// Native returns a pointer to the underlying WebKitWebContext.
func (w *WebContext) Native() *C.WebKitWebContext {
	if w == nil || w.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(w.GObject)
	return C.toWebKitWebContext(p)
}

// DefaultWebContext is a wrapper around webkit_web_context_get_default().
func DefaultWebContext() *WebContext {
	c := C.webkit_web_context_get_default()
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapWebContext(obj)
}

//
// WebKitWebView
//

// WebView is a representation of WebKit's WebKitWebView.
type WebView struct {
	gtk.Widget
}

func marshalWebView(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	return wrapWebView(obj), nil
}

func wrapWebView(obj *glib.Object) *WebView {
	return &WebView{gtk.Widget{glib.InitiallyUnowned{obj}}}
}

// Native returns a pointer to the underlying WebKitWebView.
func (w *WebView) Native() *C.WebKitWebView {
	if w == nil || w.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(w.GObject)
	return C.toWebKitWebView(p)
}

// NewWebView is a wrapper around webkit_web_view_new().
func NewWebView() *WebView {
	c := C.webkit_web_view_new()
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapWebView(obj)
}

// NewWebViewWithContext is a wrapper around webkit_web_view_new_with_context().
func NewWebViewWithContext(context *WebContext) *WebView {
	c := C.webkit_web_view_new_with_context(context.Native())
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapWebView(obj)
}

// NewWebViewWithGroup is a wrapper around webkit_web_view_new_with_group().
func NewWebViewWithGroup(group *WebViewGroup) *WebView {
	c := C.webkit_web_view_new_with_group(group.Native())
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapWebView(obj)
}

// Context is a wrapper around webkit_web_view_get_context().
func (w *WebView) Context() *WebContext {
	c := C.webkit_web_view_get_context(w.Native())
	wc := (*WebContext)(unsafe.Pointer(c))
	// TODO: is this a good idea?
	w.Ref()
	runtime.SetFinalizer(wc, func(_ *WebContext) {
		w.Unref()
	})
	return wc
}

// LoadUri is a wrapper around webkit_web_view_load_uri().
func (w *WebView) LoadUri(uri string) {
	cstr := C.CString(uri)
	defer C.free(unsafe.Pointer(cstr))
	C.webkit_web_view_load_uri(w.Native(), (*C.gchar)(cstr))
}

// LoadHTML is a wrapper around webkit_web_view_load_html().
func (w *WebView) LoadHTML(content, baseURI string) {
	cContent := C.CString(content)
	cBaseURI := C.CString(baseURI)
	defer C.free(unsafe.Pointer(cContent))
	defer C.free(unsafe.Pointer(cBaseURI))
	C.webkit_web_view_load_html(w.Native(), (*C.gchar)(cContent),
		(*C.gchar)(cBaseURI))
}

// LoadAlternateHTML is a wrapper around webkit_web_view_load_alternate_html().
func (w *WebView) LoadAlternateHTML(content, contentURI, baseURI string) {
	cContent := C.CString(content)
	cContentURI := C.CString(contentURI)
	cBaseURI := C.CString(baseURI)
	defer C.free(unsafe.Pointer(cContent))
	defer C.free(unsafe.Pointer(cContentURI))
	defer C.free(unsafe.Pointer(cBaseURI))
	C.webkit_web_view_load_alternate_html(w.Native(), (*C.gchar)(cContent),
		(*C.gchar)(cContentURI), (*C.gchar)(cBaseURI))
}

// LoadPlainText is a wrapper around webkit_web_view_load_plain_text().
func (w *WebView) LoadPlainText(plainText string) {
	cstr := C.CString(plainText)
	defer C.free(unsafe.Pointer(cstr))
	C.webkit_web_view_load_plain_text(w.Native(), (*C.gchar)(cstr))
}

// LoadRequest is a wrapper around webkit_web_view_load_request().
func (w *WebView) LoadRequest(request *URIRequest) {
	C.webkit_web_view_load_request(w.Native(), request.Native())
}

//
// WebKitWebViewGroup
//

// WebViewGroup is a representation of WebKit's WebKitWebViewGroup.
type WebViewGroup struct {
	*glib.Object
}

func marshalWebViewGroup(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	return wrapWebViewGroup(obj), nil
}

func wrapWebViewGroup(obj *glib.Object) *WebViewGroup {
	return &WebViewGroup{obj}
}

// Native returns a pointer to the underlying WebKitWebViewGroup.
func (w *WebViewGroup) Native() *C.WebKitWebViewGroup {
	if w == nil || w.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(w.GObject)
	return C.toWebKitWebViewGroup(p)
}
<commit_msg>LoadUri -> LoadURI.<commit_after>// Copyright (c) 2014 Josh Rickmar.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

// Package wk2 provides webkitgtk2 bindings for Go.
package wk2

// #cgo pkg-config: webkit2gtk-3.0
//
// #include <stdint.h>
// #include <stdlib.h>
// #include <string.h>
//
// #include <webkit2.h>
//
// #include "webkit2.go.h"
import "C"
import (
	"runtime"
	"unsafe"

	"github.com/conformal/gotk3/glib"
	"github.com/conformal/gotk3/gtk"
)

func init() {
	tm := []glib.TypeMarshaler{
		// Enums
		{glib.Type(C.webkit_load_event_get_type()), marshalLoadEvent},

		// Objects/Interfaces
		{glib.Type(C.webkit_uri_request_get_type()), marshalURIRequest},
		{glib.Type(C.webkit_web_context_get_type()), marshalWebContext},
		{glib.Type(C.webkit_web_view_get_type()), marshalWebView},
		{glib.Type(C.webkit_web_view_group_get_type()), marshalWebViewGroup},
	}
	glib.RegisterGValueMarshalers(tm)
}

//
// Constants
//

// LoadEvent is a representation of WebKit's WebKitLoadEvent.
type LoadEvent int

const (
	LoadStarted    LoadEvent = C.WEBKIT_LOAD_STARTED
	LoadRedirected LoadEvent = C.WEBKIT_LOAD_REDIRECTED
	LoadCommitted  LoadEvent = C.WEBKIT_LOAD_COMMITTED
	LoadFinished   LoadEvent = C.WEBKIT_LOAD_FINISHED
)

func marshalLoadEvent(p uintptr) (interface{}, error) {
	c := C.g_value_get_enum((*C.GValue)(unsafe.Pointer(p)))
	return LoadEvent(c), nil
}

//
// WebKitURIRequest
//

// URIRequest is a representation of WebKit's WebKitURIRequest.
type URIRequest struct {
	*glib.Object
}

func marshalURIRequest(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	return wrapURIRequest(obj), nil
}

func wrapURIRequest(obj *glib.Object) *URIRequest {
	return &URIRequest{obj}
}

// Native returns a pointer to the underlying WebKitURIRequest.
func (r *URIRequest) Native() *C.WebKitURIRequest {
	if r == nil || r.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(r.GObject)
	return C.toWebKitURIRequest(p)
}

// NewURIRequest is a wrapper around webkit_uri_request_new().
func NewURIRequest(uri string) *URIRequest {
	cstr := C.CString(uri)
	defer C.free(unsafe.Pointer(cstr))
	c := C.webkit_uri_request_new((*C.gchar)(cstr))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapURIRequest(obj)
}

//
// WebKitWebContext
//

// WebContext is a representation of WebKit's WebKitWebContext.
type WebContext struct {
	*glib.Object
}

func marshalWebContext(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	return wrapWebContext(obj), nil
}

func wrapWebContext(obj *glib.Object) *WebContext {
	return &WebContext{obj}
}

// Native returns a pointer to the underlying WebKitWebContext.
func (w *WebContext) Native() *C.WebKitWebContext {
	if w == nil || w.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(w.GObject)
	return C.toWebKitWebContext(p)
}

// DefaultWebContext is a wrapper around webkit_web_context_get_default().
func DefaultWebContext() *WebContext {
	c := C.webkit_web_context_get_default()
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapWebContext(obj)
}

//
// WebKitWebView
//

// WebView is a representation of WebKit's WebKitWebView.
type WebView struct {
	gtk.Widget
}

func marshalWebView(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	return wrapWebView(obj), nil
}

func wrapWebView(obj *glib.Object) *WebView {
	return &WebView{gtk.Widget{glib.InitiallyUnowned{obj}}}
}

// Native returns a pointer to the underlying WebKitWebView.
func (w *WebView) Native() *C.WebKitWebView {
	if w == nil || w.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(w.GObject)
	return C.toWebKitWebView(p)
}

// NewWebView is a wrapper around webkit_web_view_new().
func NewWebView() *WebView {
	c := C.webkit_web_view_new()
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapWebView(obj)
}

// NewWebViewWithContext is a wrapper around webkit_web_view_new_with_context().
func NewWebViewWithContext(context *WebContext) *WebView {
	c := C.webkit_web_view_new_with_context(context.Native())
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapWebView(obj)
}

// NewWebViewWithGroup is a wrapper around webkit_web_view_new_with_group().
func NewWebViewWithGroup(group *WebViewGroup) *WebView {
	c := C.webkit_web_view_new_with_group(group.Native())
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	obj.RefSink()
	runtime.SetFinalizer(obj, (*glib.Object).Unref)
	return wrapWebView(obj)
}

// Context is a wrapper around webkit_web_view_get_context().
func (w *WebView) Context() *WebContext {
	c := C.webkit_web_view_get_context(w.Native())
	wc := (*WebContext)(unsafe.Pointer(c))
	// TODO: is this a good idea?
	w.Ref()
	runtime.SetFinalizer(wc, func(_ *WebContext) {
		w.Unref()
	})
	return wc
}

// LoadURI is a wrapper around webkit_web_view_load_uri().
func (w *WebView) LoadURI(uri string) {
	cstr := C.CString(uri)
	defer C.free(unsafe.Pointer(cstr))
	C.webkit_web_view_load_uri(w.Native(), (*C.gchar)(cstr))
}

// LoadHTML is a wrapper around webkit_web_view_load_html().
func (w *WebView) LoadHTML(content, baseURI string) {
	cContent := C.CString(content)
	cBaseURI := C.CString(baseURI)
	defer C.free(unsafe.Pointer(cContent))
	defer C.free(unsafe.Pointer(cBaseURI))
	C.webkit_web_view_load_html(w.Native(), (*C.gchar)(cContent),
		(*C.gchar)(cBaseURI))
}

// LoadAlternateHTML is a wrapper around webkit_web_view_load_alternate_html().
func (w *WebView) LoadAlternateHTML(content, contentURI, baseURI string) {
	cContent := C.CString(content)
	cContentURI := C.CString(contentURI)
	cBaseURI := C.CString(baseURI)
	defer C.free(unsafe.Pointer(cContent))
	defer C.free(unsafe.Pointer(cContentURI))
	defer C.free(unsafe.Pointer(cBaseURI))
	C.webkit_web_view_load_alternate_html(w.Native(), (*C.gchar)(cContent),
		(*C.gchar)(cContentURI), (*C.gchar)(cBaseURI))
}

// LoadPlainText is a wrapper around webkit_web_view_load_plain_text().
func (w *WebView) LoadPlainText(plainText string) {
	cstr := C.CString(plainText)
	defer C.free(unsafe.Pointer(cstr))
	C.webkit_web_view_load_plain_text(w.Native(), (*C.gchar)(cstr))
}

// LoadRequest is a wrapper around webkit_web_view_load_request().
func (w *WebView) LoadRequest(request *URIRequest) {
	C.webkit_web_view_load_request(w.Native(), request.Native())
}

//
// WebKitWebViewGroup
//

// WebViewGroup is a representation of WebKit's WebKitWebViewGroup.
type WebViewGroup struct {
	*glib.Object
}

func marshalWebViewGroup(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	obj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}
	return wrapWebViewGroup(obj), nil
}

func wrapWebViewGroup(obj *glib.Object) *WebViewGroup {
	return &WebViewGroup{obj}
}

// Native returns a pointer to the underlying WebKitWebViewGroup.
func (w *WebViewGroup) Native() *C.WebKitWebViewGroup {
	if w == nil || w.GObject == nil {
		return nil
	}
	p := unsafe.Pointer(w.GObject)
	return C.toWebKitWebViewGroup(p)
}
<|endoftext|>


<commit_before>package gearman

import (
	"io"
	_ "net"
	"testing"
)

func trivialWorker(t *testing.T, end chan struct{}, srv ...Conn) {
	w := NewWorker(end, nil)
	w.AddServers(srv...)
	w.AddHandler("reverse", JobHandler(func(payload io.Reader, reply io.Writer) error {
		buff := make([]byte, 1<<16)
		s, _ := payload.Read(buff)
		buff = buff[0:s]

		for i := len(buff); i > 0; i-- {
			reply.Write([]byte{buff[i-1]})
		}

		return nil
	}))

	<-end
}

func Test_Worker_simple(t *testing.T) {
	end := make(chan struct{})
	defer close(end)

	srv := ConnTest()
	go trivialWorker(t, end, srv)

	if !valid_step(t, srv.Received(), packet(CAN_DO, []byte("reverse"))) {
		return
	}

	if !valid_step(t, srv.Received(), pre_sleep) {
		return
	}

	srv.Send(noop)
	if !valid_step(t, srv.Received(), grab_job) {
		return
	}

	if !valid_step(t, srv.Received(), grab_job_uniq) {
		return
	}

	srv.Send(no_job)
	srv.Send(packet(JOB_ASSIGN, []byte("H:lap:1"), []byte("reverse"), []byte("test")))
	if !valid_step(t, srv.Received(), pre_sleep) {
		return
	}
	if !valid_step(t, srv.Received(), packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("tset"))) {
		return
	}
}

func Test_Worker_two_servers(t *testing.T) {
	end := make(chan struct{})
	defer close(end)

	srv1 := ConnTest()
	srv2 := ConnTest()
	go trivialWorker(t, end, srv1, srv2)

	for _, srv := range []*testConn{srv1, srv2} {
		if !valid_step(t, srv.Received(), packet(CAN_DO, []byte("reverse"))) {
			return
		}

		if !valid_step(t, srv.Received(), pre_sleep) {
			return
		}

	}

	srv2.Send(noop)
	srv1.Send(noop)

	for _, srv := range []*testConn{srv1, srv2} {
		if !valid_step(t, srv.Received(), grab_job) {
			return
		}
		if !valid_step(t, srv.Received(), grab_job_uniq) {
			return
		}
	}

	srv1.Send(no_job)
	srv2.Send(no_job)

	srv1.Send(packet(JOB_ASSIGN, []byte("H:lap:1"), []byte("reverse"), []byte("test srv1")))
	srv2.Send(packet(JOB_ASSIGN, []byte("H:lap:1"), []byte("reverse"), []byte("test srv2")))

	rec := srv1.Received()
	if !valid_any_step(t, rec, pre_sleep, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("1vrs tset"))) {
		return
	}

	rec = srv1.Received()
	if !valid_any_step(t, rec, pre_sleep, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("1vrs tset"))) {
		return
	}

	rec = srv2.Received()
	if !valid_any_step(t, rec, pre_sleep, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("2vrs tset"))) {
		return
	}

	rec = srv2.Received()
	if !valid_any_step(t, rec, pre_sleep, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("2vrs tset"))) {
		return
	}
}

func Test_Worker_netcon(t *testing.T) {
	end := make(chan struct{})

	l, err := net.Listen("tcp", "localhost:60000")
	if err != nil {
		t.Errorf("got error %+v", err)
		return
	}
	defer l.Close()
	defer close(end)

	go trivialWorker(t, end, NetConn("tcp", "localhost:60000"))

	nb_test := 0
	for {
		select {
		case <-end:
			return

		default:
			conn, err := l.Accept()
			if err != nil {
				t.Errorf("got error %+v", err)
				return
			}
			nb_test++
			if nb_test > 10 {
				return
			}

			go func(c net.Conn) {
				defer c.Close()

				if !packet_received_is(t, c, can_do("reverse")) {
					return
				}

				if !packet_received_is(t, c, pre_sleep) {
					return
				}

				WritePacket(c, noop)

				if !packet_received_is(t, c, grab_job) {
					return
				}

				if !packet_received_is(t, c, grab_job_uniq) {
					return
				}

				WritePacket(c, no_job)
				WritePacket(c, packet(JOB_ASSIGN, []byte("H:lap:1"), []byte("reverse"), []byte("test")))

				if !packet_received_is(t, c, pre_sleep) {
					return
				}

				if !packet_received_is(t, c, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("tset"))) {
					return
				}
			}(conn)
		}
	}
}
//*/
<commit_msg>add missing dep<commit_after>package gearman

import (
	"io"
	"net"
	"testing"
)

func trivialWorker(t *testing.T, end chan struct{}, srv ...Conn) {
	w := NewWorker(end, nil)
	w.AddServers(srv...)
	w.AddHandler("reverse", JobHandler(func(payload io.Reader, reply io.Writer) error {
		buff := make([]byte, 1<<16)
		s, _ := payload.Read(buff)
		buff = buff[0:s]

		for i := len(buff); i > 0; i-- {
			reply.Write([]byte{buff[i-1]})
		}

		return nil
	}))

	<-end
}

func Test_Worker_simple(t *testing.T) {
	end := make(chan struct{})
	defer close(end)

	srv := ConnTest()
	go trivialWorker(t, end, srv)

	if !valid_step(t, srv.Received(), packet(CAN_DO, []byte("reverse"))) {
		return
	}

	if !valid_step(t, srv.Received(), pre_sleep) {
		return
	}

	srv.Send(noop)
	if !valid_step(t, srv.Received(), grab_job) {
		return
	}

	if !valid_step(t, srv.Received(), grab_job_uniq) {
		return
	}

	srv.Send(no_job)
	srv.Send(packet(JOB_ASSIGN, []byte("H:lap:1"), []byte("reverse"), []byte("test")))
	if !valid_step(t, srv.Received(), pre_sleep) {
		return
	}
	if !valid_step(t, srv.Received(), packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("tset"))) {
		return
	}
}

func Test_Worker_two_servers(t *testing.T) {
	end := make(chan struct{})
	defer close(end)

	srv1 := ConnTest()
	srv2 := ConnTest()
	go trivialWorker(t, end, srv1, srv2)

	for _, srv := range []*testConn{srv1, srv2} {
		if !valid_step(t, srv.Received(), packet(CAN_DO, []byte("reverse"))) {
			return
		}

		if !valid_step(t, srv.Received(), pre_sleep) {
			return
		}

	}

	srv2.Send(noop)
	srv1.Send(noop)

	for _, srv := range []*testConn{srv1, srv2} {
		if !valid_step(t, srv.Received(), grab_job) {
			return
		}
		if !valid_step(t, srv.Received(), grab_job_uniq) {
			return
		}
	}

	srv1.Send(no_job)
	srv2.Send(no_job)

	srv1.Send(packet(JOB_ASSIGN, []byte("H:lap:1"), []byte("reverse"), []byte("test srv1")))
	srv2.Send(packet(JOB_ASSIGN, []byte("H:lap:1"), []byte("reverse"), []byte("test srv2")))

	rec := srv1.Received()
	if !valid_any_step(t, rec, pre_sleep, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("1vrs tset"))) {
		return
	}

	rec = srv1.Received()
	if !valid_any_step(t, rec, pre_sleep, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("1vrs tset"))) {
		return
	}

	rec = srv2.Received()
	if !valid_any_step(t, rec, pre_sleep, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("2vrs tset"))) {
		return
	}

	rec = srv2.Received()
	if !valid_any_step(t, rec, pre_sleep, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("2vrs tset"))) {
		return
	}
}

func Test_Worker_netcon(t *testing.T) {
	end := make(chan struct{})

	l, err := net.Listen("tcp", "localhost:60000")
	if err != nil {
		t.Errorf("got error %+v", err)
		return
	}
	defer l.Close()
	defer close(end)

	go trivialWorker(t, end, NetConn("tcp", "localhost:60000"))

	nb_test := 0
	for {
		select {
		case <-end:
			return

		default:
			conn, err := l.Accept()
			if err != nil {
				t.Errorf("got error %+v", err)
				return
			}
			nb_test++
			if nb_test > 10 {
				return
			}

			go func(c net.Conn) {
				defer c.Close()

				if !packet_received_is(t, c, packet(CAN_DO, []byte("reverse"))) {
					return
				}

				if !packet_received_is(t, c, pre_sleep) {
					return
				}

				WritePacket(c, noop)

				if !packet_received_is(t, c, grab_job) {
					return
				}

				if !packet_received_is(t, c, grab_job_uniq) {
					return
				}

				WritePacket(c, no_job)
				WritePacket(c, packet(JOB_ASSIGN, []byte("H:lap:1"), []byte("reverse"), []byte("test")))

				if !packet_received_is(t, c, pre_sleep) {
					return
				}

				if !packet_received_is(t, c, packet(WORK_COMPLETE_WRK, []byte("H:lap:1"), []byte("tset"))) {
					return
				}
			}(conn)
		}
	}
}
//*/
<|endoftext|>


<commit_before>// Copyright 2014 Mikio Hara. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tcp

import (
	"os"
	"sync"
	"syscall"
	"time"
	"unsafe"
)

var tcpKeepAlive = struct {
	sync.RWMutex
	syscall.TCPKeepalive
}{
	TCPKeepalive: syscall.TCPKeepalive{
		OnOff:    1,
		Time:     uint32(2 * time.Hour / time.Millisecond),
		Interval: uint32(time.Second / time.Millisecond),
	},
}

func (c *Conn) setKeepAliveIdleInterval(d time.Duration) error {
	fd, err := c.sysfd()
	if err != nil {
		return err
	}
	tcpKeepAlive.Lock()
	defer tcpKeepAlive.Unlock()
	d += (time.Millisecond - time.Nanosecond)
	msecs := uint32(d / time.Millisecond)
	prev := tcpKeepAlive.Time
	tcpKeepAlive.Time = msecs
	rv := uint32(0)
	siz := uint32(unsafe.Sizeof(tcpKeepAlive))
	if err := syscall.WSAIoctl(fd, syscall.SIO_KEEPALIVE_VALS, (*byte)(unsafe.Pointer(&tcpKeepAlive)), siz, nil, 0, &rv, nil, 0); err != nil {
		tcpKeepAlive.Time = prev
		return os.NewSyscallError("WSAIoctl", err)
	}
	return nil
}

func (c *Conn) setKeepAliveProbeInterval(d time.Duration) error {
	fd, err := c.sysfd()
	if err != nil {
		return err
	}
	tcpKeepAlive.Lock()
	defer tcpKeepAlive.Unlock()
	d += (time.Millisecond - time.Nanosecond)
	msecs := uint32(d / time.Millisecond)
	prev := tcpKeepAlive.Interval
	tcpKeepAlive.Interval = msecs
	rv := uint32(0)
	siz := uint32(unsafe.Sizeof(tcpKeepAlive))
	if err := syscall.WSAIoctl(fd, syscall.SIO_KEEPALIVE_VALS, (*byte)(unsafe.Pointer(&tcpKeepAlive)), siz, nil, 0, &rv, nil, 0); err != nil {
		tcpKeepAlive.Interval = prev
		return os.NewSyscallError("WSAIoctl", err)
	}
	return nil
}

func (c *Conn) setKeepAliveProbes(max int) error {
	// See http://msdn.microsoft.com/en-us/library/windows/desktop/dd877220(v=vs.85).aspx
	return errOpNoSupport
}

func (c *Conn) setCork(on bool) error {
	return errOpNoSupport
}

func (c *Conn) info() (*Info, error) {
	return nil, errOpNoSupport
}
<commit_msg>tcp: drop tcp prefix from internal variables<commit_after>// Copyright 2014 Mikio Hara. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tcp

import (
	"os"
	"sync"
	"syscall"
	"time"
	"unsafe"
)

var keepAlive = struct {
	sync.RWMutex
	syscall.TCPKeepalive
}{
	TCPKeepalive: syscall.TCPKeepalive{
		OnOff:    1,
		Time:     uint32(2 * time.Hour / time.Millisecond),
		Interval: uint32(time.Second / time.Millisecond),
	},
}

func (c *Conn) setKeepAliveIdleInterval(d time.Duration) error {
	fd, err := c.sysfd()
	if err != nil {
		return err
	}
	keepAlive.Lock()
	defer keepAlive.Unlock()
	d += (time.Millisecond - time.Nanosecond)
	msecs := uint32(d / time.Millisecond)
	prev := keepAlive.Time
	keepAlive.Time = msecs
	rv := uint32(0)
	siz := uint32(unsafe.Sizeof(keepAlive))
	if err := syscall.WSAIoctl(fd, syscall.SIO_KEEPALIVE_VALS, (*byte)(unsafe.Pointer(&keepAlive)), siz, nil, 0, &rv, nil, 0); err != nil {
		keepAlive.Time = prev
		return os.NewSyscallError("WSAIoctl", err)
	}
	return nil
}

func (c *Conn) setKeepAliveProbeInterval(d time.Duration) error {
	fd, err := c.sysfd()
	if err != nil {
		return err
	}
	keepAlive.Lock()
	defer keepAlive.Unlock()
	d += (time.Millisecond - time.Nanosecond)
	msecs := uint32(d / time.Millisecond)
	prev := keepAlive.Interval
	keepAlive.Interval = msecs
	rv := uint32(0)
	siz := uint32(unsafe.Sizeof(keepAlive))
	if err := syscall.WSAIoctl(fd, syscall.SIO_KEEPALIVE_VALS, (*byte)(unsafe.Pointer(&keepAlive)), siz, nil, 0, &rv, nil, 0); err != nil {
		keepAlive.Interval = prev
		return os.NewSyscallError("WSAIoctl", err)
	}
	return nil
}

func (c *Conn) setKeepAliveProbes(max int) error {
	// See http://msdn.microsoft.com/en-us/library/windows/desktop/dd877220(v=vs.85).aspx
	return errOpNoSupport
}

func (c *Conn) setCork(on bool) error {
	return errOpNoSupport
}

func (c *Conn) info() (*Info, error) {
	return nil, errOpNoSupport
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package merkle implements a time series prefix tree. Each epoch has its own
// prefix tree. By default, each new epoch is equal to the contents of the
// previous epoch.
// The prefix tree is a binary tree where the path through the tree expresses
// the location of each node.  Each branch expresses the longest shared prefix
// between child nodes. The depth of the tree is the longest shared prefix between
// all nodes.

package sparse

import (
	"crypto/sha512"
	"encoding/binary"
)

const (
	// HashSize contains the blocksize of the used hash function in bytes.
	HashSize = sha512.Size256
	// IndexLen is the maximum number of levels in this Merkle Tree.
	IndexLen = HashSize * 8
)

var (
	// LeafIdentifier is the data used to indicate a leaf node.
	LeafIdentifier = []byte("L")
	// EmptyIdentifier is used while calculating the data of nil sub branches.
	EmptyIdentifier = []byte("E")

	NewHash = sha512.New512_256
)

// HashLeaf calculate the merkle tree leaf node value. This is computed as
// H(Identifier || depth || index || dataHash), where Identifier, depth, and
// index are fixed-length.
func HashLeaf(identifier []byte, depth int, index []byte, dataHash []byte) []byte {
	bdepth := make([]byte, 4)
	binary.BigEndian.PutUint32(bdepth, uint32(depth))

	h := NewHash()
	h.Write(identifier)
	h.Write(bdepth)
	h.Write(index)
	h.Write(dataHash)
	return h.Sum(nil)
}

// HashIntermediateNode calculates an interior node's value by H(left || right)
func HashIntermediateNode(left []byte, right []byte) []byte {
	h := NewHash()
	h.Write(left)
	h.Write(right)
	return h.Sum(nil)
}

// EmptyLeafValue computes the value of an empty leaf as
// H(EmptyIdentifier || depth || index), where EmptyIdentifier, depth, and
// index are fixed-length.
func EmptyLeafValue(prefix string) []byte {
	return HashLeaf(EmptyIdentifier, len(prefix), []byte(prefix), nil)
}
<commit_msg>Function for computing new tree values<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package merkle implements a time series prefix tree. Each epoch has its own
// prefix tree. By default, each new epoch is equal to the contents of the
// previous epoch.
// The prefix tree is a binary tree where the path through the tree expresses
// the location of each node.  Each branch expresses the longest shared prefix
// between child nodes. The depth of the tree is the longest shared prefix between
// all nodes.

package sparse

import (
	"crypto/sha512"
	"encoding/binary"

	"github.com/google/e2e-key-server/tree"
)

const (
	// HashSize contains the blocksize of the used hash function in bytes.
	HashSize = sha512.Size256
	// IndexLen is the maximum number of levels in this Merkle Tree.
	IndexLen = HashSize * 8
)

var (
	// LeafIdentifier is the data used to indicate a leaf node.
	LeafIdentifier = []byte("L")
	// EmptyIdentifier is used while calculating the data of nil sub branches.
	EmptyIdentifier = []byte("E")

	NewHash = sha512.New512_256
)

// HashLeaf calculate the merkle tree leaf node value. This is computed as
// H(Identifier || depth || index || dataHash), where Identifier, depth, and
// index are fixed-length.
func HashLeaf(identifier []byte, depth int, index []byte, dataHash []byte) []byte {
	bdepth := make([]byte, 4)
	binary.BigEndian.PutUint32(bdepth, uint32(depth))

	h := NewHash()
	h.Write(identifier)
	h.Write(bdepth)
	h.Write(index)
	h.Write(dataHash)
	return h.Sum(nil)
}

// HashIntermediateNode calculates an interior node's value by H(left || right)
func HashIntermediateNode(left []byte, right []byte) []byte {
	h := NewHash()
	h.Write(left)
	h.Write(right)
	return h.Sum(nil)
}

// EmptyLeafValue computes the value of an empty leaf as
// H(EmptyIdentifier || depth || index), where EmptyIdentifier, depth, and
// index are fixed-length.
func EmptyLeafValue(prefix string) []byte {
	return HashLeaf(EmptyIdentifier, len(prefix), []byte(prefix), nil)
}

// NodeValues computes the new values for nodes up the tree.
func NodeValues(bindex string, leafHash []byte, nbrValues [][]byte) [][]byte {
	levels := len(bindex) + 1
	steps := len(bindex)
	nodeValues := make([][]byte, levels)
	nodeValues[0] = leafHash
	// assert len(nbrValues) == levels - 1
	for i := 0; i < steps; i++ {
		// Is the last node 0 or 1?
		var left, right []byte
		if bindex[steps-i-1] == tree.Zero {
			left = nodeValues[i]
			right = nbrValues[i]
		} else {
			left = nbrValues[i]
			right = nodeValues[i]
		}
		nodeValues[i+1] = HashIntermediateNode(left, right)
	}
	return nodeValues
}
<|endoftext|>


<commit_before>package suture

import "fmt"

type Incrementor struct {
	current int
	next    chan int
	stop    chan bool
}

func (i *Incrementor) Stop() {
	fmt.Println("Stopping the service")
	i.stop <- true
}

func (i *Incrementor) Serve() {
	for {
		select {
		case i.next <- i.current:
			i.current++
		case <-i.stop:
			// We sync here just to guarantee the output of "Stopping the service",
			// so this passes the test reliably.
			// Most services would simply "return" here.
			i.stop <- true
			return
		}
	}
}

func ExampleNew_simple() {
	supervisor := NewSimple("Supervisor")
	service := &Incrementor{0, make(chan int), make(chan bool)}
	supervisor.Add(service)

	go supervisor.ServeBackground()

	fmt.Println("Got:", <-service.next)
	fmt.Println("Got:", <-service.next)
	supervisor.Stop()

	// We sync here just to guarantee the output of "Stopping the service"
	<-service.stop

	// Output:
	// Got: 0
	// Got: 1
	// Stopping the service
}
<commit_msg>Resolve issue #19 by removing extraneous 'go' in example.<commit_after>package suture

import "fmt"

type Incrementor struct {
	current int
	next    chan int
	stop    chan bool
}

func (i *Incrementor) Stop() {
	fmt.Println("Stopping the service")
	i.stop <- true
}

func (i *Incrementor) Serve() {
	for {
		select {
		case i.next <- i.current:
			i.current++
		case <-i.stop:
			// We sync here just to guarantee the output of "Stopping the service",
			// so this passes the test reliably.
			// Most services would simply "return" here.
			i.stop <- true
			return
		}
	}
}

func ExampleNew_simple() {
	supervisor := NewSimple("Supervisor")
	service := &Incrementor{0, make(chan int), make(chan bool)}
	supervisor.Add(service)

	supervisor.ServeBackground()

	fmt.Println("Got:", <-service.next)
	fmt.Println("Got:", <-service.next)
	supervisor.Stop()

	// We sync here just to guarantee the output of "Stopping the service"
	<-service.stop

	// Output:
	// Got: 0
	// Got: 1
	// Stopping the service
}
<|endoftext|>


<commit_before>package leetcode

func searchMatrix(matrix [][]int, target int) bool {
	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return false
	}

	m, n := len(matrix), len(matrix[0])
	start, end, mid := 0, m*n-1, 0
	for start <= end {
		mid = (start + end) / 2
		v := matrix[mid/n][mid%n]

		if target < v {
			end = mid - 1
		} else if target > v {
			start = mid + 1
		} else {
			return true
		}
	}

	return false
}
<commit_msg>update searchMatrix<commit_after>package leetcode

func searchMatrix(matrix [][]int, target int) bool {
	if len(matrix) == 0 || len(matrix[0]) == 0 {
		return false
	}

	m, n := len(matrix), len(matrix[0])
	start, end, mid := 0, m*n-1, 0
	for start <= end {
		mid = start + (end-start)/2
		v := matrix[mid/n][mid%n]

		if target < v {
			end = mid - 1
		} else if target > v {
			start = mid + 1
		} else {
			return true
		}
	}

	return false
}
<|endoftext|>


<commit_before>package eventexporter

import (
	"time"

	analytics "github.com/segmentio/analytics-go"
)

var DateLayout = "Jan 2, 2006"

type SegmentIOExporter struct {
	Client *analytics.Client
}

func NewSegmentIOExporter(key string, size int) *SegmentIOExporter {
	client := analytics.New(key) // access token to authorize requests
	client.Size = size           // size of queue before flushing to api

	return &SegmentIOExporter{Client: client}
}

func (s *SegmentIOExporter) Send(event *Event) error {
	trackEvent, err := buildTrack(event)
	if err != nil {
		return err
	}

	return s.Client.Track(trackEvent)
}

func buildTrack(event *Event) (*analytics.Track, error) {
	if event.User.Username == "" {
		return nil, ErrSegmentIOUsernameEmpty
	}

	if event.User.Email == "" {
		return nil, ErrSegmentIOEmailEmpty
	}

	if event.Name == "" {
		return nil, ErrSegmentIOEventEmpty
	}

	event = addBody(event)

	return &analytics.Track{
		Event:      event.Name,
		UserId:     event.User.Username,
		Properties: event.Properties,
	}, nil
}

func addBody(event *Event) *Event {
	_, ok := event.Properties["body"]
	if ok {
		return event
	}

	if event.Body != nil {
		if event.Properties == nil {
			event.Properties = map[string]interface{}{}
		}

		event.Properties["body"] = event.Body.Content
		event.Properties["bodyType"] = event.Body.Type
	}

	event.Properties["email"] = event.User.Email
	event.Properties["currentDate"] = time.Now().UTC().Format(DateLayout)

	return event
}
<commit_msg>sender: check if user exists<commit_after>package eventexporter

import (
	"time"

	analytics "github.com/segmentio/analytics-go"
)

var DateLayout = "Jan 2, 2006"

type SegmentIOExporter struct {
	Client *analytics.Client
}

func NewSegmentIOExporter(key string, size int) *SegmentIOExporter {
	client := analytics.New(key) // access token to authorize requests
	client.Size = size           // size of queue before flushing to api

	return &SegmentIOExporter{Client: client}
}

func (s *SegmentIOExporter) Send(event *Event) error {
	trackEvent, err := buildTrack(event)
	if err != nil {
		return err
	}

	return s.Client.Track(trackEvent)
}

func buildTrack(event *Event) (*analytics.Track, error) {
	if event.User == nil {
		return nil, ErrSegmentIOUsernameEmpty
	}

	if event.User.Username == "" {
		return nil, ErrSegmentIOUsernameEmpty
	}

	if event.User.Email == "" {
		return nil, ErrSegmentIOEmailEmpty
	}

	if event.Name == "" {
		return nil, ErrSegmentIOEventEmpty
	}

	event = addBody(event)

	return &analytics.Track{
		Event:      event.Name,
		UserId:     event.User.Username,
		Properties: event.Properties,
	}, nil
}

func addBody(event *Event) *Event {
	_, ok := event.Properties["body"]
	if ok {
		return event
	}

	if event.Body != nil {
		if event.Properties == nil {
			event.Properties = map[string]interface{}{}
		}

		event.Properties["body"] = event.Body.Content
		event.Properties["bodyType"] = event.Body.Type
	}

	event.Properties["email"] = event.User.Email
	event.Properties["currentDate"] = time.Now().UTC().Format(DateLayout)

	return event
}
<|endoftext|>