<commit_before>// Package handlers is generated automatically by goal toolkit.
// Please, do not edit it manually.
package handlers

import (
	"net/http"

	contr "github.com/colegion/contrib/controllers/templates"

	"github.com/colegion/goal/strconv"
)

// Templates is an insance of tTemplates that is automatically generated from Templates controller
// being found at "github.com/colegion/contrib/controllers/templates/templates.go",
// and contains methods to be used as handler functions.
//
// Templates is a controller that provides support of HTML result
// rendering to your application.
// Use SetTemplatePaths to register templates and
// call c.RenderTemplate from your action to render some.
var Templates tTemplates

// tTemplates is a type with handler methods of Templates controller.
type tTemplates struct {
}

// New allocates (github.com/colegion/contrib/controllers/templates).Templates controller,
// then returns it.
func (t tTemplates) New() *contr.Templates {
	c := &contr.Templates{}
	return c
}

// Before calls (github.com/colegion/contrib/controllers/templates).Templates.Before.
func (t tTemplates) Before(c *contr.Templates, w http.ResponseWriter, r *http.Request) http.Handler {
	// Call magic Before action of (github.com/colegion/contrib/controllers/templates).Templates.
	if res := c.Before( // "Binding" parameters.
	); res != nil {
		return res
	}
	return nil
}

// After is a dump method that always returns nil.
func (t tTemplates) After(c *contr.Templates, w http.ResponseWriter, r *http.Request) http.Handler {
	return nil
}

// Initially is a method that is started by every handler function at the very beginning
// of their execution phase.
func (t tTemplates) Initially(c *contr.Templates, w http.ResponseWriter, r *http.Request, a []string) (finish bool) {
	// Call magic Initially method of (github.com/colegion/contrib/controllers/templates).Templates.
	return c.Initially(w, r, a)
}

// Finally is a method that is started by every handler function at the very end
// of their execution phase no matter what.
func (t tTemplates) Finally(c *contr.Templates, w http.ResponseWriter, r *http.Request, a []string) (finish bool) {
	return
}

// Render is a handler that was generated automatically.
// It calls Before, After, Finally methods, and Render action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// Render is an equivalent of
// RenderTemplate(ControllerName+"/"+ActionName+".html").
func (t tTemplates) Render(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "Render"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.Render( // "Binding" parameters.
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// RenderTemplate is a handler that was generated automatically.
// It calls Before, After, Finally methods, and RenderTemplate action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// RenderTemplate is an action that gets a path to template
// and renders it using data from Context.
func (t tTemplates) RenderTemplate(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "RenderTemplate"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.RenderTemplate( // "Binding" parameters.
		strconv.String(r.Form, "templatePath"),
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// RenderError is a handler that was generated automatically.
// It calls Before, After, Finally methods, and RenderError action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// RenderError is an action that renders Error 500 page.
func (t tTemplates) RenderError(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "RenderError"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.RenderError( // "Binding" parameters.
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// RenderNotFound is a handler that was generated automatically.
// It calls Before, After, Finally methods, and RenderNotFound action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// RenderNotFound is an action that renders Error 404 page.
func (t tTemplates) RenderNotFound(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "RenderNotFound"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.RenderNotFound( // "Binding" parameters.
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// Init is used to initialize controllers of "github.com/colegion/contrib/controllers/templates"
// and its parents.
func Init() {
	initTemplates()
	contr.Init()
}

func initTemplates() {
}

func init() {
	_ = strconv.MeaningOfLife
}
<commit_msg>Redirect action has been added to templates controller<commit_after>// Package handlers is generated automatically by goal toolkit.
// Please, do not edit it manually.
package handlers

import (
	"net/http"

	contr "github.com/colegion/contrib/controllers/templates"

	"github.com/colegion/goal/strconv"
)

// Templates is an insance of tTemplates that is automatically generated from Templates controller
// being found at "github.com/colegion/contrib/controllers/templates/templates.go",
// and contains methods to be used as handler functions.
//
// Templates is a controller that provides support of HTML result
// rendering to your application.
// Use SetTemplatePaths to register templates and
// call c.RenderTemplate from your action to render some.
var Templates tTemplates

// tTemplates is a type with handler methods of Templates controller.
type tTemplates struct {
}

// New allocates (github.com/colegion/contrib/controllers/templates).Templates controller,
// then returns it.
func (t tTemplates) New() *contr.Templates {
	c := &contr.Templates{}
	return c
}

// Before calls (github.com/colegion/contrib/controllers/templates).Templates.Before.
func (t tTemplates) Before(c *contr.Templates, w http.ResponseWriter, r *http.Request) http.Handler {
	// Call magic Before action of (github.com/colegion/contrib/controllers/templates).Templates.
	if res := c.Before( // "Binding" parameters.
	); res != nil {
		return res
	}
	return nil
}

// After is a dump method that always returns nil.
func (t tTemplates) After(c *contr.Templates, w http.ResponseWriter, r *http.Request) http.Handler {
	return nil
}

// Initially is a method that is started by every handler function at the very beginning
// of their execution phase.
func (t tTemplates) Initially(c *contr.Templates, w http.ResponseWriter, r *http.Request, a []string) (finish bool) {
	// Call magic Initially method of (github.com/colegion/contrib/controllers/templates).Templates.
	return c.Initially(w, r, a)
}

// Finally is a method that is started by every handler function at the very end
// of their execution phase no matter what.
func (t tTemplates) Finally(c *contr.Templates, w http.ResponseWriter, r *http.Request, a []string) (finish bool) {
	return
}

// Render is a handler that was generated automatically.
// It calls Before, After, Finally methods, and Render action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// Render is an equivalent of
// RenderTemplate(ControllerName+"/"+ActionName+".html").
func (t tTemplates) Render(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "Render"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.Render( // "Binding" parameters.
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// RenderTemplate is a handler that was generated automatically.
// It calls Before, After, Finally methods, and RenderTemplate action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// RenderTemplate is an action that gets a path to template
// and renders it using data from Context.
func (t tTemplates) RenderTemplate(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "RenderTemplate"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.RenderTemplate( // "Binding" parameters.
		strconv.String(r.Form, "templatePath"),
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// RenderError is a handler that was generated automatically.
// It calls Before, After, Finally methods, and RenderError action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// RenderError is an action that renders Error 500 page.
func (t tTemplates) RenderError(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "RenderError"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.RenderError( // "Binding" parameters.
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// RenderNotFound is a handler that was generated automatically.
// It calls Before, After, Finally methods, and RenderNotFound action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// RenderNotFound is an action that renders Error 404 page.
func (t tTemplates) RenderNotFound(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "RenderNotFound"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.RenderNotFound( // "Binding" parameters.
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// Redirect is a handler that was generated automatically.
// It calls Before, After, Finally methods, and Redirect action found at
// github.com/colegion/contrib/controllers/templates/templates.go
// in appropriate order.
//
// Redirect gets a URI or URN (e.g. "https://si.te/smt or "/users")
// and returns a handler for user's redirect using 303 status code.
func (t tTemplates) Redirect(w http.ResponseWriter, r *http.Request) {
	var h http.Handler
	c := Templates.New()
	defer func() {
		if h != nil {
			h.ServeHTTP(w, r)
		}
	}()
	a := []string{"Templates", "Redirect"}
	defer Templates.Finally(c, w, r, a)
	if finish := Templates.Initially(c, w, r, a); finish {
		return
	}
	if res := Templates.Before(c, w, r); res != nil {
		h = res
		return
	}
	if res := c.Redirect( // "Binding" parameters.
		strconv.String(r.Form, "urn"),
	); res != nil {
		h = res
		return
	}
	if res := Templates.After(c, w, r); res != nil {
		h = res
	}
}

// Init is used to initialize controllers of "github.com/colegion/contrib/controllers/templates"
// and its parents.
func Init() {
	initTemplates()
	contr.Init()
}

func initTemplates() {
}

func init() {
	_ = strconv.MeaningOfLife
}
<|endoftext|>


<commit_before>// (C) Copyright 2021 Hewlett Packard Enterprise Development LP
//
// 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 oneview

import (
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/HewlettPackard/oneview-golang/utils"
	"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func resourceScope() *schema.Resource {
	return &schema.Resource{
		Create: resourceScopeCreate,
		Read:   resourceScopeRead,
		Update: resourceScopeUpdate,
		Delete: resourceScopeDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"description": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"state": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"type": {
				Type:     schema.TypeString,
				Required: true,
			},
			"uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"ext_attributes": {
				Optional: true,
				Type:     schema.TypeList,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"type": {
							Type:     schema.TypeString,
							Optional: true,
						},
					},
				},
			},
			"appliance_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"category": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"etag": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"old_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"scopes_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"initial_scope_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"added_resource_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"removed_resource_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
		},
	}
}

func resourceScopeCreate(d *schema.ResourceData, meta interface{}) error {

	config := meta.(*Config)

	scope := ov.Scope{
		Type:        d.Get("type").(string),
		Name:        d.Get("name").(string),
		Description: utils.NewNstring(d.Get("description").(string)),
	}

	if val, ok := d.GetOk("initial_scope_uris"); ok {
		rawinitialScopeUris := val.(*schema.Set).List()
		initialScopeUris := make([]utils.Nstring, len(rawinitialScopeUris))
		for i, rawData := range rawinitialScopeUris {
			initialScopeUris[i] = utils.Nstring(rawData.(string))
		}
		scope.InitialScopeUris = initialScopeUris
	}

	if val, ok := d.GetOk("added_resource_uris"); ok {
		rawAddedResourceUris := val.(*schema.Set).List()
		addedScopeUris := make([]utils.Nstring, len(rawAddedResourceUris))
		for i, rawData := range rawAddedResourceUris {
			addedScopeUris[i] = utils.Nstring(rawData.(string))
		}
		scope.AddedResourceUris = addedScopeUris
	}

	if val, ok := d.GetOk("removed_resource_uris"); ok {
		rawRemovedScopeUris := val.(*schema.Set).List()
		removedScopeUris := make([]utils.Nstring, len(rawRemovedScopeUris))
		for i, rawData := range rawRemovedScopeUris {
			removedScopeUris[i] = utils.Nstring(rawData.(string))
		}
		scope.RemovedResourceUris = removedScopeUris
	}

	err := config.ovClient.CreateScope(scope)
	d.SetId(d.Get("name").(string))
	if err != nil {
		d.SetId("")
		return err
	}

	return resourceScopeRead(d, meta)
}

func resourceScopeRead(d *schema.ResourceData, meta interface{}) error {

	config := meta.(*Config)

	scope, err := config.ovClient.GetScopeByName(d.Id())
	if err != nil || scope.URI.IsNil() {
		d.SetId("")
		return nil
	}
	d.Set("name", scope.Name)
	d.Set("description", scope.Description)
	d.Set("state", scope.State)
	d.Set("status", scope.Status)
	d.Set("type", scope.Type)
	d.Set("uri", scope.URI.String())
	d.Set("appliance_id", scope.ApplianceId)
	d.Set("category", scope.Category)
	d.Set("etag", scope.Etag)
	d.Set("old_uri", scope.OldUri.String())
	d.Set("scopes_uri", scope.ScopesUri.String())
	d.Set("initial_scope_uris", scope.InitialScopeUris)
	d.Set("added_resource_uris", scope.AddedResourceUris)
	d.Set("removed_resource_uris", scope.RemovedResourceUris)

	return nil
}

func resourceScopeUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	scope := ov.Scope{
		URI:         utils.NewNstring(d.Get("uri").(string)),
		Type:        d.Get("type").(string),
		Name:        d.Get("name").(string),
		Description: utils.NewNstring(d.Get("description").(string)),
	}

	if val, ok := d.GetOk("added_resource_uris"); ok {
		rawAddedResourceUris := val.(*schema.Set).List()
		addedResourceUris := make([]utils.Nstring, len(rawAddedResourceUris))
		for i, rawData := range rawAddedResourceUris {
			addedResourceUris[i] = utils.Nstring(rawData.(string))
		}
		scope.AddedResourceUris = addedResourceUris
	}

	if val, ok := d.GetOk("removed_resource_uris"); ok {
		rawRemovedResourceUris := val.(*schema.Set).List()
		removedResourceUris := make([]utils.Nstring, len(rawRemovedResourceUris))
		for i, rawData := range rawRemovedResourceUris {
			removedResourceUris[i] = utils.Nstring(rawData.(string))
		}
		scope.RemovedResourceUris = removedResourceUris
	}

	err := config.ovClient.UpdateScope(scope)
	if err != nil {
		d.SetId("")
		return err
	}

	d.SetId(d.Get("name").(string))
	return resourceScopeRead(d, meta)
}

func resourceScopeDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	err := config.ovClient.DeleteScope(d.Get("name").(string))
	if err != nil {
		return err
	}
	return nil
}
<commit_msg>Update resource_scope.go<commit_after>// (C) Copyright 2021 Hewlett Packard Enterprise Development LP
//
// 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 oneview

import (
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/HewlettPackard/oneview-golang/utils"
	"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func resourceScope() *schema.Resource {
	return &schema.Resource{
		Create: resourceScopeCreate,
		Read:   resourceScopeRead,
		Update: resourceScopeUpdate,
		Delete: resourceScopeDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},

		Schema: map[string]*schema.Schema{
			"description": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"state": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"type": {
				Type:     schema.TypeString,
				Required: true,
			},
			"uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"ext_attributes": {
				Optional: true,
				Type:     schema.TypeList,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"type": {
							Type:     schema.TypeString,
							Optional: true,
						},
					},
				},
			},
			"appliance_id": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"category": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"etag": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"old_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"scopes_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"initial_scope_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"added_resource_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"removed_resource_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
		},
	}
}

func resourceScopeCreate(d *schema.ResourceData, meta interface{}) error {

	config := meta.(*Config)

	scope := ov.Scope{
		Type:        d.Get("type").(string),
		Name:        d.Get("name").(string),
		Description: utils.NewNstring(d.Get("description").(string)),
	}

	if val, ok := d.GetOk("initial_scope_uris"); ok {
		rawinitialScopeUris := val.(*schema.Set).List()
		initialScopeUris := make([]utils.Nstring, len(rawinitialScopeUris))
		for i, rawData := range rawinitialScopeUris {
			initialScopeUris[i] = utils.Nstring(rawData.(string))
		}
		scope.InitialScopeUris = initialScopeUris
	}

	if val, ok := d.GetOk("added_resource_uris"); ok {
		rawAddedResourceUris := val.(*schema.Set).List()
		addedScopeUris := make([]utils.Nstring, len(rawAddedResourceUris))
		for i, rawData := range rawAddedResourceUris {
			addedScopeUris[i] = utils.Nstring(rawData.(string))
		}
		scope.AddedResourceUris = addedScopeUris
	}

	if val, ok := d.GetOk("removed_resource_uris"); ok {
		rawRemovedScopeUris := val.(*schema.Set).List()
		removedScopeUris := make([]utils.Nstring, len(rawRemovedScopeUris))
		for i, rawData := range rawRemovedScopeUris {
			removedScopeUris[i] = utils.Nstring(rawData.(string))
		}
		scope.RemovedResourceUris = removedScopeUris
	}

	err := config.ovClient.CreateScope(scope)
	d.SetId(d.Get("name").(string))
	if err != nil {
		d.SetId("")
		return err
	}

	return resourceScopeRead(d, meta)
}

func resourceScopeRead(d *schema.ResourceData, meta interface{}) error {

	config := meta.(*Config)

	scope, err := config.ovClient.GetScopeByName(d.Id())
	if err != nil || scope.URI.IsNil() {
		d.SetId("")
		return nil
	}
	d.Set("name", scope.Name)
	d.Set("description", scope.Description)
	d.Set("state", scope.State)
	d.Set("status", scope.Status)
	d.Set("type", scope.Type)
	d.Set("uri", scope.URI.String())
	d.Set("appliance_id", scope.ApplianceId)
	d.Set("category", scope.Category)
	d.Set("etag", scope.Etag)
	d.Set("old_uri", scope.OldUri.String())
	d.Set("scopes_uri", scope.ScopesUri.String())
	d.Set("initial_scope_uris", scope.InitialScopeUris)
	d.Set("added_resource_uris", scope.AddedResourceUris)
	d.Set("removed_resource_uris", scope.RemovedResourceUris)

	return nil
}

func resourceScopeUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	scope := ov.Scope{
		URI:         utils.NewNstring(d.Get("uri").(string)),
		Type:        d.Get("type").(string),
		Name:        d.Get("name").(string),
		Description: utils.NewNstring(d.Get("description").(string)),
	}

	if val, ok := d.GetOk("added_resource_uris"); ok {
		rawAddedResourceUris := val.(*schema.Set).List()
		addedResourceUris := make([]utils.Nstring, len(rawAddedResourceUris))
		for i, rawData := range rawAddedResourceUris {
			addedResourceUris[i] = utils.Nstring(rawData.(string))
		}
		scope.AddedResourceUris = addedResourceUris
	}

	if val, ok := d.GetOk("removed_resource_uris"); ok {
		rawRemovedResourceUris := val.(*schema.Set).List()
		removedResourceUris := make([]utils.Nstring, len(rawRemovedResourceUris))
		for i, rawData := range rawRemovedResourceUris {
			removedResourceUris[i] = utils.Nstring(rawData.(string))
		}
		scope.RemovedResourceUris = removedResourceUris
	}

	err := config.ovClient.UpdateScope(scope)
	if err != nil {
		d.SetId("")
		return err
	}

	d.SetId(d.Get("name").(string))
	return resourceScopeRead(d, meta)
}

func resourceScopeDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	err := config.ovClient.DeleteScope(d.Get("name").(string))
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"log"
	"net/http"
)

var (
	address = flag.String("address", "127.0.0.1:8080", "bind host:port")
)

func EventsHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		log.Println("GET")
	} else if r.Method == "DELETE" {
		log.Println("DELETE")
	} else {
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

func main() {
	http.HandleFunc("/events", EventsHandler)
	log.Printf("Serving requests on: %s \n", *address)
	err := http.ListenAndServe(*address, nil)
	if err != nil {
		log.Fatal(err)
	}
}
<commit_msg>handle TCP and UDP simultaneously. UDP packets in separate go routines<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
)

var (
	host    = flag.String("host", "127.0.0.1", "host IP")
	udpPort = flag.String("udp", "8080", "udp port")
	tcpPort = flag.String("tcp", "8081", "tcp port")
)

func EventsHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		log.Println("GET")
	} else if r.Method == "DELETE" {
		log.Println("DELETE")
	} else {
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

func main() {
	flag.Parse()
	go serveUdp()
	serveTcp()
}

func serveTcp() {
	http.HandleFunc("/events", EventsHandler)
	log.Printf("Serving TCP requests on: %s:%s\n", *host, *tcpPort)
	err := http.ListenAndServe(*host+":"+*tcpPort, nil)
	if err != nil {
		log.Fatal(err)
	}
}

func serveUdp() {
	log.Printf("Serving UDP requests on: %s:%s\n", *host, *udpPort)
	addr, _ := net.ResolveUDPAddr("udp", ":"+*udpPort)
	sock, _ := net.ListenUDP("udp", addr)
	sock.SetReadBuffer(1048576)
	for {
		buf := make([]byte, 1024)
		rlen, _, err := sock.ReadFromUDP(buf)
		if err != nil {
			log.Fatal(err)
		}
		go handlePacket(buf, rlen)
	}
}

func handlePacket(buf []byte, rlen int) {
	fmt.Println(string(buf[0:rlen]))
}
<|endoftext|>


<commit_before>package acme

import (
	"time"

	"gopkg.in/square/go-jose.v1"
)

type directory struct {
	NewAuthzURL   string `json:"new-authz"`
	NewCertURL    string `json:"new-cert"`
	NewRegURL     string `json:"new-reg"`
	RevokeCertURL string `json:"revoke-cert"`
}

type recoveryKeyMessage struct {
	Length int             `json:"length,omitempty"`
	Client jose.JsonWebKey `json:"client,omitempty"`
	Server jose.JsonWebKey `json:"client,omitempty"`
}

type registrationMessage struct {
	Resource string   `json:"resource"`
	Contact  []string `json:"contact"`
	Delete   bool     `json:"delete,omitempty"`
	//	RecoveryKey recoveryKeyMessage `json:"recoveryKey,omitempty"`
}

// Registration is returned by the ACME server after the registration
// The client implementation should save this registration somewhere.
type Registration struct {
	Resource       string          `json:"resource,omitempty"`
	ID             int             `json:"id"`
	Key            jose.JsonWebKey `json:"key"`
	Contact        []string        `json:"contact"`
	Agreement      string          `json:"agreement,omitempty"`
	Authorizations string          `json:"authorizations,omitempty"`
	Certificates   string          `json:"certificates,omitempty"`
	//	RecoveryKey    recoveryKeyMessage `json:"recoveryKey,omitempty"`
}

// RegistrationResource represents all important informations about a registration
// of which the client needs to keep track itself.
type RegistrationResource struct {
	Body        Registration `json:"body,omitempty"`
	URI         string       `json:"uri,omitempty"`
	NewAuthzURL string       `json:"new_authzr_uri,omitempty"`
	TosURL      string       `json:"terms_of_service,omitempty"`
}

type authorizationResource struct {
	Body       authorization
	Domain     string
	NewCertURL string
	AuthURL    string
}

type authorization struct {
	Resource     string      `json:"resource,omitempty"`
	Identifier   identifier  `json:"identifier"`
	Status       string      `json:"status,omitempty"`
	Expires      time.Time   `json:"expires,omitempty"`
	Challenges   []challenge `json:"challenges,omitempty"`
	Combinations [][]int     `json:"combinations,omitempty"`
}

type identifier struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type validationRecord struct {
	URI               string   `json:"url,omitempty"`
	Hostname          string   `json:"hostname,omitempty"`
	Port              string   `json:"port,omitempty"`
	ResolvedAddresses []string `json:"addressesResolved,omitempty"`
	UsedAddress       string   `json:"addressUsed,omitempty"`
}

type challenge struct {
	Resource          string             `json:"resource,omitempty"`
	Type              Challenge          `json:"type,omitempty"`
	Status            string             `json:"status,omitempty"`
	URI               string             `json:"uri,omitempty"`
	Token             string             `json:"token,omitempty"`
	KeyAuthorization  string             `json:"keyAuthorization,omitempty"`
	TLS               bool               `json:"tls,omitempty"`
	Iterations        int                `json:"n,omitempty"`
	Error             RemoteError        `json:"error,omitempty"`
	ValidationRecords []validationRecord `json:"validationRecord,omitempty"`
}

type csrMessage struct {
	Resource       string   `json:"resource,omitempty"`
	Csr            string   `json:"csr"`
	Authorizations []string `json:"authorizations"`
}

type revokeCertMessage struct {
	Resource    string `json:"resource"`
	Certificate string `json:"certificate"`
}

// CertificateResource represents a CA issued certificate.
// PrivateKey and Certificate are both already PEM encoded
// and can be directly written to disk. Certificate may
// be a certificate bundle, depending on the options supplied
// to create it.
type CertificateResource struct {
	Domain        string `json:"domain"`
	CertURL       string `json:"certUrl"`
	CertStableURL string `json:"certStableUrl"`
	AccountRef    string `json:"accountRef,omitempty"`
	PrivateKey    []byte `json:"-"`
	Certificate   []byte `json:"-"`
	CSR           []byte `json:"-"`
}
<commit_msg>Fix duplicate json tag in recoveryKeyMessage<commit_after>package acme

import (
	"time"

	"gopkg.in/square/go-jose.v1"
)

type directory struct {
	NewAuthzURL   string `json:"new-authz"`
	NewCertURL    string `json:"new-cert"`
	NewRegURL     string `json:"new-reg"`
	RevokeCertURL string `json:"revoke-cert"`
}

type registrationMessage struct {
	Resource string   `json:"resource"`
	Contact  []string `json:"contact"`
	Delete   bool     `json:"delete,omitempty"`
}

// Registration is returned by the ACME server after the registration
// The client implementation should save this registration somewhere.
type Registration struct {
	Resource       string          `json:"resource,omitempty"`
	ID             int             `json:"id"`
	Key            jose.JsonWebKey `json:"key"`
	Contact        []string        `json:"contact"`
	Agreement      string          `json:"agreement,omitempty"`
	Authorizations string          `json:"authorizations,omitempty"`
	Certificates   string          `json:"certificates,omitempty"`
}

// RegistrationResource represents all important informations about a registration
// of which the client needs to keep track itself.
type RegistrationResource struct {
	Body        Registration `json:"body,omitempty"`
	URI         string       `json:"uri,omitempty"`
	NewAuthzURL string       `json:"new_authzr_uri,omitempty"`
	TosURL      string       `json:"terms_of_service,omitempty"`
}

type authorizationResource struct {
	Body       authorization
	Domain     string
	NewCertURL string
	AuthURL    string
}

type authorization struct {
	Resource     string      `json:"resource,omitempty"`
	Identifier   identifier  `json:"identifier"`
	Status       string      `json:"status,omitempty"`
	Expires      time.Time   `json:"expires,omitempty"`
	Challenges   []challenge `json:"challenges,omitempty"`
	Combinations [][]int     `json:"combinations,omitempty"`
}

type identifier struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type validationRecord struct {
	URI               string   `json:"url,omitempty"`
	Hostname          string   `json:"hostname,omitempty"`
	Port              string   `json:"port,omitempty"`
	ResolvedAddresses []string `json:"addressesResolved,omitempty"`
	UsedAddress       string   `json:"addressUsed,omitempty"`
}

type challenge struct {
	Resource          string             `json:"resource,omitempty"`
	Type              Challenge          `json:"type,omitempty"`
	Status            string             `json:"status,omitempty"`
	URI               string             `json:"uri,omitempty"`
	Token             string             `json:"token,omitempty"`
	KeyAuthorization  string             `json:"keyAuthorization,omitempty"`
	TLS               bool               `json:"tls,omitempty"`
	Iterations        int                `json:"n,omitempty"`
	Error             RemoteError        `json:"error,omitempty"`
	ValidationRecords []validationRecord `json:"validationRecord,omitempty"`
}

type csrMessage struct {
	Resource       string   `json:"resource,omitempty"`
	Csr            string   `json:"csr"`
	Authorizations []string `json:"authorizations"`
}

type revokeCertMessage struct {
	Resource    string `json:"resource"`
	Certificate string `json:"certificate"`
}

// CertificateResource represents a CA issued certificate.
// PrivateKey and Certificate are both already PEM encoded
// and can be directly written to disk. Certificate may
// be a certificate bundle, depending on the options supplied
// to create it.
type CertificateResource struct {
	Domain        string `json:"domain"`
	CertURL       string `json:"certUrl"`
	CertStableURL string `json:"certStableUrl"`
	AccountRef    string `json:"accountRef,omitempty"`
	PrivateKey    []byte `json:"-"`
	Certificate   []byte `json:"-"`
	CSR           []byte `json:"-"`
}
<|endoftext|>


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

package action

import (
	"fmt"
	"sync"

	"github.com/pkg/errors"
	"github.com/tsuru/tsuru/log"
)

// Result is the value returned by Forward. It is used in the call of the next
// action, and also when rolling back the actions.
type Result interface{}

// Forward is the function called by the pipeline executor in the forward
// phase.  It receives a FWContext instance, that contains the list of
// parameters given to the pipeline executor and the result of the previous
// action in the pipeline (which will be nil for the first action in the
// pipeline).
type Forward func(context FWContext) (Result, error)

// Backward is the function called by the pipeline executor when in the
// backward phase. It receives the context instance, that contains the list of
// parameters given to the pipeline executor and the result of the forward
// phase.
type Backward func(context BWContext)

type OnErrorFunc func(FWContext, error)

// FWContext is the context used in calls to Forward functions (forward phase).
type FWContext struct {
	// Result of the previous action.
	Previous Result

	// List of parameters given to the executor.
	Params []interface{}
}

// BWContext is the context used in calls to Backward functions (backward
// phase).
type BWContext struct {
	// Result of the forward phase (for the current action).
	FWResult Result

	// List of parameters given to the executor.
	Params []interface{}
}

// Action defines actions that should be . It is composed of two functions:
// Forward and Backward.
//
// Each action should do only one thing, and do it well. All information that
// is needed to undo the action should be returned by the Forward function.
type Action struct {
	// Name is the action name. Used by the log.
	Name string

	// Function that will be invoked in the forward phase. This value
	// cannot be nil.
	Forward Forward

	// Function that will be invoked in the backward phase. For actions
	// that are not undoable, this attribute should be nil.
	Backward Backward

	// Minimum number of parameters that this action requires to run.
	MinParams int

	// Function that will be invoked after some failure occurured in the
	// Forward phase of this same action.
	OnError OnErrorFunc

	// Result of the action. Stored for use in the backward phase.
	result Result

	// mutex for the result
	rMutex sync.Mutex
}

// Pipeline is a list of actions. Each pipeline is atomic: either all actions
// are successfully executed, or none of them are. For that, it's fundamental
// that all actions are really small and atomic.
type Pipeline struct {
	actions []*Action
}

var (
	ErrPipelineNoActions      = errors.New("No actions to execute.")
	ErrPipelineForwardMissing = errors.New("All actions must define the forward function.")
	ErrPipelineFewParameters  = errors.New("Not enough parameters to call Action.Forward.")
)

// NewPipeline creates a new pipeline instance with the given list of actions.
func NewPipeline(actions ...*Action) *Pipeline {
	// Actions are usually global functions, copying them
	// guarantees each copy has an isolated Result.
	newActions := make([]*Action, len(actions))
	for i, action := range actions {
		newAction := &Action{
			Name:      action.Name,
			Forward:   action.Forward,
			Backward:  action.Backward,
			MinParams: action.MinParams,
			OnError:   action.OnError,
		}
		newActions[i] = newAction
	}
	return &Pipeline{actions: newActions}

}

// Result returns the result of the last action.
func (p *Pipeline) Result() Result {
	action := p.actions[len(p.actions)-1]
	action.rMutex.Lock()
	defer action.rMutex.Unlock()
	return action.result
}

// Execute executes the pipeline.
//
// The execution starts in the forward phase, calling the Forward function of
// all actions. If none of the Forward calls return error, the pipeline
// execution ends in the forward phase and is "committed".
//
// If any of the Forward calls fails, the executor switches to the backward phase
// (roll back) and call the Backward function for each action completed. It
// does not call the Backward function of the action that has failed.
//
// After rolling back all completed actions, it returns the original error
// returned by the action that failed.
func (p *Pipeline) Execute(params ...interface{}) (err error) {
	var (
		r Result
	)
	if len(p.actions) == 0 {
		return ErrPipelineNoActions
	}
	fwCtx := FWContext{Params: params}
	var i int
	var a *Action
	defer func() {
		if r := recover(); r != nil {
			log.Debugf("[pipeline] PANIC running the Forward for the %s action - %v", a.Name, r)
			err = fmt.Errorf("panic running the Forward for the %s action: %v", a.Name, r)
			if a.OnError != nil {
				a.OnError(fwCtx, err)
			}
			p.rollback(i-1, params)
		}
	}()
	for i, a = range p.actions {
		log.Debugf("[pipeline] running the Forward for the %s action", a.Name)
		if a.Forward == nil {
			err = ErrPipelineForwardMissing
		} else if len(fwCtx.Params) < a.MinParams {
			err = ErrPipelineFewParameters
		} else {
			r, err = a.Forward(fwCtx)
			a.rMutex.Lock()
			a.result = r
			a.rMutex.Unlock()
			fwCtx.Previous = r
		}
		if err != nil {
			log.Debugf("[pipeline] error running the Forward for the %s action - %s", a.Name, err)
			if a.OnError != nil {
				a.OnError(fwCtx, err)
			}
			p.rollback(i-1, params)
			return err
		}
	}
	return nil
}

func (p *Pipeline) rollback(index int, params []interface{}) {
	bwCtx := BWContext{Params: params}
	for i := index; i >= 0; i-- {
		log.Debugf("[pipeline] running Backward for %s action", p.actions[i].Name)
		if p.actions[i].Backward != nil {
			bwCtx.FWResult = p.actions[i].result
			p.actions[i].Backward(bwCtx)
		}
	}
}
<commit_msg>action: log pipeline error/panic with log.Errorf<commit_after>// Copyright 2013 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package action

import (
	"fmt"
	"sync"

	"github.com/pkg/errors"
	"github.com/tsuru/tsuru/log"
)

// Result is the value returned by Forward. It is used in the call of the next
// action, and also when rolling back the actions.
type Result interface{}

// Forward is the function called by the pipeline executor in the forward
// phase.  It receives a FWContext instance, that contains the list of
// parameters given to the pipeline executor and the result of the previous
// action in the pipeline (which will be nil for the first action in the
// pipeline).
type Forward func(context FWContext) (Result, error)

// Backward is the function called by the pipeline executor when in the
// backward phase. It receives the context instance, that contains the list of
// parameters given to the pipeline executor and the result of the forward
// phase.
type Backward func(context BWContext)

type OnErrorFunc func(FWContext, error)

// FWContext is the context used in calls to Forward functions (forward phase).
type FWContext struct {
	// Result of the previous action.
	Previous Result

	// List of parameters given to the executor.
	Params []interface{}
}

// BWContext is the context used in calls to Backward functions (backward
// phase).
type BWContext struct {
	// Result of the forward phase (for the current action).
	FWResult Result

	// List of parameters given to the executor.
	Params []interface{}
}

// Action defines actions that should be . It is composed of two functions:
// Forward and Backward.
//
// Each action should do only one thing, and do it well. All information that
// is needed to undo the action should be returned by the Forward function.
type Action struct {
	// Name is the action name. Used by the log.
	Name string

	// Function that will be invoked in the forward phase. This value
	// cannot be nil.
	Forward Forward

	// Function that will be invoked in the backward phase. For actions
	// that are not undoable, this attribute should be nil.
	Backward Backward

	// Minimum number of parameters that this action requires to run.
	MinParams int

	// Function that will be invoked after some failure occurured in the
	// Forward phase of this same action.
	OnError OnErrorFunc

	// Result of the action. Stored for use in the backward phase.
	result Result

	// mutex for the result
	rMutex sync.Mutex
}

// Pipeline is a list of actions. Each pipeline is atomic: either all actions
// are successfully executed, or none of them are. For that, it's fundamental
// that all actions are really small and atomic.
type Pipeline struct {
	actions []*Action
}

var (
	ErrPipelineNoActions      = errors.New("No actions to execute.")
	ErrPipelineForwardMissing = errors.New("All actions must define the forward function.")
	ErrPipelineFewParameters  = errors.New("Not enough parameters to call Action.Forward.")
)

// NewPipeline creates a new pipeline instance with the given list of actions.
func NewPipeline(actions ...*Action) *Pipeline {
	// Actions are usually global functions, copying them
	// guarantees each copy has an isolated Result.
	newActions := make([]*Action, len(actions))
	for i, action := range actions {
		newAction := &Action{
			Name:      action.Name,
			Forward:   action.Forward,
			Backward:  action.Backward,
			MinParams: action.MinParams,
			OnError:   action.OnError,
		}
		newActions[i] = newAction
	}
	return &Pipeline{actions: newActions}

}

// Result returns the result of the last action.
func (p *Pipeline) Result() Result {
	action := p.actions[len(p.actions)-1]
	action.rMutex.Lock()
	defer action.rMutex.Unlock()
	return action.result
}

// Execute executes the pipeline.
//
// The execution starts in the forward phase, calling the Forward function of
// all actions. If none of the Forward calls return error, the pipeline
// execution ends in the forward phase and is "committed".
//
// If any of the Forward calls fails, the executor switches to the backward phase
// (roll back) and call the Backward function for each action completed. It
// does not call the Backward function of the action that has failed.
//
// After rolling back all completed actions, it returns the original error
// returned by the action that failed.
func (p *Pipeline) Execute(params ...interface{}) (err error) {
	var (
		r Result
	)
	if len(p.actions) == 0 {
		return ErrPipelineNoActions
	}
	fwCtx := FWContext{Params: params}
	var i int
	var a *Action
	defer func() {
		if r := recover(); r != nil {
			log.Errorf("[pipeline] PANIC running the Forward for the %s action - %v", a.Name, r)
			err = fmt.Errorf("panic running the Forward for the %s action: %v", a.Name, r)
			if a.OnError != nil {
				a.OnError(fwCtx, err)
			}
			p.rollback(i-1, params)
		}
	}()
	for i, a = range p.actions {
		log.Debugf("[pipeline] running the Forward for the %s action", a.Name)
		if a.Forward == nil {
			err = ErrPipelineForwardMissing
		} else if len(fwCtx.Params) < a.MinParams {
			err = ErrPipelineFewParameters
		} else {
			r, err = a.Forward(fwCtx)
			a.rMutex.Lock()
			a.result = r
			a.rMutex.Unlock()
			fwCtx.Previous = r
		}
		if err != nil {
			log.Errorf("[pipeline] error running the Forward for the %s action - %s", a.Name, err)
			if a.OnError != nil {
				a.OnError(fwCtx, err)
			}
			p.rollback(i-1, params)
			return err
		}
	}
	return nil
}

func (p *Pipeline) rollback(index int, params []interface{}) {
	bwCtx := BWContext{Params: params}
	for i := index; i >= 0; i-- {
		log.Debugf("[pipeline] running Backward for %s action", p.actions[i].Name)
		if p.actions[i].Backward != nil {
			bwCtx.FWResult = p.actions[i].result
			p.actions[i].Backward(bwCtx)
		}
	}
}
<|endoftext|>


<commit_before>package action

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"github.com/fatih/color"
	"github.com/ghodss/yaml"
	"github.com/justwatchcom/gopass/fsutil"
	"github.com/justwatchcom/gopass/gpg"
	"github.com/justwatchcom/gopass/password"
)

// Action knows everything to run gopass CLI actions
type Action struct {
	Name  string
	Store *password.RootStore
}

// New returns a new Action wrapper
func New(v string) *Action {
	name := "gopass"
	if len(os.Args) > 0 {
		name = filepath.Base(os.Args[0])
	}

	if gdb := os.Getenv("GOPASS_DEBUG"); gdb == "true" {
		gpg.Debug = true
	}
	pwDir := pwStoreDir("")

	// try to read config (if it exists)
	for _, l := range configLocations() {
		if cfg, err := newFromFile(l); err == nil && cfg != nil {
			cfg.ImportFunc = askForKeyImport
			cfg.FsckFunc = askForConfirmation
			cfg.Version = v
			color.NoColor = cfg.NoColor
			// need this override for our integration tests
			if nc := os.Getenv("GOPASS_NOCOLOR"); nc == "true" {
				color.NoColor = true
			}
			return &Action{
				Name:  name,
				Store: cfg,
			}
		}
	}

	cfg, err := password.NewRootStore(pwDir)
	if err != nil {
		panic(err)
	}

	cfg.ImportFunc = askForKeyImport
	cfg.FsckFunc = askForConfirmation
	cfg.Version = v
	color.NoColor = cfg.NoColor
	// need this override for our integration tests
	if nc := os.Getenv("GOPASS_NOCOLOR"); nc == "true" {
		color.NoColor = true
	}

	return &Action{
		Name:  name,
		Store: cfg,
	}
}

// newFromFile creates a new RootStore instance by unmarsahling a config file.
// If the file doesn't exist or fails to unmarshal an error is returned
func newFromFile(cf string) (*password.RootStore, error) {
	// deliberately using os.Stat here, a symlinked
	// config is OK
	if _, err := os.Stat(cf); err != nil {
		return nil, err
	}
	buf, err := ioutil.ReadFile(cf)
	if err != nil {
		fmt.Printf("Error reading config from %s: %s\n", cf, err)
		return nil, err
	}
	cfg := &password.RootStore{}
	err = yaml.Unmarshal(buf, &cfg)
	if err != nil {
		fmt.Printf("Error reading config from %s: %s\n", cf, err)
		return nil, err
	}
	return cfg, nil
}

// String implement fmt.Stringer
func (s *Action) String() string {
	return s.Store.String()
}

// pwStoreDir reads the password store dir from the environment
// or returns the default location ~/.password-store if the env is
// not set
func pwStoreDir(mount string) string {
	if mount != "" {
		return fsutil.CleanPath(filepath.Join(os.Getenv("HOME"), ".password-store-"+strings.Replace(mount, string(filepath.Separator), "-", -1)))
	}
	if d := os.Getenv("PASSWORD_STORE_DIR"); d != "" {
		return fsutil.CleanPath(d)
	}
	return os.Getenv("HOME") + "/.password-store"
}
<commit_msg>Suppress ANSI color codes unless stdout is a terminal (#111)<commit_after>package action

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	"golang.org/x/crypto/ssh/terminal"

	"github.com/fatih/color"
	"github.com/ghodss/yaml"
	"github.com/justwatchcom/gopass/fsutil"
	"github.com/justwatchcom/gopass/gpg"
	"github.com/justwatchcom/gopass/password"
)

// Action knows everything to run gopass CLI actions
type Action struct {
	Name  string
	Store *password.RootStore
}

// New returns a new Action wrapper
func New(v string) *Action {
	name := "gopass"
	if len(os.Args) > 0 {
		name = filepath.Base(os.Args[0])
	}

	if gdb := os.Getenv("GOPASS_DEBUG"); gdb == "true" {
		gpg.Debug = true
	}
	pwDir := pwStoreDir("")

	// try to read config (if it exists)
	for _, l := range configLocations() {
		if cfg, err := newFromFile(l); err == nil && cfg != nil {
			cfg.ImportFunc = askForKeyImport
			cfg.FsckFunc = askForConfirmation
			cfg.Version = v
			color.NoColor = cfg.NoColor
			// need this override for our integration tests
			if nc := os.Getenv("GOPASS_NOCOLOR"); nc == "true" {
				color.NoColor = true
			}
			// only emit color codes when stdout is a terminal
			if !terminal.IsTerminal(int(os.Stdout.Fd())) {
				color.NoColor = true
			}
			return &Action{
				Name:  name,
				Store: cfg,
			}
		}
	}

	cfg, err := password.NewRootStore(pwDir)
	if err != nil {
		panic(err)
	}

	cfg.ImportFunc = askForKeyImport
	cfg.FsckFunc = askForConfirmation
	cfg.Version = v
	color.NoColor = cfg.NoColor
	// need this override for our integration tests
	if nc := os.Getenv("GOPASS_NOCOLOR"); nc == "true" {
		color.NoColor = true
	}
	if !terminal.IsTerminal(int(os.Stdout.Fd())) {
		color.NoColor = true
	}

	return &Action{
		Name:  name,
		Store: cfg,
	}
}

// newFromFile creates a new RootStore instance by unmarsahling a config file.
// If the file doesn't exist or fails to unmarshal an error is returned
func newFromFile(cf string) (*password.RootStore, error) {
	// deliberately using os.Stat here, a symlinked
	// config is OK
	if _, err := os.Stat(cf); err != nil {
		return nil, err
	}
	buf, err := ioutil.ReadFile(cf)
	if err != nil {
		fmt.Printf("Error reading config from %s: %s\n", cf, err)
		return nil, err
	}
	cfg := &password.RootStore{}
	err = yaml.Unmarshal(buf, &cfg)
	if err != nil {
		fmt.Printf("Error reading config from %s: %s\n", cf, err)
		return nil, err
	}
	return cfg, nil
}

// String implement fmt.Stringer
func (s *Action) String() string {
	return s.Store.String()
}

// pwStoreDir reads the password store dir from the environment
// or returns the default location ~/.password-store if the env is
// not set
func pwStoreDir(mount string) string {
	if mount != "" {
		return fsutil.CleanPath(filepath.Join(os.Getenv("HOME"), ".password-store-"+strings.Replace(mount, string(filepath.Separator), "-", -1)))
	}
	if d := os.Getenv("PASSWORD_STORE_DIR"); d != "" {
		return fsutil.CleanPath(d)
	}
	return os.Getenv("HOME") + "/.password-store"
}
<|endoftext|>


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

package action

import "errors"

// Result is the value returned by Forward. It is used in the call of the next
// action, and also when rolling back the actions.
type Result interface{}

// Forward is the function called by the pipeline executor in the forward
// phase.  It receives a FWContext instance, that contains the list of
// parameters given to the pipeline executor and the result of the previous
// action in the pipeline (which will be nil for the first action in the
// pipeline).
type Forward func(context FWContext) (Result, error)

// Backward is the function called by the pipeline executor when in the
// backward phase. It receives the context instance, that contains the list of
// parameters given to the pipeline executor and the result of the forward
// phase.
type Backward func(context BWContext)

// FWContext is the context used in calls to Forward functions (forward phase).
type FWContext struct {
	// Result of the previous action.
	Previous Result

	// List of parameters given to the executor.
	Params []interface{}
}

// BWContext is the context used in calls to Backward functions (backward
// phase).
type BWContext struct {
	// Result of the forward phase (for the current action).
	FWResult Result

	// List of parameters given to the executor.
	Params []interface{}
}

// Action defines actions that should be . It is composed of two functions:
// Forward and Backward.
//
// Each action should do only one thing, and do it well. All information that
// is needed to undo the action should be returned by the Forward function.
type Action struct {
	// Name is the action name. Used by the log.
	Name string

	// Function that will be invoked in the forward phase. This value
	// cannot be nil.
	Forward Forward

	// Function that will be invoked in the backward phase. For actions
	// that are not undoable, this attribute should be nil.
	Backward Backward

	// Minimum number of parameters that this action requires to run.
	MinParams int

	// Result of the action. Stored for use in the backward phase.
	result Result
}

// Pipeline is a list of actions. Each pipeline is atomic: either all actions
// are successfully executed, or none of them are. For that, it's fundamental
// that all actions are really small and atomic.
type Pipeline struct {
	actions []*Action
}

// NewPipeline creates a new pipeline instance with the given list of actions.
func NewPipeline(actions ...*Action) *Pipeline {
	return &Pipeline{actions: actions}
}

// Execute executes the pipeline.
//
// The execution starts in the forward phase, calling the Forward function of
// all actions. If none of the Forward calls return error, the pipeline
// execution ends in the forward phase and is "committed".
//
// If any of the Forward call fail, the executor switches to the backward phase
// (roll back) and call the Backward function for each action completed. It
// does not call the Backward function of the action that has failed.
//
// After rolling back all completed actions, it returns the original error
// returned by the action that failed.
func (p *Pipeline) Execute(params ...interface{}) error {
	var (
		r   Result
		err error
	)
	if len(p.actions) == 0 {
		return errors.New("No actions to execute.")
	}
	fwCtx := FWContext{Params: params}
	for i, a := range p.actions {
		if a.Forward == nil {
			err = errors.New("All actions must define the forward function.")
		} else if len(fwCtx.Params) < a.MinParams {
			err = errors.New("Not enough parameters to call Action.Forward.")
		} else {
			r, err = a.Forward(fwCtx)
			a.result = r
			fwCtx.Previous = r
		}
		if err != nil {
			p.rollback(i-1, params)
			return err
		}
	}
	return nil
}

func (p *Pipeline) rollback(index int, params []interface{}) {
	bwCtx := BWContext{Params: params}
	for i := index; i >= 0; i-- {
		if p.actions[i].Backward != nil {
			bwCtx.FWResult = p.actions[i].result
			p.actions[i].Backward(bwCtx)
		}
	}
}
<commit_msg>action: logging the Forward execution.<commit_after>// Copyright 2013 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package action

import (
	"errors"
	"github.com/globocom/tsuru/log"
)

// Result is the value returned by Forward. It is used in the call of the next
// action, and also when rolling back the actions.
type Result interface{}

// Forward is the function called by the pipeline executor in the forward
// phase.  It receives a FWContext instance, that contains the list of
// parameters given to the pipeline executor and the result of the previous
// action in the pipeline (which will be nil for the first action in the
// pipeline).
type Forward func(context FWContext) (Result, error)

// Backward is the function called by the pipeline executor when in the
// backward phase. It receives the context instance, that contains the list of
// parameters given to the pipeline executor and the result of the forward
// phase.
type Backward func(context BWContext)

// FWContext is the context used in calls to Forward functions (forward phase).
type FWContext struct {
	// Result of the previous action.
	Previous Result

	// List of parameters given to the executor.
	Params []interface{}
}

// BWContext is the context used in calls to Backward functions (backward
// phase).
type BWContext struct {
	// Result of the forward phase (for the current action).
	FWResult Result

	// List of parameters given to the executor.
	Params []interface{}
}

// Action defines actions that should be . It is composed of two functions:
// Forward and Backward.
//
// Each action should do only one thing, and do it well. All information that
// is needed to undo the action should be returned by the Forward function.
type Action struct {
	// Name is the action name. Used by the log.
	Name string

	// Function that will be invoked in the forward phase. This value
	// cannot be nil.
	Forward Forward

	// Function that will be invoked in the backward phase. For actions
	// that are not undoable, this attribute should be nil.
	Backward Backward

	// Minimum number of parameters that this action requires to run.
	MinParams int

	// Result of the action. Stored for use in the backward phase.
	result Result
}

// Pipeline is a list of actions. Each pipeline is atomic: either all actions
// are successfully executed, or none of them are. For that, it's fundamental
// that all actions are really small and atomic.
type Pipeline struct {
	actions []*Action
}

// NewPipeline creates a new pipeline instance with the given list of actions.
func NewPipeline(actions ...*Action) *Pipeline {
	return &Pipeline{actions: actions}
}

// Execute executes the pipeline.
//
// The execution starts in the forward phase, calling the Forward function of
// all actions. If none of the Forward calls return error, the pipeline
// execution ends in the forward phase and is "committed".
//
// If any of the Forward call fail, the executor switches to the backward phase
// (roll back) and call the Backward function for each action completed. It
// does not call the Backward function of the action that has failed.
//
// After rolling back all completed actions, it returns the original error
// returned by the action that failed.
func (p *Pipeline) Execute(params ...interface{}) error {
	var (
		r   Result
		err error
	)
	if len(p.actions) == 0 {
		return errors.New("No actions to execute.")
	}
	fwCtx := FWContext{Params: params}
	for i, a := range p.actions {
		log.Printf("[pipeline] running the Forward for the %s action", a.Name)
		if a.Forward == nil {
			err = errors.New("All actions must define the forward function.")
		} else if len(fwCtx.Params) < a.MinParams {
			err = errors.New("Not enough parameters to call Action.Forward.")
		} else {
			r, err = a.Forward(fwCtx)
			a.result = r
			fwCtx.Previous = r
		}
		if err != nil {
			p.rollback(i-1, params)
			return err
		}
	}
	return nil
}

func (p *Pipeline) rollback(index int, params []interface{}) {
	bwCtx := BWContext{Params: params}
	for i := index; i >= 0; i-- {
		if p.actions[i].Backward != nil {
			bwCtx.FWResult = p.actions[i].result
			p.actions[i].Backward(bwCtx)
		}
	}
}
<|endoftext|>


<commit_before>package actions

import (
	"sort"

	"github.com/containrrr/watchtower/container"
)

// CheckPrereqs will ensure that there are not multiple instances of the
// watchtower running simultaneously. If multiple watchtower containers are
// detected, this function will stop and remove all but the most recently
// started container.
func CheckPrereqs(client container.Client, cleanup bool) error {
	containers, err := client.ListContainers(container.WatchtowerContainersFilter)
	if err != nil {
		return err
	}

	if len(containers) > 1 {
		sort.Sort(container.ByCreated(containers))

		// Iterate over all containers execept the last one
		for _, c := range containers[0 : len(containers)-1] {
			client.StopContainer(c, 60)

			if cleanup {
				client.RemoveImage(c)
			}
		}
	}

	return nil
}
<commit_msg>print to log if multiple watchtower instances are detected<commit_after>package actions

import (
	"sort"

	log "github.com/sirupsen/logrus"

	"github.com/containrrr/watchtower/container"
)

// CheckPrereqs will ensure that there are not multiple instances of the
// watchtower running simultaneously. If multiple watchtower containers are
// detected, this function will stop and remove all but the most recently
// started container.
func CheckPrereqs(client container.Client, cleanup bool) error {
	containers, err := client.ListContainers(container.WatchtowerContainersFilter)
	if err != nil {
		return err
	}

	if len(containers) > 1 {
		log.Info("Found multiple running watchtower instances. Cleaning up")
		sort.Sort(container.ByCreated(containers))

		// Iterate over all containers execept the last one
		for _, c := range containers[0 : len(containers)-1] {
			client.StopContainer(c, 60)

			if cleanup {
				client.RemoveImage(c)
			}
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/alecthomas/kingpin"

	"bitbucket.org/johnsto/ocrpdf/internal"
)

var (
	debug   bool = false
	verbose bool = false

	app = kingpin.New("ocrpdf", "OCR and PDF")

	output = app.Flag("output", "output file name").Short('o').String()

	tessData = app.Flag("tess-data", "Tesseract data directory").String()
	tessLang = app.Flag("tess-lang", "Tesseract language").String()

	docSize = app.Flag("size", "document size").
		Short('s').Default("a4").String()
	docTitle    = app.Flag("title", "document title").Short('t').String()
	docKeywords = app.Flag("keywords", "space-separated document keywords").
			Short('t').String()
	docAuthor      = app.Flag("author", "document author").Short('o').String()
	docOrientation = app.Flag("orientation", "document orientation").
			Default("auto").Short('r').Enum("auto", "portrait", "landscape")

	compress = app.Flag("compress", "compress document").
			Default("true").Short('c').Bool()

	fontName = app.Flag("font-name", "text font").
			Default("Arial").String()
	fontStyle = app.Flag("font-style", "font style, [B]old, [I]talic, [U]nderline").
			PlaceHolder(" ").
			Enum("B", "I", "U", "BI", "BU", "IU", "BIU")
	fontSize = app.Flag("font-size", "OCR layer font size").
			Default("10").Float()
	textScaling = app.Flag("scaling", "Scale text to match word boundaries").
			Default("match").Enum("off", "contain", "match")

	force = app.Flag("force", "overwrite output file").Short('f').Bool()

	imgContrast = app.Flag("contrast", "automatic contrast amount").
			Default("0.5").Float()
	imgFormat = app.Flag("format", "format to use when storing images in PDF").
			Default("auto").Enum("auto", "jpg", "png")

	input = app.Arg("input", "input image").Required().Strings()
)

func init() {
	app.Flag("debug", "enable debug mode").Short('d').BoolVar(&debug)
	app.Flag("verbose", "enable verbose mode").Short('v').BoolVar(&verbose)

}

func main() {
	kingpin.MustParse(app.Parse(os.Args[1:]))

	logv("Initialising Tesseract...")
	tess, err := internal.NewTess(*tessData, *tessLang)

	if err != nil {
		fmt.Errorf("Could not initialise Tesseract: %s\n", err)
		os.Exit(1)
	}

	doc := NewDocument(*docSize)
	doc.debug = debug
	doc.SetFont(*fontName, *fontStyle, *fontSize)
	doc.SetTextScaling(TextScaling(*textScaling))
	doc.SetTitle(*docTitle, true)
	doc.SetKeywords(*docKeywords, true)
	doc.SetAuthor(*docAuthor, true)
	doc.SetCompression(*compress)
	doc.SetOrientation(*docOrientation)

	files := *input

	if len(files) == 0 {
		fmt.Printf("No file(s) specified!\n")
		flag.Usage()
		os.Exit(1)
	}

	// When only one file is specified, output to a PDF of the same name
	outfn := *output
	if outfn == "" {
		outfn = files[0]
		ext := filepath.Ext(outfn)
		outfn = strings.TrimRight(outfn, ext) + ".pdf"
	}

	logvf("Using '%s' as output file.\n", outfn)

	openFlags := os.O_RDWR | os.O_CREATE
	if *force {
		openFlags |= os.O_TRUNC
	} else {
		openFlags |= os.O_EXCL
	}

	outfile, err := os.OpenFile(outfn, openFlags, 0666)

	if os.IsExist(err) {
		fmt.Printf("Output file '%s' already exists. Use -force to overwrite.",
			outfn)
		os.Exit(1)
	} else if err != nil {
		fmt.Printf("Couldn't create output file '%s': %s", outfn, err)
		os.Exit(1)
	}

	// Iterate through each filename specified, adding a page for each
	for i, fn := range files {
		no := i + 1
		logvf("[P%d] Reading '%s'...\n", no, fn)
		img := internal.NewImageFromFile(fn)
		img = img.Adjust(float32(*imgContrast))
		tess.SetImagePix(img.CPIX())
		logvf("[P%d] Recognising...", no)
		words := tess.Words()
		logvf(" %d words found.\n", len(words))
		logvf("[P%d] Adding page\n", no)
		err = doc.AddPage(fn, *img, words, *imgFormat)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}

	logvf("Writing output to '%s'...\n", outfn)

	doc.OutputAndClose(outfile)
}
<commit_msg>Tiny formatting fix<commit_after>package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/alecthomas/kingpin"

	"bitbucket.org/johnsto/ocrpdf/internal"
)

var (
	debug   bool = false
	verbose bool = false

	app = kingpin.New("ocrpdf", "OCR and PDF")

	output = app.Flag("output", "output file name").Short('o').String()

	tessData = app.Flag("tess-data", "Tesseract data directory").String()
	tessLang = app.Flag("tess-lang", "Tesseract language").String()

	docSize = app.Flag("size", "document size").
		Short('s').Default("a4").String()
	docTitle    = app.Flag("title", "document title").Short('t').String()
	docKeywords = app.Flag("keywords", "space-separated document keywords").
			Short('t').String()
	docAuthor      = app.Flag("author", "document author").Short('o').String()
	docOrientation = app.Flag("orientation", "document orientation").
			Default("auto").Short('r').Enum("auto", "portrait", "landscape")

	compress = app.Flag("compress", "compress document").
			Default("true").Short('c').Bool()

	fontName = app.Flag("font-name", "text font").
			Default("Arial").String()
	fontStyle = app.Flag("font-style", "font style, [B]old, [I]talic, [U]nderline").
			PlaceHolder(" ").
			Enum("B", "I", "U", "BI", "BU", "IU", "BIU")
	fontSize = app.Flag("font-size", "OCR layer font size").
			Default("10").Float()
	textScaling = app.Flag("scaling", "Scale text to match word boundaries").
			Default("match").Enum("off", "contain", "match")

	force = app.Flag("force", "overwrite output file").Short('f').Bool()

	imgContrast = app.Flag("contrast", "automatic contrast amount").
			Default("0.5").Float()
	imgFormat = app.Flag("format", "format to use when storing images in PDF").
			Default("auto").Enum("auto", "jpg", "png")

	input = app.Arg("input", "input image").Required().Strings()
)

func init() {
	app.Flag("debug", "enable debug mode").Short('d').BoolVar(&debug)
	app.Flag("verbose", "enable verbose mode").Short('v').BoolVar(&verbose)
}

func main() {
	kingpin.MustParse(app.Parse(os.Args[1:]))

	logv("Initialising Tesseract...")
	tess, err := internal.NewTess(*tessData, *tessLang)

	if err != nil {
		fmt.Errorf("Could not initialise Tesseract: %s\n", err)
		os.Exit(1)
	}

	doc := NewDocument(*docSize)
	doc.debug = debug
	doc.SetFont(*fontName, *fontStyle, *fontSize)
	doc.SetTextScaling(TextScaling(*textScaling))
	doc.SetTitle(*docTitle, true)
	doc.SetKeywords(*docKeywords, true)
	doc.SetAuthor(*docAuthor, true)
	doc.SetCompression(*compress)
	doc.SetOrientation(*docOrientation)

	files := *input

	if len(files) == 0 {
		fmt.Printf("No file(s) specified!\n")
		flag.Usage()
		os.Exit(1)
	}

	// When only one file is specified, output to a PDF of the same name
	outfn := *output
	if outfn == "" {
		outfn = files[0]
		ext := filepath.Ext(outfn)
		outfn = strings.TrimRight(outfn, ext) + ".pdf"
	}

	logvf("Using '%s' as output file.\n", outfn)

	openFlags := os.O_RDWR | os.O_CREATE
	if *force {
		openFlags |= os.O_TRUNC
	} else {
		openFlags |= os.O_EXCL
	}

	outfile, err := os.OpenFile(outfn, openFlags, 0666)

	if os.IsExist(err) {
		fmt.Printf("Output file '%s' already exists. Use -force to overwrite.",
			outfn)
		os.Exit(1)
	} else if err != nil {
		fmt.Printf("Couldn't create output file '%s': %s", outfn, err)
		os.Exit(1)
	}

	// Iterate through each filename specified, adding a page for each
	for i, fn := range files {
		no := i + 1
		logvf("[P%d] Reading '%s'...\n", no, fn)
		img := internal.NewImageFromFile(fn)
		img = img.Adjust(float32(*imgContrast))
		tess.SetImagePix(img.CPIX())
		logvf("[P%d] Recognising...", no)
		words := tess.Words()
		logvf(" %d words found.\n", len(words))
		logvf("[P%d] Adding page\n", no)
		err = doc.AddPage(fn, *img, words, *imgFormat)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}

	logvf("Writing output to '%s'...\n", outfn)

	doc.OutputAndClose(outfile)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Initializing Octave CPU...")

	cpu := new(CPU)
	cpu.running = true

	file, err := os.Open(os.Args[1])

	if err != nil {
		return
	}

	defer file.Close()

	stat, err := file.Stat()

	if err != nil {
		return
	}

	cpu.memory = make([]uint8, stat.Size())
	_, err = file.Read(cpu.memory)

	if err != nil {
		return
	}

	for cpu.running {
		inst_byte := fetch(cpu)
		inst_func := decode(inst_byte)
		inst_func(inst_byte, cpu)
	}
}

type CPU struct {
	memory  []uint8
	r0      uint8
	r1      uint8
	r2      uint8
	r3      uint8
	pc      uint16
	running bool
}

type instruction func(uint8, *CPU)

func fetch(cpu *CPU) uint8 {
	inst := cpu.memory[cpu.pc]
	cpu.pc = cpu.pc + 1
	return inst
}

func decode(i uint8) instruction {
	inst := illegal

	switch i >> 5 {
	case 0:
		inst = mem
	case 1:
		inst = loadi
	case 2:
		if (i << 3) < 25 {
			inst = stack
		} else {
			inst = inte
		}
	case 3:
		inst = jmp
	case 4:
		inst = math
	case 5:
		inst = logic
	case 6:
		inst = in
	case 7:
		inst = out
	}

	return inst
}

func mem(i uint8, cpu *CPU) {
	fmt.Println("mem")
}

func loadi(i uint8, cpu *CPU) {
	fmt.Println("loadi")
}

func stack(i uint8, cpu *CPU) {
	fmt.Println("stack")
}

func inte(i uint8, cpu *CPU) {
	fmt.Println("inte")
}

func jmp(i uint8, cpu *CPU) {
	if i == 96 {
		cpu.running = false
	}

	fmt.Println("jmp")
}

func math(i uint8, cpu *CPU) {
	fmt.Println("math")
}

func logic(i uint8, cpu *CPU) {
	fmt.Println("logic")
}

func in(i uint8, cpu *CPU) {
	fmt.Println("in")
}

func out(i uint8, cpu *CPU) {
	fmt.Println("out")
}

func illegal(i uint8, cpu *CPU) {
	fmt.Println("illegal")
}
<commit_msg>Removed print statements, added loadi and math instructions<commit_after>package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Initializing Octave CPU...")

	cpu := new(CPU)
	cpu.running = true
	cpu.registers = make([]uint8, 4)

	file, err := os.Open(os.Args[1])

	if err != nil {
		return
	}

	defer file.Close()

	stat, err := file.Stat()

	if err != nil {
		return
	}

	cpu.memory = make([]uint8, stat.Size())
	_, err = file.Read(cpu.memory)

	if err != nil {
		return
	}

	for cpu.running {
		inst_byte := fetch(cpu)
		inst_func := decode(inst_byte)
		inst_func(inst_byte, cpu)

		fmt.Printf("R0: %v\n", cpu.registers[0])
		fmt.Printf("R1: %v\n", cpu.registers[1])
		fmt.Printf("R2: %v\n", cpu.registers[2])
		fmt.Printf("R3: %v\n", cpu.registers[3])
		fmt.Println("")
	}
}

type CPU struct {
	memory    []uint8
	registers []uint8
	pc        uint16
	running   bool
}

type instruction func(uint8, *CPU)

func fetch(cpu *CPU) uint8 {
	inst := cpu.memory[cpu.pc]
	cpu.pc = cpu.pc + 1
	return inst
}

func decode(i uint8) instruction {
	inst := illegal

	switch i >> 5 {
	case 0:
		inst = mem
	case 1:
		inst = loadi
	case 2:
		if (i << 3) < 25 {
			inst = stack
		} else {
			inst = inte
		}
	case 3:
		inst = jmp
	case 4:
		inst = math
	case 5:
		inst = logic
	case 6:
		inst = in
	case 7:
		inst = out
	}

	return inst
}

func mem(i uint8, cpu *CPU) {
}

func loadi(i uint8, cpu *CPU) {
	cpu.registers[0] = i << 3 >> 3
}

func stack(i uint8, cpu *CPU) {
}

func inte(i uint8, cpu *CPU) {
}

func jmp(i uint8, cpu *CPU) {
	if i == 96 {
		cpu.running = false
	}
}

func math(i uint8, cpu *CPU) {
	operation := i << 3 >> 7
	destination := i << 4 >> 6
	source := i << 6 >> 6

	if operation == 0 {
		cpu.registers[destination] = cpu.registers[destination] + cpu.registers[source]
	} else {
		cpu.registers[destination] = cpu.registers[destination] / cpu.registers[source]
	}
}

func logic(i uint8, cpu *CPU) {
}

func in(i uint8, cpu *CPU) {
}

func out(i uint8, cpu *CPU) {
}

func illegal(i uint8, cpu *CPU) {
}
<|endoftext|>


<commit_before>// Ogo

package ogo

import (
	"fmt"
	"sync"
	"time"
)

type OnlineMap struct {
	lock *sync.RWMutex
	olm  map[string]*Online
}

type Online struct {
	Key  string
	Ex   time.Time
	Perm interface{}
}

var (
	OnlineCache *OnlineMap
)

func init() {
	OnlineCache = &OnlineMap{
		lock: new(sync.RWMutex),
		olm:  make(map[string]*Online),
	}
}

/* {{{ func GetOnlineKey(id string) (*Online,error)
 * 获取在线的key
 */
func GetOnlineKey(id string) (ol *Online, err error) {
	if ol = OnlineCache.Get(id); ol == nil {
		err = fmt.Errorf("not found")
	}
	return
}

/* }}} */

/* {{{ func SetOnlineKey(id string, ol *Online,p interface{}) bool
 *
 */
func SetOnlineKey(id, key string, p interface{}) bool {
	ol := &Online{
		Key:  key,
		Ex:   time.Now().Add(300 * time.Second), //缓存5分钟
		Perm: p,
	}
	return OnlineCache.Set(id, ol)
}

/* }}} */

// Maps the given key and value. Returns false
// if the key is already in the map and changes nothing.
func (m *OnlineMap) Set(k string, v *Online) bool {
	m.lock.Lock()
	defer m.lock.Unlock()
	if val, ok := m.olm[k]; !ok {
		m.olm[k] = v
	} else if val != v {
		m.olm[k] = v
	} else {
		return false
	}
	return true
}

// Get from maps return the k's value
func (m *OnlineMap) Get(k string) (ol *Online) {
	m.lock.RLock()
	defer m.lock.RUnlock()
	if val, ok := m.olm[k]; ok {
		if time.Now().Before(val.Ex) { //还没过期
			return val
		} else { //过期,删除
			m.Delete(k)
		}
	}
	return nil
}

// Delete the given key and value.
func (m *OnlineMap) Delete(k string) {
	m.lock.Lock()
	defer m.lock.Unlock()
	delete(m.olm, k)
}
<commit_msg>bugfix<commit_after>// Ogo

package ogo

import (
	"fmt"
	"sync"
	"time"
)

type OnlineMap struct {
	lock *sync.RWMutex
	olm  map[string]*Online
}

type Online struct {
	Key  string
	Ex   time.Time
	Perm interface{}
}

var (
	OnlineCache *OnlineMap
)

func init() {
	OnlineCache = &OnlineMap{
		lock: new(sync.RWMutex),
		olm:  make(map[string]*Online),
	}
}

/* {{{ func GetOnlineKey(id string) (*Online,error)
 * 获取在线的key
 */
func GetOnlineKey(id string) (ol *Online, err error) {
	if ol = OnlineCache.Get(id); ol == nil {
		err = fmt.Errorf("not found")
	}
	return
}

/* }}} */

/* {{{ func SetOnlineKey(id string, ol *Online,p interface{}) bool
 *
 */
func SetOnlineKey(id, key string, p interface{}) bool {
	ol := &Online{
		Key:  key,
		Ex:   time.Now().Add(300 * time.Second), //缓存5分钟
		Perm: p,
	}
	return OnlineCache.Set(id, ol)
}

/* }}} */

// Maps the given key and value. Returns false
// if the key is already in the map and changes nothing.
func (m *OnlineMap) Set(k string, v *Online) bool {
	m.lock.Lock()
	defer m.lock.Unlock()
	if val, ok := m.olm[k]; !ok {
		m.olm[k] = v
	} else if val != v {
		m.olm[k] = v
	} else {
		return false
	}
	return true
}

// Get from maps return the k's value
func (m *OnlineMap) Get(k string) (ol *Online) {
	m.lock.RLock()
	//defer m.lock.RUnlock()
	if val, ok := m.olm[k]; ok {
		if time.Now().Before(val.Ex) { //还没过期
			m.lock.RUnlock()
			return val
		} else { //过期,删除
			m.lock.RUnlock()
			m.Delete(k)
			return nil
		}
	}
	m.lock.RUnlock()
	return nil
}

// Delete the given key and value.
func (m *OnlineMap) Delete(k string) {
	m.lock.Lock()
	defer m.lock.Unlock()
	delete(m.olm, k)
}
<|endoftext|>


<commit_before>package dptools

import (
	"github.com/bit4bit/glivo"
	"bytes"
)

//Execute Bridge and returns the events hangup for the ALeg and BLeg of the call
func (dptools *DPTools) Bridge(endpoint string) *glivo.Event {
	var send bytes.Buffer

	send.WriteString(endpoint)

	wait_bridge := dptools.call.WaitExecute("bridge", map[string]string{
		"Event-Name": "CHANNEL_EXECUTE",
		"Application": "bridge",
	})
	dptools.call.Execute("bridge", send.String(), true)
	<-wait_bridge

	wait_action := dptools.call.OnceEventHandle("bridge_action", func(res chan interface{}) glivo.HandlerEvent {
		return glivo.NewWaitAnyEventHandle(res,
			[]map[string]string{
				{"Event-Name": "CHANNEL_UNBRIDGE"},
				{"Event-Name": "CHANNEL_HANGUP"},
				{"Event-Name": "CHANNEL_EXECUTE_COMPLETE", "Application": "bridge" },
			})
	})

	action := (<-wait_action).(glivo.Event)

	switch action.Content["Event-Name"] {
		//hangup BLeg
	case "CHANNEL_UNBRIDGE":
		return &action
	case "CHANNEL_HANGUP":
		return &action
	case "CHANNEL_EXECUTE_COMPLETE":
		return &action
	}
	panic("NOT DETECT BRIDGE END WHY?")
	return nil
}
<commit_msg>se deben agregar los filtros antes de llamar un comando<commit_after>package dptools

import (
	"github.com/bit4bit/glivo"
	"bytes"
)

//Execute Bridge and returns the events hangup for the ALeg and BLeg of the call
func (dptools *DPTools) Bridge(endpoint string) *glivo.Event {
	var send bytes.Buffer

	send.WriteString(endpoint)

	wait_bridge := dptools.call.WaitExecute("bridge", map[string]string{
		"Event-Name": "CHANNEL_EXECUTE",
		"Application": "bridge",
	})

	wait_action := dptools.call.OnceEventHandle("bridge_action", func(res chan interface{}) glivo.HandlerEvent {
		return glivo.NewWaitAnyEventHandle(res,
			[]map[string]string{
				{"Event-Name": "CHANNEL_UNBRIDGE"},
				{"Event-Name": "CHANNEL_HANGUP"},
				{"Event-Name": "CHANNEL_EXECUTE_COMPLETE", "Application": "bridge" },
			})
	})

	dptools.call.Execute("bridge", send.String(), true)
	<-wait_bridge

	action := (<-wait_action).(glivo.Event)

	switch action.Content["Event-Name"] {
		//hangup BLeg
	case "CHANNEL_UNBRIDGE":
		return &action
	case "CHANNEL_HANGUP":
		return &action
	case "CHANNEL_EXECUTE_COMPLETE":
		return &action
	}
	panic("NOT DETECT BRIDGE END WHY?")
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2016, Timothy Bogdala <tdb@animal-machine.com>
// See the LICENSE file for more details.

package openvr

/*
#cgo CFLAGS: -I${SRCDIR}/vendor/openvr/headers -std=c99
#cgo windows,386 LDFLAGS: -L${SRCDIR}/vendor/openvr/bin/win32 -lopenvr_api
#cgo windows,amd64 LDFLAGS: -L${SRCDIR}/vendor/openvr/bin/win64 -lopenvr_api
#cgo linux,amd64 LDFLAGS: -L${SRCDIR}/vendor/openvr/bin/win64 -lopenvr_api

#include <stdio.h>
#include <stdlib.h>
#include "openvr_capi.h"

#if defined(_WIN32)
    #define IMPORT __declspec(dllimport)
#else
    #define IMPORT
#endif

// lets declare some externals from the openvr_api.dll
IMPORT intptr_t VR_InitInternal( EVRInitError *peError, EVRApplicationType eType );
IMPORT const char * VR_GetVRInitErrorAsEnglishDescription( EVRInitError error );
IMPORT bool VR_IsInterfaceVersionValid(const char *interface);
IMPORT void VR_ShutdownInternal();
IMPORT intptr_t VR_GetGenericInterface( const char *pchInterfaceVersion, EVRInitError *peError );

// api tokens; set in initInternal()
intptr_t _iToken;
struct VR_IVRSystem_FnTable* _iSystem;
struct VR_IVRCompositor_FnTable* _iCompositor;
struct VR_IVRRenderModels_FnTable* _iRenderModels;

// gets the api token and makes sure the interface is valid
int initInternal(int appTypeEnum) {
    // get the api token
    EVRInitError error = EVRInitError_VRInitError_None;
    _iToken = VR_InitInternal(&error, appTypeEnum);
    if (error != EVRInitError_VRInitError_None) {
        const char* msg = VR_GetVRInitErrorAsEnglishDescription(error);
        printf("VR_InitInternal failed: %s\n", msg);
        return error;
    }

    bool icheck = VR_IsInterfaceVersionValid(IVRSystem_Version);
    if (!icheck) {
        printf("INVALID interface\n");
        VR_ShutdownInternal();
        return EVRInitError_VRInitError_Unknown;
    }

    char interfaceFnTable[256];
    sprintf(interfaceFnTable, "FnTable:%s", IVRSystem_Version);
    _iSystem = (struct VR_IVRSystem_FnTable*) VR_GetGenericInterface(interfaceFnTable, &error);
    if (error != EVRInitError_VRInitError_None) {
        const char* msg = VR_GetVRInitErrorAsEnglishDescription(error);
        printf("Error on getting IVRSystem: %s\n", msg);
        return error;
    }

    return EVRInitError_VRInitError_None;
}

int compositor_SetInternalInterface() {
    EVRInitError error = EVRInitError_VRInitError_None;
    if (_iCompositor == NULL) {
        char interfaceFnTable[256];
        sprintf(interfaceFnTable, "FnTable:%s", IVRCompositor_Version);
        _iCompositor = (struct VR_IVRCompositor_FnTable*) VR_GetGenericInterface(interfaceFnTable, &error);
        if (error != EVRInitError_VRInitError_None) {
            const char* msg = VR_GetVRInitErrorAsEnglishDescription(error);
            printf("Error on getting IVRCompositor: %s\n", msg);
            return error;
        }
    }
    return error;
}

int rendermodels_SetInternalInterface() {
    EVRInitError error = EVRInitError_VRInitError_None;
    if (_iRenderModels == NULL) {
        char interfaceFnTable[256];
        sprintf(interfaceFnTable, "FnTable:%s", IVRRenderModels_Version);
        _iRenderModels = (struct VR_IVRRenderModels_FnTable*) VR_GetGenericInterface(interfaceFnTable, &error);
        if (error != EVRInitError_VRInitError_None) {
            const char* msg = VR_GetVRInitErrorAsEnglishDescription(error);
            printf("Error on getting IVRRenderModels: %s\n", msg);
            return error;
        }
    }
    return error;
}

*/
import "C"
import (
	"fmt"
)

// Mat4 is a 4x4 matrix in column-major order
type Mat4 [16]float32

// Mat34 is a 3x4 matrix in column-major order
type Mat34 [12]float32

// Vec2 is a 2 diminensional vector of floats
type Vec2 [2]float32

// Vec3 is a 3 diminensional vector of floats
type Vec3 [3]float32

// Vec4 is a 4 diminensional vector of floats
type Vec4 [4]float32

// Init initializes the internal VR api structers and on success will
// return a System object with a valid IVRSystem interface ptr.
func Init() (*System, error) {
	// initialize the module _iToken value from the openvr api
	e := C.initInternal(C.EVRApplicationType_VRApplication_Scene)
	if e == C.EVRInitError_VRInitError_None {
		sys := new(System)
		sys.ptr = C._iSystem
		return sys, nil
	}

	errStr := GetErrorAsEnglish(int(e))
	return nil, fmt.Errorf("%s", errStr)
}

// Shutdown calls the ShutdownInternal function on the VR library.
func Shutdown() {
	C.VR_ShutdownInternal()
}

// GetErrorAsEnglish takes an EVRInitError enumeration value and returns a string.
func GetErrorAsEnglish(e int) string {
	cs := C.VR_GetVRInitErrorAsEnglishDescription(C.EVRInitError(e))
	// NOTE: does cs need to be freed somehow?
	return C.GoString(cs)
}

// GetCompositor returns a new IVRCompositor interface.
func GetCompositor() (*Compositor, error) {
	e := C.compositor_SetInternalInterface()
	if e == C.EVRInitError_VRInitError_None {
		comp := new(Compositor)
		comp.ptr = C._iCompositor
		return comp, nil
	}
	cs := C.VR_GetVRInitErrorAsEnglishDescription(C.EVRInitError(e))
	return nil, fmt.Errorf("%s", C.GoString(cs))
}

// GetRenderModels returns a new IVRRenderModels interface.
func GetRenderModels() (*RenderModels, error) {
	e := C.rendermodels_SetInternalInterface()
	if e == C.EVRInitError_VRInitError_None {
		rm := new(RenderModels)
		rm.ptr = C._iRenderModels
		return rm, nil
	}
	cs := C.VR_GetVRInitErrorAsEnglishDescription(C.EVRInitError(e))
	return nil, fmt.Errorf("%s", C.GoString(cs))
}
<commit_msg>fixed linux library linkage<commit_after>// Copyright 2016, Timothy Bogdala <tdb@animal-machine.com>
// See the LICENSE file for more details.

package openvr

/*
#cgo CFLAGS: -I${SRCDIR}/vendor/openvr/headers -std=c99
#cgo windows,386 LDFLAGS: -L${SRCDIR}/vendor/openvr/bin/win32 -lopenvr_api
#cgo windows,amd64 LDFLAGS: -L${SRCDIR}/vendor/openvr/bin/win64 -lopenvr_api
#cgo linux,amd64 LDFLAGS: -L${SRCDIR}/vendor/openvr/bin/linux64 -lopenvr_api
#cgo linux,386 LDFLAGS: -L${SRCDIR}/vendor/openvr/bin/linux32 -lopenvr_api

#include <stdio.h>
#include <stdlib.h>
#include "openvr_capi.h"

#if defined(_WIN32)
    #define IMPORT __declspec(dllimport)
#else
    #define IMPORT
#endif

// lets declare some externals from the openvr_api.dll
IMPORT intptr_t VR_InitInternal( EVRInitError *peError, EVRApplicationType eType );
IMPORT const char * VR_GetVRInitErrorAsEnglishDescription( EVRInitError error );
IMPORT bool VR_IsInterfaceVersionValid(const char *interface);
IMPORT void VR_ShutdownInternal();
IMPORT intptr_t VR_GetGenericInterface( const char *pchInterfaceVersion, EVRInitError *peError );

// api tokens; set in initInternal()
intptr_t _iToken;
struct VR_IVRSystem_FnTable* _iSystem;
struct VR_IVRCompositor_FnTable* _iCompositor;
struct VR_IVRRenderModels_FnTable* _iRenderModels;

// gets the api token and makes sure the interface is valid
int initInternal(int appTypeEnum) {
    // get the api token
    EVRInitError error = EVRInitError_VRInitError_None;
    _iToken = VR_InitInternal(&error, appTypeEnum);
    if (error != EVRInitError_VRInitError_None) {
        const char* msg = VR_GetVRInitErrorAsEnglishDescription(error);
        printf("VR_InitInternal failed: %s\n", msg);
        return error;
    }

    bool icheck = VR_IsInterfaceVersionValid(IVRSystem_Version);
    if (!icheck) {
        printf("INVALID interface\n");
        VR_ShutdownInternal();
        return EVRInitError_VRInitError_Unknown;
    }

    char interfaceFnTable[256];
    sprintf(interfaceFnTable, "FnTable:%s", IVRSystem_Version);
    _iSystem = (struct VR_IVRSystem_FnTable*) VR_GetGenericInterface(interfaceFnTable, &error);
    if (error != EVRInitError_VRInitError_None) {
        const char* msg = VR_GetVRInitErrorAsEnglishDescription(error);
        printf("Error on getting IVRSystem: %s\n", msg);
        return error;
    }

    return EVRInitError_VRInitError_None;
}

int compositor_SetInternalInterface() {
    EVRInitError error = EVRInitError_VRInitError_None;
    if (_iCompositor == NULL) {
        char interfaceFnTable[256];
        sprintf(interfaceFnTable, "FnTable:%s", IVRCompositor_Version);
        _iCompositor = (struct VR_IVRCompositor_FnTable*) VR_GetGenericInterface(interfaceFnTable, &error);
        if (error != EVRInitError_VRInitError_None) {
            const char* msg = VR_GetVRInitErrorAsEnglishDescription(error);
            printf("Error on getting IVRCompositor: %s\n", msg);
            return error;
        }
    }
    return error;
}

int rendermodels_SetInternalInterface() {
    EVRInitError error = EVRInitError_VRInitError_None;
    if (_iRenderModels == NULL) {
        char interfaceFnTable[256];
        sprintf(interfaceFnTable, "FnTable:%s", IVRRenderModels_Version);
        _iRenderModels = (struct VR_IVRRenderModels_FnTable*) VR_GetGenericInterface(interfaceFnTable, &error);
        if (error != EVRInitError_VRInitError_None) {
            const char* msg = VR_GetVRInitErrorAsEnglishDescription(error);
            printf("Error on getting IVRRenderModels: %s\n", msg);
            return error;
        }
    }
    return error;
}

*/
import "C"
import (
	"fmt"
)

// Mat4 is a 4x4 matrix in column-major order
type Mat4 [16]float32

// Mat34 is a 3x4 matrix in column-major order
type Mat34 [12]float32

// Vec2 is a 2 diminensional vector of floats
type Vec2 [2]float32

// Vec3 is a 3 diminensional vector of floats
type Vec3 [3]float32

// Vec4 is a 4 diminensional vector of floats
type Vec4 [4]float32

// Init initializes the internal VR api structers and on success will
// return a System object with a valid IVRSystem interface ptr.
func Init() (*System, error) {
	// initialize the module _iToken value from the openvr api
	e := C.initInternal(C.EVRApplicationType_VRApplication_Scene)
	if e == C.EVRInitError_VRInitError_None {
		sys := new(System)
		sys.ptr = C._iSystem
		return sys, nil
	}

	errStr := GetErrorAsEnglish(int(e))
	return nil, fmt.Errorf("%s", errStr)
}

// Shutdown calls the ShutdownInternal function on the VR library.
func Shutdown() {
	C.VR_ShutdownInternal()
}

// GetErrorAsEnglish takes an EVRInitError enumeration value and returns a string.
func GetErrorAsEnglish(e int) string {
	cs := C.VR_GetVRInitErrorAsEnglishDescription(C.EVRInitError(e))
	// NOTE: does cs need to be freed somehow?
	return C.GoString(cs)
}

// GetCompositor returns a new IVRCompositor interface.
func GetCompositor() (*Compositor, error) {
	e := C.compositor_SetInternalInterface()
	if e == C.EVRInitError_VRInitError_None {
		comp := new(Compositor)
		comp.ptr = C._iCompositor
		return comp, nil
	}
	cs := C.VR_GetVRInitErrorAsEnglishDescription(C.EVRInitError(e))
	return nil, fmt.Errorf("%s", C.GoString(cs))
}

// GetRenderModels returns a new IVRRenderModels interface.
func GetRenderModels() (*RenderModels, error) {
	e := C.rendermodels_SetInternalInterface()
	if e == C.EVRInitError_VRInitError_None {
		rm := new(RenderModels)
		rm.ptr = C._iRenderModels
		return rm, nil
	}
	cs := C.VR_GetVRInitErrorAsEnglishDescription(C.EVRInitError(e))
	return nil, fmt.Errorf("%s", C.GoString(cs))
}
<|endoftext|>