<commit_before>package rev

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"net/http"
	"reflect"
)

type Result interface {
	Apply(req *Request, resp *Response)
}

// This result handles all kinds of error codes (500, 404, ..).
// It renders the relevant error page (errors/CODE.format, e.g. errors/500.json).
// If RunMode is "dev", this results in a friendly error page.
type ErrorResult struct {
	RenderArgs map[string]interface{}
	error
}

func (r ErrorResult) Apply(req *Request, resp *Response) {
	format := req.Format
	status := resp.Status
	if status == 0 {
		status = http.StatusInternalServerError
	}

	contentType := ContentTypeByFilename("xxx." + format)
	if contentType == DefaultFileContentType {
		contentType = "text/plain"
	}

	// Get the error template.
	var err error
	templatePath := fmt.Sprintf("errors/%d.%s", status, format)
	tmpl, err := MainTemplateLoader.Template(templatePath)

	// This func shows a plaintext error message, in case the template rendering
	// doesn't work.
	showPlaintext := func(err error) {
		PlaintextErrorResult{fmt.Errorf("Server Error:\n%s\n\n"+
			"Additionally, an error occurred when rendering the error page:\n%s",
			r.error, err)}.Apply(req, resp)
	}

	if tmpl == nil {
		if err == nil {
			err = fmt.Errorf("Couldn't find template %s", templatePath)
		}
		showPlaintext(err)
		return
	}

	// If it's not a revel error, wrap it in one.
	var revelError *Error
	switch e := r.error.(type) {
	case *Error:
		revelError = e
	case error:
		revelError = &Error{
			Title:       "Server Error",
			Description: e.Error(),
		}
	}

	if revelError == nil {
		panic("no error provided")
	}

	r.RenderArgs["RunMode"] = RunMode
	r.RenderArgs["Error"] = revelError
	r.RenderArgs["Router"] = MainRouter

	// Render it.
	var b bytes.Buffer
	err = tmpl.Render(&b, r.RenderArgs)

	// If there was an error, print it in plain text.
	if err != nil {
		showPlaintext(err)
		return
	}

	resp.WriteHeader(status, contentType)
	b.WriteTo(resp.Out)
}

type PlaintextErrorResult struct {
	error
}

// This method is used when the template loader or error template is not available.
func (r PlaintextErrorResult) Apply(req *Request, resp *Response) {
	resp.WriteHeader(http.StatusInternalServerError, "text/plain")
	resp.Out.Write([]byte(r.Error()))
}

// Action methods return this result to request a template be rendered.
type RenderTemplateResult struct {
	Template   Template
	RenderArgs map[string]interface{}
}

func (r *RenderTemplateResult) Apply(req *Request, resp *Response) {
	// If "result staging" is on..
	// Render the template into a temporary buffer, to see if there was an error
	// rendering the template.  If not, then copy it into the response buffer.
	// Otherwise, template render errors may result in unpredictable HTML (and
	// would carry a 200 status code)
	if Config.BoolDefault("results.staging", true) {
		// Handle panics when rendering templates.
		defer func() {
			if err := recover(); err != nil {
				ERROR.Println(err)
				PlaintextErrorResult{fmt.Errorf("Template Execution Panic in %s:\n%s",
					r.Template.Name(), err)}.Apply(req, resp)
			}
		}()

		var b bytes.Buffer
		err := r.Template.Render(&b, r.RenderArgs)
		if err != nil {
			line, description := parseTemplateError(err)
			compileError := &Error{
				Title:       "Template Execution Error",
				Path:        r.Template.Name(),
				Description: description,
				Line:        line,
				SourceLines: r.Template.Content(),
				SourceType:  "template",
			}
			ErrorResult{r.RenderArgs, compileError}.Apply(req, resp)
			return
		}

		resp.WriteHeader(http.StatusOK, "text/html")
		b.WriteTo(resp.Out)
		return
	}

	// Else, write the status, render, and hope for the best.
	resp.WriteHeader(http.StatusOK, "text/html")
	err := r.Template.Render(resp.Out, r.RenderArgs)
	if err != nil {
		ERROR.Println("Failed to render template", r.Template.Name(), "\n", err)
	}
}

type RenderHtmlResult struct {
	html string
}

func (r RenderHtmlResult) Apply(req *Request, resp *Response) {
	resp.WriteHeader(http.StatusOK, "text/html")
	resp.Out.Write([]byte(r.html))
}

type RenderJsonResult struct {
	obj interface{}
}

func (r RenderJsonResult) Apply(req *Request, resp *Response) {
	var b []byte
	var err error
	if Config.BoolDefault("results.pretty", false) {
		b, err = json.MarshalIndent(r.obj, "", "  ")
	} else {
		b, err = json.Marshal(r.obj)
	}

	if err != nil {
		ErrorResult{error: err}.Apply(req, resp)
		return
	}

	resp.WriteHeader(http.StatusOK, "application/json")
	resp.Out.Write(b)
}

type RenderXmlResult struct {
	obj interface{}
}

func (r RenderXmlResult) Apply(req *Request, resp *Response) {
	var b []byte
	var err error
	if Config.BoolDefault("results.pretty", false) {
		b, err = xml.MarshalIndent(r.obj, "", "  ")
	} else {
		b, err = xml.Marshal(r.obj)
	}

	if err != nil {
		ErrorResult{error: err}.Apply(req, resp)
		return
	}

	resp.WriteHeader(http.StatusOK, "application/xml")
	resp.Out.Write(b)
}

type RenderTextResult struct {
	text string
}

func (r RenderTextResult) Apply(req *Request, resp *Response) {
	resp.WriteHeader(http.StatusOK, "text/plain")
	resp.Out.Write([]byte(r.text))
}

type ContentDisposition string

var (
	Attachment ContentDisposition = "attachment"
	Inline     ContentDisposition = "inline"
)

type BinaryResult struct {
	Reader   io.Reader
	Name     string
	Length   int64
	Delivery ContentDisposition
}

func (r *BinaryResult) Apply(req *Request, resp *Response) {
	disposition := string(r.Delivery)
	if r.Name != "" {
		disposition += fmt.Sprintf("; filename=%s;", r.Name)
	}
	resp.Out.Header().Set("Content-Disposition", disposition)

	if r.Length != -1 {
		resp.Out.Header().Set("Content-Length", fmt.Sprintf("%d", r.Length))
	}
	resp.WriteHeader(http.StatusOK, ContentTypeByFilename(r.Name))
	io.Copy(resp.Out, r.Reader)
}

type RedirectToUrlResult struct {
	url string
}

func (r *RedirectToUrlResult) Apply(req *Request, resp *Response) {
	resp.Out.Header().Set("Location", r.url)
	resp.WriteHeader(http.StatusFound, "")
}

type RedirectToActionResult struct {
	val interface{}
}

func (r *RedirectToActionResult) Apply(req *Request, resp *Response) {
	url, err := getRedirectUrl(r.val)
	if err != nil {
		ERROR.Println("Couldn't resolve redirect:", err.Error())
		ErrorResult{error: err}.Apply(req, resp)
		return
	}
	resp.Out.Header().Set("Location", url)
	resp.WriteHeader(http.StatusFound, "")
}

func getRedirectUrl(item interface{}) (string, error) {
	// Handle strings
	if url, ok := item.(string); ok {
		return url, nil
	}

	// Handle funcs
	val := reflect.ValueOf(item)
	typ := reflect.TypeOf(item)
	if typ.Kind() == reflect.Func && typ.NumIn() > 0 {
		// Get the Controller Method
		recvType := typ.In(0)
		method := FindMethod(recvType, &val)
		if method == nil {
			return "", errors.New("couldn't find method")
		}

		// Construct the action string (e.g. "Controller.Method")
		if recvType.Kind() == reflect.Ptr {
			recvType = recvType.Elem()
		}
		action := recvType.Name() + "." + method.Name
		actionDef := MainRouter.Reverse(action, make(map[string]string))
		if actionDef == nil {
			return "", errors.New("no route for action " + action)
		}

		return actionDef.String(), nil
	}

	// Out of guesses
	return "", errors.New("didn't recognize type: " + typ.String())
}
<commit_msg>Don't rely on builtins being exported<commit_after>package rev

import (
	"bytes"
	"encoding/json"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"net/http"
	"reflect"
)

type Result interface {
	Apply(req *Request, resp *Response)
}

// This result handles all kinds of error codes (500, 404, ..).
// It renders the relevant error page (errors/CODE.format, e.g. errors/500.json).
// If RunMode is "dev", this results in a friendly error page.
type ErrorResult struct {
	RenderArgs map[string]interface{}
	Error      error
}

func (r ErrorResult) Apply(req *Request, resp *Response) {
	format := req.Format
	status := resp.Status
	if status == 0 {
		status = http.StatusInternalServerError
	}

	contentType := ContentTypeByFilename("xxx." + format)
	if contentType == DefaultFileContentType {
		contentType = "text/plain"
	}

	// Get the error template.
	var err error
	templatePath := fmt.Sprintf("errors/%d.%s", status, format)
	tmpl, err := MainTemplateLoader.Template(templatePath)

	// This func shows a plaintext error message, in case the template rendering
	// doesn't work.
	showPlaintext := func(err error) {
		PlaintextErrorResult{fmt.Errorf("Server Error:\n%s\n\n"+
			"Additionally, an error occurred when rendering the error page:\n%s",
			r.Error, err)}.Apply(req, resp)
	}

	if tmpl == nil {
		if err == nil {
			err = fmt.Errorf("Couldn't find template %s", templatePath)
		}
		showPlaintext(err)
		return
	}

	// If it's not a revel error, wrap it in one.
	var revelError *Error
	switch e := r.Error.(type) {
	case *Error:
		revelError = e
	case error:
		revelError = &Error{
			Title:       "Server Error",
			Description: e.Error(),
		}
	}

	if revelError == nil {
		panic("no error provided")
	}

	r.RenderArgs["RunMode"] = RunMode
	r.RenderArgs["Error"] = revelError
	r.RenderArgs["Router"] = MainRouter

	// Render it.
	var b bytes.Buffer
	err = tmpl.Render(&b, r.RenderArgs)

	// If there was an error, print it in plain text.
	if err != nil {
		showPlaintext(err)
		return
	}

	resp.WriteHeader(status, contentType)
	b.WriteTo(resp.Out)
}

type PlaintextErrorResult struct {
	Error error
}

// This method is used when the template loader or error template is not available.
func (r PlaintextErrorResult) Apply(req *Request, resp *Response) {
	resp.WriteHeader(http.StatusInternalServerError, "text/plain")
	resp.Out.Write([]byte(r.Error.Error()))
}

// Action methods return this result to request a template be rendered.
type RenderTemplateResult struct {
	Template   Template
	RenderArgs map[string]interface{}
}

func (r *RenderTemplateResult) Apply(req *Request, resp *Response) {
	// If "result staging" is on..
	// Render the template into a temporary buffer, to see if there was an error
	// rendering the template.  If not, then copy it into the response buffer.
	// Otherwise, template render errors may result in unpredictable HTML (and
	// would carry a 200 status code)
	if Config.BoolDefault("results.staging", true) {
		// Handle panics when rendering templates.
		defer func() {
			if err := recover(); err != nil {
				ERROR.Println(err)
				PlaintextErrorResult{fmt.Errorf("Template Execution Panic in %s:\n%s",
					r.Template.Name(), err)}.Apply(req, resp)
			}
		}()

		var b bytes.Buffer
		err := r.Template.Render(&b, r.RenderArgs)
		if err != nil {
			line, description := parseTemplateError(err)
			compileError := &Error{
				Title:       "Template Execution Error",
				Path:        r.Template.Name(),
				Description: description,
				Line:        line,
				SourceLines: r.Template.Content(),
				SourceType:  "template",
			}
			ErrorResult{r.RenderArgs, compileError}.Apply(req, resp)
			return
		}

		resp.WriteHeader(http.StatusOK, "text/html")
		b.WriteTo(resp.Out)
		return
	}

	// Else, write the status, render, and hope for the best.
	resp.WriteHeader(http.StatusOK, "text/html")
	err := r.Template.Render(resp.Out, r.RenderArgs)
	if err != nil {
		ERROR.Println("Failed to render template", r.Template.Name(), "\n", err)
	}
}

type RenderHtmlResult struct {
	html string
}

func (r RenderHtmlResult) Apply(req *Request, resp *Response) {
	resp.WriteHeader(http.StatusOK, "text/html")
	resp.Out.Write([]byte(r.html))
}

type RenderJsonResult struct {
	obj interface{}
}

func (r RenderJsonResult) Apply(req *Request, resp *Response) {
	var b []byte
	var err error
	if Config.BoolDefault("results.pretty", false) {
		b, err = json.MarshalIndent(r.obj, "", "  ")
	} else {
		b, err = json.Marshal(r.obj)
	}

	if err != nil {
		ErrorResult{Error: err}.Apply(req, resp)
		return
	}

	resp.WriteHeader(http.StatusOK, "application/json")
	resp.Out.Write(b)
}

type RenderXmlResult struct {
	obj interface{}
}

func (r RenderXmlResult) Apply(req *Request, resp *Response) {
	var b []byte
	var err error
	if Config.BoolDefault("results.pretty", false) {
		b, err = xml.MarshalIndent(r.obj, "", "  ")
	} else {
		b, err = xml.Marshal(r.obj)
	}

	if err != nil {
		ErrorResult{Error: err}.Apply(req, resp)
		return
	}

	resp.WriteHeader(http.StatusOK, "application/xml")
	resp.Out.Write(b)
}

type RenderTextResult struct {
	text string
}

func (r RenderTextResult) Apply(req *Request, resp *Response) {
	resp.WriteHeader(http.StatusOK, "text/plain")
	resp.Out.Write([]byte(r.text))
}

type ContentDisposition string

var (
	Attachment ContentDisposition = "attachment"
	Inline     ContentDisposition = "inline"
)

type BinaryResult struct {
	Reader   io.Reader
	Name     string
	Length   int64
	Delivery ContentDisposition
}

func (r *BinaryResult) Apply(req *Request, resp *Response) {
	disposition := string(r.Delivery)
	if r.Name != "" {
		disposition += fmt.Sprintf("; filename=%s;", r.Name)
	}
	resp.Out.Header().Set("Content-Disposition", disposition)

	if r.Length != -1 {
		resp.Out.Header().Set("Content-Length", fmt.Sprintf("%d", r.Length))
	}
	resp.WriteHeader(http.StatusOK, ContentTypeByFilename(r.Name))
	io.Copy(resp.Out, r.Reader)
}

type RedirectToUrlResult struct {
	url string
}

func (r *RedirectToUrlResult) Apply(req *Request, resp *Response) {
	resp.Out.Header().Set("Location", r.url)
	resp.WriteHeader(http.StatusFound, "")
}

type RedirectToActionResult struct {
	val interface{}
}

func (r *RedirectToActionResult) Apply(req *Request, resp *Response) {
	url, err := getRedirectUrl(r.val)
	if err != nil {
		ERROR.Println("Couldn't resolve redirect:", err.Error())
		ErrorResult{Error: err}.Apply(req, resp)
		return
	}
	resp.Out.Header().Set("Location", url)
	resp.WriteHeader(http.StatusFound, "")
}

func getRedirectUrl(item interface{}) (string, error) {
	// Handle strings
	if url, ok := item.(string); ok {
		return url, nil
	}

	// Handle funcs
	val := reflect.ValueOf(item)
	typ := reflect.TypeOf(item)
	if typ.Kind() == reflect.Func && typ.NumIn() > 0 {
		// Get the Controller Method
		recvType := typ.In(0)
		method := FindMethod(recvType, &val)
		if method == nil {
			return "", errors.New("couldn't find method")
		}

		// Construct the action string (e.g. "Controller.Method")
		if recvType.Kind() == reflect.Ptr {
			recvType = recvType.Elem()
		}
		action := recvType.Name() + "." + method.Name
		actionDef := MainRouter.Reverse(action, make(map[string]string))
		if actionDef == nil {
			return "", errors.New("no route for action " + action)
		}

		return actionDef.String(), nil
	}

	// Out of guesses
	return "", errors.New("didn't recognize type: " + typ.String())
}
<|endoftext|>


<commit_before>// Copyright © 2015 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

package components

import (
	"fmt"
	"github.com/thethingsnetwork/core"
	"github.com/thethingsnetwork/core/utils/log"
	"time"
)

const (
	EXPIRY_DELAY = time.Hour * 8
)

type Router struct {
	loggers []log.Logger
	brokers []core.Recipient
	db      addressKeeper // Local storage that maps end-device addresses to broker addresses
}

var ErrBadOptions = fmt.Errorf("Invalid supplied options")
var ErrNotInitialized = fmt.Errorf("Illegal operation call on non initialized component")

// NewRouter constructs a Router and setup its internal structure
func NewRouter(brokers []core.Recipient, loggers ...log.Logger) (*Router, error) {
	localDB, err := NewLocalDB(EXPIRY_DELAY)

	if err != nil {
		return nil, err
	}

	if len(brokers) == 0 {
		return nil, ErrBadOptions
	}

	return &Router{
		loggers: loggers,
		brokers: brokers,
		db:      localDB,
	}, nil
}

// Register implements the core.Component interface
func (r *Router) Register(reg core.Registration) error {
	if !r.ok() {
		return ErrNotInitialized
	}
	return r.db.store(reg.DevAddr, reg.Recipient)
}

// ok ensure the router has been initialized by NewRouter()
func (r *Router) ok() bool {
	return r == nil && r.db != nil
}

// log broadcast the log message to all registered logger
func (r *Router) log(format string, i ...interface{}) {
	for _, logger := range r.loggers {
		logger.Log(format, i...)
	}
}
<commit_msg>[broker] Add dump-implementation of Router.HandleDown()<commit_after>// Copyright © 2015 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

package components

import (
	"fmt"
	"github.com/thethingsnetwork/core"
	"github.com/thethingsnetwork/core/utils/log"
	"time"
)

const (
	EXPIRY_DELAY = time.Hour * 8
)

type Router struct {
	loggers []log.Logger
	brokers []core.Recipient
	db      addressKeeper // Local storage that maps end-device addresses to broker addresses
}

var ErrBadOptions = fmt.Errorf("Invalid supplied options")
var ErrNotInitialized = fmt.Errorf("Illegal operation call on non initialized component")

// NewRouter constructs a Router and setup its internal structure
func NewRouter(brokers []core.Recipient, loggers ...log.Logger) (*Router, error) {
	localDB, err := NewLocalDB(EXPIRY_DELAY)

	if err != nil {
		return nil, err
	}

	if len(brokers) == 0 {
		return nil, ErrBadOptions
	}

	return &Router{
		loggers: loggers,
		brokers: brokers,
		db:      localDB,
	}, nil
}

// Register implements the core.Component interface
func (r *Router) Register(reg core.Registration) error {
	if !r.ok() {
		return ErrNotInitialized
	}
	return r.db.store(reg.DevAddr, reg.Recipient)
}

// HandleDown implements the core.Component interface
func (r *Router) HandleDown(p core.Packet, an core.AckNacker) error {
	return fmt.Errorf("TODO. Not Implemented")
}

// ok ensure the router has been initialized by NewRouter()
func (r *Router) ok() bool {
	return r == nil && r.db != nil
}

// log broadcast the log message to all registered logger
func (r *Router) log(format string, i ...interface{}) {
	for _, logger := range r.loggers {
		logger.Log(format, i...)
	}
}
<|endoftext|>


<commit_before>// +build linux

package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/opencontainers/runc/libcontainer"
	"github.com/opencontainers/runc/libcontainer/utils"
	"github.com/opencontainers/runtime-spec/specs-go"
	"github.com/urfave/cli"
)

var execCommand = cli.Command{
	Name:  "exec",
	Usage: "execute new process inside the container",
	ArgsUsage: `<container-id> <command> [command options]  || -p process.json <container-id>

Where "<container-id>" is the name for the instance of the container and
"<command>" is the command to be executed in the container.
"<command>" can't be empty unless a "-p" flag provided.

EXAMPLE:
For example, if the container is configured to run the linux ps command the
following will output a list of processes running in the container:

       # runc exec <container-id> ps`,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "console-socket",
			Usage: "path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal",
		},
		cli.StringFlag{
			Name:  "cwd",
			Usage: "current working directory in the container",
		},
		cli.StringSliceFlag{
			Name:  "env, e",
			Usage: "set environment variables",
		},
		cli.BoolFlag{
			Name:  "tty, t",
			Usage: "allocate a pseudo-TTY",
		},
		cli.StringFlag{
			Name:  "user, u",
			Usage: "UID (format: <uid>[:<gid>])",
		},
		cli.Int64SliceFlag{
			Name:  "additional-gids, g",
			Usage: "additional gids",
		},
		cli.StringFlag{
			Name:  "process, p",
			Usage: "path to the process.json",
		},
		cli.BoolFlag{
			Name:  "detach,d",
			Usage: "detach from the container's process",
		},
		cli.StringFlag{
			Name:  "pid-file",
			Value: "",
			Usage: "specify the file to write the process id to",
		},
		cli.StringFlag{
			Name:  "process-label",
			Usage: "set the asm process label for the process commonly used with selinux",
		},
		cli.StringFlag{
			Name:  "apparmor",
			Usage: "set the apparmor profile for the process",
		},
		cli.BoolFlag{
			Name:  "no-new-privs",
			Usage: "set the no new privileges value for the process",
		},
		cli.StringSliceFlag{
			Name:  "cap, c",
			Value: &cli.StringSlice{},
			Usage: "add a capability to the bounding set for the process",
		},
		cli.BoolFlag{
			Name:   "no-subreaper",
			Usage:  "disable the use of the subreaper used to reap reparented processes",
			Hidden: true,
		},
		cli.IntFlag{
			Name:  "preserve-fds",
			Usage: "Pass N additional file descriptors to the container (stdio + $LISTEN_FDS + N in total)",
		},
	},
	Action: func(context *cli.Context) error {
		if err := checkArgs(context, 1, minArgs); err != nil {
			return err
		}
		if err := revisePidFile(context); err != nil {
			return err
		}
		status, err := execProcess(context)
		if err == nil {
			os.Exit(status)
		}
		return fmt.Errorf("exec failed: %v", err)
	},
	SkipArgReorder: true,
}

func execProcess(context *cli.Context) (int, error) {
	container, err := getContainer(context)
	if err != nil {
		return -1, err
	}
	status, err := container.Status()
	if err != nil {
		return -1, err
	}
	if status == libcontainer.Stopped {
		return -1, fmt.Errorf("cannot exec a container that has stopped")
	}
	path := context.String("process")
	if path == "" && len(context.Args()) == 1 {
		return -1, fmt.Errorf("process args cannot be empty")
	}
	detach := context.Bool("detach")
	state, err := container.State()
	if err != nil {
		return -1, err
	}
	bundle := utils.SearchLabels(state.Config.Labels, "bundle")
	p, err := getProcess(context, bundle)
	if err != nil {
		return -1, err
	}

	logLevel := "info"
	if context.GlobalBool("debug") {
		logLevel = "debug"
	}

	r := &runner{
		enableSubreaper: false,
		shouldDestroy:   false,
		container:       container,
		consoleSocket:   context.String("console-socket"),
		detach:          detach,
		pidFile:         context.String("pid-file"),
		action:          CT_ACT_RUN,
		init:            false,
		preserveFDs:     context.Int("preserve-fds"),
		logLevel:        logLevel,
	}
	return r.run(p)
}

func getProcess(context *cli.Context, bundle string) (*specs.Process, error) {
	if path := context.String("process"); path != "" {
		f, err := os.Open(path)
		if err != nil {
			return nil, err
		}
		defer f.Close()
		var p specs.Process
		if err := json.NewDecoder(f).Decode(&p); err != nil {
			return nil, err
		}
		return &p, validateProcessSpec(&p)
	}
	// process via cli flags
	if err := os.Chdir(bundle); err != nil {
		return nil, err
	}
	spec, err := loadSpec(specConfig)
	if err != nil {
		return nil, err
	}
	p := spec.Process
	p.Args = context.Args()[1:]
	// override the cwd, if passed
	if context.String("cwd") != "" {
		p.Cwd = context.String("cwd")
	}
	if ap := context.String("apparmor"); ap != "" {
		p.ApparmorProfile = ap
	}
	if l := context.String("process-label"); l != "" {
		p.SelinuxLabel = l
	}
	if caps := context.StringSlice("cap"); len(caps) > 0 {
		for _, c := range caps {
			p.Capabilities.Bounding = append(p.Capabilities.Bounding, c)
			p.Capabilities.Inheritable = append(p.Capabilities.Inheritable, c)
			p.Capabilities.Effective = append(p.Capabilities.Effective, c)
			p.Capabilities.Permitted = append(p.Capabilities.Permitted, c)
			p.Capabilities.Ambient = append(p.Capabilities.Ambient, c)
		}
	}
	// append the passed env variables
	p.Env = append(p.Env, context.StringSlice("env")...)

	// set the tty
	p.Terminal = false
	if context.IsSet("tty") {
		p.Terminal = context.Bool("tty")
	}
	if context.IsSet("no-new-privs") {
		p.NoNewPrivileges = context.Bool("no-new-privs")
	}
	// override the user, if passed
	if context.String("user") != "" {
		u := strings.SplitN(context.String("user"), ":", 2)
		if len(u) > 1 {
			gid, err := strconv.Atoi(u[1])
			if err != nil {
				return nil, fmt.Errorf("parsing %s as int for gid failed: %v", u[1], err)
			}
			p.User.GID = uint32(gid)
		}
		uid, err := strconv.Atoi(u[0])
		if err != nil {
			return nil, fmt.Errorf("parsing %s as int for uid failed: %v", u[0], err)
		}
		p.User.UID = uint32(uid)
	}
	for _, gid := range context.Int64Slice("additional-gids") {
		if gid < 0 {
			return nil, fmt.Errorf("additional-gids must be a positive number %d", gid)
		}
		p.User.AdditionalGids = append(p.User.AdditionalGids, uint32(gid))
	}
	return p, validateProcessSpec(p)
}
<commit_msg>exec: rm --no-subreaper flag<commit_after>// +build linux

package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/opencontainers/runc/libcontainer"
	"github.com/opencontainers/runc/libcontainer/utils"
	"github.com/opencontainers/runtime-spec/specs-go"
	"github.com/urfave/cli"
)

var execCommand = cli.Command{
	Name:  "exec",
	Usage: "execute new process inside the container",
	ArgsUsage: `<container-id> <command> [command options]  || -p process.json <container-id>

Where "<container-id>" is the name for the instance of the container and
"<command>" is the command to be executed in the container.
"<command>" can't be empty unless a "-p" flag provided.

EXAMPLE:
For example, if the container is configured to run the linux ps command the
following will output a list of processes running in the container:

       # runc exec <container-id> ps`,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "console-socket",
			Usage: "path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal",
		},
		cli.StringFlag{
			Name:  "cwd",
			Usage: "current working directory in the container",
		},
		cli.StringSliceFlag{
			Name:  "env, e",
			Usage: "set environment variables",
		},
		cli.BoolFlag{
			Name:  "tty, t",
			Usage: "allocate a pseudo-TTY",
		},
		cli.StringFlag{
			Name:  "user, u",
			Usage: "UID (format: <uid>[:<gid>])",
		},
		cli.Int64SliceFlag{
			Name:  "additional-gids, g",
			Usage: "additional gids",
		},
		cli.StringFlag{
			Name:  "process, p",
			Usage: "path to the process.json",
		},
		cli.BoolFlag{
			Name:  "detach,d",
			Usage: "detach from the container's process",
		},
		cli.StringFlag{
			Name:  "pid-file",
			Value: "",
			Usage: "specify the file to write the process id to",
		},
		cli.StringFlag{
			Name:  "process-label",
			Usage: "set the asm process label for the process commonly used with selinux",
		},
		cli.StringFlag{
			Name:  "apparmor",
			Usage: "set the apparmor profile for the process",
		},
		cli.BoolFlag{
			Name:  "no-new-privs",
			Usage: "set the no new privileges value for the process",
		},
		cli.StringSliceFlag{
			Name:  "cap, c",
			Value: &cli.StringSlice{},
			Usage: "add a capability to the bounding set for the process",
		},
		cli.IntFlag{
			Name:  "preserve-fds",
			Usage: "Pass N additional file descriptors to the container (stdio + $LISTEN_FDS + N in total)",
		},
	},
	Action: func(context *cli.Context) error {
		if err := checkArgs(context, 1, minArgs); err != nil {
			return err
		}
		if err := revisePidFile(context); err != nil {
			return err
		}
		status, err := execProcess(context)
		if err == nil {
			os.Exit(status)
		}
		return fmt.Errorf("exec failed: %v", err)
	},
	SkipArgReorder: true,
}

func execProcess(context *cli.Context) (int, error) {
	container, err := getContainer(context)
	if err != nil {
		return -1, err
	}
	status, err := container.Status()
	if err != nil {
		return -1, err
	}
	if status == libcontainer.Stopped {
		return -1, fmt.Errorf("cannot exec a container that has stopped")
	}
	path := context.String("process")
	if path == "" && len(context.Args()) == 1 {
		return -1, fmt.Errorf("process args cannot be empty")
	}
	detach := context.Bool("detach")
	state, err := container.State()
	if err != nil {
		return -1, err
	}
	bundle := utils.SearchLabels(state.Config.Labels, "bundle")
	p, err := getProcess(context, bundle)
	if err != nil {
		return -1, err
	}

	logLevel := "info"
	if context.GlobalBool("debug") {
		logLevel = "debug"
	}

	r := &runner{
		enableSubreaper: false,
		shouldDestroy:   false,
		container:       container,
		consoleSocket:   context.String("console-socket"),
		detach:          detach,
		pidFile:         context.String("pid-file"),
		action:          CT_ACT_RUN,
		init:            false,
		preserveFDs:     context.Int("preserve-fds"),
		logLevel:        logLevel,
	}
	return r.run(p)
}

func getProcess(context *cli.Context, bundle string) (*specs.Process, error) {
	if path := context.String("process"); path != "" {
		f, err := os.Open(path)
		if err != nil {
			return nil, err
		}
		defer f.Close()
		var p specs.Process
		if err := json.NewDecoder(f).Decode(&p); err != nil {
			return nil, err
		}
		return &p, validateProcessSpec(&p)
	}
	// process via cli flags
	if err := os.Chdir(bundle); err != nil {
		return nil, err
	}
	spec, err := loadSpec(specConfig)
	if err != nil {
		return nil, err
	}
	p := spec.Process
	p.Args = context.Args()[1:]
	// override the cwd, if passed
	if context.String("cwd") != "" {
		p.Cwd = context.String("cwd")
	}
	if ap := context.String("apparmor"); ap != "" {
		p.ApparmorProfile = ap
	}
	if l := context.String("process-label"); l != "" {
		p.SelinuxLabel = l
	}
	if caps := context.StringSlice("cap"); len(caps) > 0 {
		for _, c := range caps {
			p.Capabilities.Bounding = append(p.Capabilities.Bounding, c)
			p.Capabilities.Inheritable = append(p.Capabilities.Inheritable, c)
			p.Capabilities.Effective = append(p.Capabilities.Effective, c)
			p.Capabilities.Permitted = append(p.Capabilities.Permitted, c)
			p.Capabilities.Ambient = append(p.Capabilities.Ambient, c)
		}
	}
	// append the passed env variables
	p.Env = append(p.Env, context.StringSlice("env")...)

	// set the tty
	p.Terminal = false
	if context.IsSet("tty") {
		p.Terminal = context.Bool("tty")
	}
	if context.IsSet("no-new-privs") {
		p.NoNewPrivileges = context.Bool("no-new-privs")
	}
	// override the user, if passed
	if context.String("user") != "" {
		u := strings.SplitN(context.String("user"), ":", 2)
		if len(u) > 1 {
			gid, err := strconv.Atoi(u[1])
			if err != nil {
				return nil, fmt.Errorf("parsing %s as int for gid failed: %v", u[1], err)
			}
			p.User.GID = uint32(gid)
		}
		uid, err := strconv.Atoi(u[0])
		if err != nil {
			return nil, fmt.Errorf("parsing %s as int for uid failed: %v", u[0], err)
		}
		p.User.UID = uint32(uid)
	}
	for _, gid := range context.Int64Slice("additional-gids") {
		if gid < 0 {
			return nil, fmt.Errorf("additional-gids must be a positive number %d", gid)
		}
		p.User.AdditionalGids = append(p.User.AdditionalGids, uint32(gid))
	}
	return p, validateProcessSpec(p)
}
<|endoftext|>


<commit_before>package origins

import (
	"fmt"
	"strings"
	"time"
)

// Operation denotes the validity of a fact. A fact can be asserted in which
// case it is deemed valid and true or retracted which denotes the fact is no
// longer valid or true. A fact may be retracted without being asserted first.
// This denotes some fact is known not to be true without necessarily knowing
// what is true.
type Operation int8

func (o Operation) String() string {
	switch o {
	case Assertion:
		return "assert"
	case Retraction:
		return "retract"
	default:
		return ""
	}
}

const (
	Noop Operation = iota
	Assertion
	Retraction
)

// ParseOperation normalizes the string operation denoting an assertion
// or retraction of a fact.
func ParseOperation(s string) (Operation, error) {
	switch strings.ToLower(s) {
	case "", "assert", "asserted", "a":
		return Assertion, nil
	case "retract", "retracted", "r":
		return Retraction, nil
	}

	return Noop, fmt.Errorf("fact: invalid operation `%s`", s)
}

// Fact is the fundamental unit of the information model. It is an immutable
// declaration of something that is true.
type Fact struct {
	// Denotes whether the fact is asserted or retracted.
	Operation Operation

	// The domain the fact applies to. The motivation is to enable asserting
	// facts about entities in different domains. This model decouples content
	// from context to support auxillary information.
	Domain string

	// The entity, attribute, and value of the fact. Also referred to as a
	// "triple", these make up the content of the fact. The entity and attribute
	// must have a domain associated with it. If not specified, they default to
	// the fact domain. If a value has a domain specified, it will be interpreted
	// as a reference to an entity, otherwise it will be treated as a literal.
	Entity    *Ident
	Attribute *Ident
	Value     *Ident

	// The time the fact is true in the world. Also known as the "valid time",
	// this can be set if the fact is true at an earlier or later time than
	// when it was added.
	Time time.Time

	// Transaction that processed this fact. The transaction serves as the
	// temporal component of the fact. Time-travel queries rely on the
	// transaction time to filter out facts not applicable in the specified
	// time range.
	Transaction uint64
}

// String returns a string representation of the fact.
func (f *Fact) String() string {
	return fmt.Sprintf("(%s %s %s %s)", f.Operation, f.Entity, f.Attribute, f.Value)
}

func parseIdent(id interface{}) (*Ident, error) {
	switch x := id.(type) {
	case *Ident:
		return x, nil
	case string:
		return ParseIdent(x)
	}

	return nil, fmt.Errorf("ident: cannot parse %v", id)
}

func parseFact(op Operation, e, a, v interface{}, t time.Time) (*Fact, error) {
	var (
		err           error
		eid, aid, vid *Ident
	)

	if eid, err = parseIdent(e); err != nil {
		return nil, err
	}

	if aid, err = parseIdent(a); err != nil {
		return nil, err
	}

	if vid, err = parseIdent(v); err != nil {
		return nil, err
	}

	return &Fact{
		Operation: op,
		Entity:    eid,
		Attribute: aid,
		Value:     vid,
		Time:      t,
	}, nil
}

// Assert returns an asserted fact. The EAV values can be strings or Ident values.
func Assert(e, a, v interface{}) (*Fact, error) {
	return parseFact(Assertion, e, a, v, time.Time{})
}

// Retract returns a retracted fact. The EAV values can be strings or Ident values.
func Retract(e, a, v interface{}) (*Fact, error) {
	return parseFact(Retraction, e, a, v, time.Time{})
}

// AssertForTime returns an asserted fact at a specified time.
func AssertForTime(e, a, v interface{}, t time.Time) (*Fact, error) {
	return parseFact(Assertion, e, a, v, t)
}

// RetractForTime returns a retracted fact at a specified time.
func RetractForTime(e, a, v interface{}, t time.Time) (*Fact, error) {
	return parseFact(Retraction, e, a, v, t)
}

// Facts is a slice of facts.
type Facts []*Fact

func (fs Facts) String() string {
	toks := make([]string, len(fs))

	for i, f := range fs {
		toks[i] = f.String()
	}

	return strings.Join(toks, "\n")
}
<commit_msg>Implement json.Marshaler for Operation<commit_after>package origins

import (
	"encoding/json"
	"fmt"
	"strings"
	"time"
)

// Operation denotes the validity of a fact. A fact can be asserted in which
// case it is deemed valid and true or retracted which denotes the fact is no
// longer valid or true. A fact may be retracted without being asserted first.
// This denotes some fact is known not to be true without necessarily knowing
// what is true.
type Operation int8

func (o Operation) String() string {
	switch o {
	case Assertion:
		return "assert"
	case Retraction:
		return "retract"
	default:
		return ""
	}
}

func (o Operation) MarshalJSON() ([]byte, error) {
	return json.Marshal(o.String())
}

const (
	Noop Operation = iota
	Assertion
	Retraction
)

// ParseOperation normalizes the string operation denoting an assertion
// or retraction of a fact.
func ParseOperation(s string) (Operation, error) {
	switch strings.ToLower(s) {
	case "", "assert", "asserted", "a":
		return Assertion, nil
	case "retract", "retracted", "r":
		return Retraction, nil
	}

	return Noop, fmt.Errorf("fact: invalid operation `%s`", s)
}

// Fact is the fundamental unit of the information model. It is an immutable
// declaration of something that is true.
type Fact struct {
	// Denotes whether the fact is asserted or retracted.
	Operation Operation

	// The domain the fact applies to. The motivation is to enable asserting
	// facts about entities in different domains. This model decouples content
	// from context to support auxillary information.
	Domain string

	// The entity, attribute, and value of the fact. Also referred to as a
	// "triple", these make up the content of the fact. The entity and attribute
	// must have a domain associated with it. If not specified, they default to
	// the fact domain. If a value has a domain specified, it will be interpreted
	// as a reference to an entity, otherwise it will be treated as a literal.
	Entity    *Ident
	Attribute *Ident
	Value     *Ident

	// The time the fact is true in the world. Also known as the "valid time",
	// this can be set if the fact is true at an earlier or later time than
	// when it was added.
	Time time.Time

	// Transaction that processed this fact. The transaction serves as the
	// temporal component of the fact. Time-travel queries rely on the
	// transaction time to filter out facts not applicable in the specified
	// time range.
	Transaction uint64
}

// String returns a string representation of the fact.
func (f *Fact) String() string {
	return fmt.Sprintf("(%s %s %s %s)", f.Operation, f.Entity, f.Attribute, f.Value)
}

func parseIdent(id interface{}) (*Ident, error) {
	switch x := id.(type) {
	case *Ident:
		return x, nil
	case string:
		return ParseIdent(x)
	}

	return nil, fmt.Errorf("ident: cannot parse %v", id)
}

func parseFact(op Operation, e, a, v interface{}, t time.Time) (*Fact, error) {
	var (
		err           error
		eid, aid, vid *Ident
	)

	if eid, err = parseIdent(e); err != nil {
		return nil, err
	}

	if aid, err = parseIdent(a); err != nil {
		return nil, err
	}

	if vid, err = parseIdent(v); err != nil {
		return nil, err
	}

	return &Fact{
		Operation: op,
		Entity:    eid,
		Attribute: aid,
		Value:     vid,
		Time:      t,
	}, nil
}

// Assert returns an asserted fact. The EAV values can be strings or Ident values.
func Assert(e, a, v interface{}) (*Fact, error) {
	return parseFact(Assertion, e, a, v, time.Time{})
}

// Retract returns a retracted fact. The EAV values can be strings or Ident values.
func Retract(e, a, v interface{}) (*Fact, error) {
	return parseFact(Retraction, e, a, v, time.Time{})
}

// AssertForTime returns an asserted fact at a specified time.
func AssertForTime(e, a, v interface{}, t time.Time) (*Fact, error) {
	return parseFact(Assertion, e, a, v, t)
}

// RetractForTime returns a retracted fact at a specified time.
func RetractForTime(e, a, v interface{}, t time.Time) (*Fact, error) {
	return parseFact(Retraction, e, a, v, t)
}

// Facts is a slice of facts.
type Facts []*Fact

func (fs Facts) String() string {
	toks := make([]string, len(fs))

	for i, f := range fs {
		toks[i] = f.String()
	}

	return strings.Join(toks, "\n")
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"strings"
)

// D3JSON is the JSON string that the frontend requests for sourcing graph data.
// It is served directly from memory via a custom http route.
var D3JSON string

// MarshalToMemory converts a JSON object to a string and saves it in-memory, in the `D3JSON` variable.
func MarshalToMemory(d3Data D3) {
	d3JSON, err := json.MarshalIndent(d3Data, "", "  ")
	if err != nil {
		log.Fatalf("Unable to marshal graph data to in-memory JSON: %s", err.Error())
	}
	D3JSON = strings.Replace(string(d3JSON), "null", "{}", -1)
}

// MarshalToFile converts a JSON object to a string and saves it in a file, specified by the `filePath` string.
func MarshalToFile(d3Data D3, filePath string) {
	d3JSON, err := json.MarshalIndent(d3Data, "", "  ")
	if err != nil {
		log.Fatalf("Unable to marshal graph data to JSON file: %s", err.Error())
	}
	d3JSON = []byte(strings.Replace(string(d3JSON), "null", "{}", -1))
	err = ioutil.WriteFile(filePath, d3JSON, 0644)
	if err != nil {
		log.Fatalf("Unable to write marshalled JSON to file \"%s\": %s", filePath, err.Error())
	}
}<commit_msg>Deprecated method removal<commit_after>package main

import (
	"encoding/json"
	"log"
	"strings"
)

// D3JSON is the JSON string that the frontend requests for sourcing graph data.
// It is served directly from memory via a custom http route.
var D3JSON string

// MarshalToMemory converts a JSON object to a string and saves it in-memory, in the `D3JSON` variable.
func MarshalToMemory(d3Data D3) {
	d3JSON, err := json.MarshalIndent(d3Data, "", "  ")
	if err != nil {
		log.Fatalf("Unable to marshal graph data to in-memory JSON: %s", err.Error())
	}
	D3JSON = strings.Replace(string(d3JSON), "null", "{}", -1)
}<|endoftext|>


<commit_before>package fuseklient

import (
	"io"
	"time"

	"github.com/jacobsa/fuse/fuseutil"
	"github.com/koding/fuseklient/transport"
)

// File represents a file system file and implements Node interface.
type File struct {
	// Entry is generic structure that contains commonality between File and Dir.
	*Entry

	////// Entry#RWLock protects the fields below.

	// IsDirty indicates if File has been written to, but not yet been synced
	// with remote.
	IsDirty bool

	// Content is the remotely fetched contents of the File.
	Content []byte
}

// NewFile is the required initializeChild for File. If internal cache is empty,
// it'll fetch from remote.
func NewFile(n *Entry) *File {
	return &File{Entry: n, Content: []byte{}}
}

// ReadAt returns contents of file at specified offset.
func (f *File) ReadAt(offset int64) ([]byte, error) {
	f.Lock()
	defer f.Unlock()

	// fetch from remote is no content
	if len(f.Content) == 0 {
		if err := f.updateContentFromRemote(); err != nil {
			return nil, nil
		}
	}

	// check offset only after fetching from remote
	if offset > int64(len(f.Content)) {
		return nil, io.EOF
	}

	return f.Content[offset:], nil
}

// Create creates a new file on remote with existing content.
func (f *File) Create() error {
	f.Lock()
	defer f.Unlock()

	return f.writeContentToRemote(f.Content)
}

// WriteAt saves specified content at specified offset. Note, this saves to
// internal cache only.
func (f *File) WriteAt(content []byte, offset int64) {
	f.Lock()
	defer f.Unlock()

	f.IsDirty = true

	var newLen = len(content) + int(offset)
	if len(f.Content) < newLen {
		padding := make([]byte, newLen-len(f.Content))
		f.Content = append(f.Content, padding...)
	}

	copy(f.Content[offset:], content)

	if offset == 0 {
		f.Content = f.Content[0:len(content)]
	}

	f.Attrs.Size = uint64(len(f.Content))
}

// TruncateTo reduces file contents to specified length.
func (f *File) TruncateTo(size uint64) error {
	f.Lock()
	defer f.Unlock()

	s := int(size)
	switch {
	case s < len(f.Content):
		// specified size less than size of file, so remove all content over size
		f.Content = f.Content[:size]
	case s > len(f.Content):
		// specified size greater same as size of file, so add empty padding to
		// existing content
		f.Content = append(f.Content, make([]byte, s-len(f.Content))...)
	case s == len(f.Content):
		// specified size is same as size of file, so nothing to be done
	}

	return f.writeContentToRemote(f.Content)
}

// Flush saves internal cache to remote.
func (f *File) Flush() error {
	f.Lock()
	defer f.Unlock()

	return f.syncToRemote()
}

// Sync saves internal cache to remote.
func (f *File) Sync() error {
	f.Lock()
	defer f.Unlock()

	return f.syncToRemote()
}

///// Node interface

// GetType returns fuseutil.DT_File for identification for fuse library.
func (f *File) GetType() fuseutil.DirentType {
	return fuseutil.DT_File
}

// Expire removes the internal cache of file and fetches it from remote. It's
// required to update from remote since Kernel caches file attrs.
func (f *File) Expire() error {
	f.Lock()
	defer f.Unlock()

	// OH THE HORROR!
	// If remote has a change where size of file hasn't changed, then Kernel
	// doesn't invalidate the local cache, so we replace the InodeId.
	f.ID = f.Parent.IDGen.Next()

	return f.updateContentFromRemote()
}

///// Helpers

func (f *File) syncToRemote() error {
	var isDirty = f.IsDirty
	if !isDirty {
		return nil
	}

	return f.writeContentToRemote(f.Content)
}

func (f *File) writeContentToRemote(content []byte) error {
	f.IsDirty = false

	req := struct {
		Path    string
		Content []byte
	}{
		Path:    f.RemotePath,
		Content: content,
	}
	var res int

	return f.Transport.Trip("fs.writeFile", req, &res)
}

func (f *File) updateContentFromRemote() error {
	content, err := f.getContentFromRemote()
	if err != nil {
		return err
	}

	f.Content = content
	f.Attrs.Size = uint64(len(f.Content))
	f.Attrs.Mtime = time.Now()
	f.Attrs.Ctime = time.Now()

	return nil
}

func (f *File) getContentFromRemote() ([]byte, error) {
	req := struct{ Path string }{f.RemotePath}
	res := transport.FsReadFileRes{}
	if err := f.Trip("fs.readFile", req, &res); err != nil {
		return []byte{}, err
	}

	return res.Content, nil
}
<commit_msg>fix dropped error when fetching file from remote<commit_after>package fuseklient

import (
	"io"
	"time"

	"github.com/jacobsa/fuse/fuseutil"
	"github.com/koding/fuseklient/transport"
)

// File represents a file system file and implements Node interface.
type File struct {
	// Entry is generic structure that contains commonality between File and Dir.
	*Entry

	////// Entry#RWLock protects the fields below.

	// IsDirty indicates if File has been written to, but not yet been synced
	// with remote.
	IsDirty bool

	// Content is the remotely fetched contents of the File.
	Content []byte
}

// NewFile is the required initializeChild for File. If internal cache is empty,
// it'll fetch from remote.
func NewFile(n *Entry) *File {
	return &File{Entry: n, Content: []byte{}}
}

// ReadAt returns contents of file at specified offset.
func (f *File) ReadAt(offset int64) ([]byte, error) {
	f.Lock()
	defer f.Unlock()

	// fetch from remote is no content
	if len(f.Content) == 0 {
		if err := f.updateContentFromRemote(); err != nil {
			return nil, err
		}
	}

	// check offset only after fetching from remote
	if offset > int64(len(f.Content)) {
		return nil, io.EOF
	}

	return f.Content[offset:], nil
}

// Create creates a new file on remote with existing content.
func (f *File) Create() error {
	f.Lock()
	defer f.Unlock()

	return f.writeContentToRemote(f.Content)
}

// WriteAt saves specified content at specified offset. Note, this saves to
// internal cache only.
func (f *File) WriteAt(content []byte, offset int64) {
	f.Lock()
	defer f.Unlock()

	f.IsDirty = true

	var newLen = len(content) + int(offset)
	if len(f.Content) < newLen {
		padding := make([]byte, newLen-len(f.Content))
		f.Content = append(f.Content, padding...)
	}

	copy(f.Content[offset:], content)

	if offset == 0 {
		f.Content = f.Content[0:len(content)]
	}

	f.Attrs.Size = uint64(len(f.Content))
}

// TruncateTo reduces file contents to specified length.
func (f *File) TruncateTo(size uint64) error {
	f.Lock()
	defer f.Unlock()

	s := int(size)
	switch {
	case s < len(f.Content):
		// specified size less than size of file, so remove all content over size
		f.Content = f.Content[:size]
	case s > len(f.Content):
		// specified size greater same as size of file, so add empty padding to
		// existing content
		f.Content = append(f.Content, make([]byte, s-len(f.Content))...)
	case s == len(f.Content):
		// specified size is same as size of file, so nothing to be done
	}

	return f.writeContentToRemote(f.Content)
}

// Flush saves internal cache to remote.
func (f *File) Flush() error {
	f.Lock()
	defer f.Unlock()

	return f.syncToRemote()
}

// Sync saves internal cache to remote.
func (f *File) Sync() error {
	f.Lock()
	defer f.Unlock()

	return f.syncToRemote()
}

///// Node interface

// GetType returns fuseutil.DT_File for identification for fuse library.
func (f *File) GetType() fuseutil.DirentType {
	return fuseutil.DT_File
}

// Expire removes the internal cache of file and fetches it from remote. It's
// required to update from remote since Kernel caches file attrs.
func (f *File) Expire() error {
	f.Lock()
	defer f.Unlock()

	// OH THE HORROR!
	// If remote has a change where size of file hasn't changed, then Kernel
	// doesn't invalidate the local cache, so we replace the InodeId.
	f.ID = f.Parent.IDGen.Next()

	return f.updateContentFromRemote()
}

///// Helpers

func (f *File) syncToRemote() error {
	var isDirty = f.IsDirty
	if !isDirty {
		return nil
	}

	return f.writeContentToRemote(f.Content)
}

func (f *File) writeContentToRemote(content []byte) error {
	f.IsDirty = false

	req := struct {
		Path    string
		Content []byte
	}{
		Path:    f.RemotePath,
		Content: content,
	}
	var res int

	return f.Transport.Trip("fs.writeFile", req, &res)
}

func (f *File) updateContentFromRemote() error {
	content, err := f.getContentFromRemote()
	if err != nil {
		return err
	}

	f.Content = content
	f.Attrs.Size = uint64(len(f.Content))
	f.Attrs.Mtime = time.Now()
	f.Attrs.Ctime = time.Now()

	return nil
}

func (f *File) getContentFromRemote() ([]byte, error) {
	req := struct{ Path string }{f.RemotePath}
	res := transport.FsReadFileRes{}
	if err := f.Trip("fs.readFile", req, &res); err != nil {
		return []byte{}, err
	}

	return res.Content, nil
}
<|endoftext|>


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

package com

import (
	"archive/tar"
	"archive/zip"
	"compress/gzip"
	"io"
	"io/ioutil"
	"os"
	"path"
)

// get filepath base name
func Basename(file string) string {
	return path.Base(file)
}

// get filepath dir name
func Dirname(file string) string {
	return path.Dir(file)
}

// get absolute filepath, based on built excutable file
func RealPath(file string) (string, error) {
	if path.IsAbs(file) {
		return file, nil
	}
	wd, err := os.Getwd()
	return path.Join(wd, file), err
}

// get file modified time
func FileMTime(file string) (int64, error) {
	f, e := os.Stat(file)
	if e != nil {
		return 0, e
	}
	return f.ModTime().Unix(), nil
}

// get file size as how many bytes
func FileSize(file string) (int64, error) {
	f, e := os.Stat(file)
	if e != nil {
		return 0, e
	}
	return f.Size(), nil
}

// copy file to new path
func Copy(file string, to string) (bool, error) {
	sf, e := os.Open(file)
	if e != nil {
		return false, e
	}
	defer sf.Close()
	df, e2 := os.Create(to)
	if e2 != nil {
		return false, e2
	}
	defer df.Close()
	// buffer reader, do chunk transfer
	buf := make([]byte, 1024)
	for {
		// read a chunk
		n, err := sf.Read(buf)
		if err != nil && err != io.EOF {
			return false, err
		}
		if n == 0 {
			break
		}
		// write a chunk
		if _, err := df.Write(buf[:n]); err != nil {
			return false, err
		}
	}
	return true, nil
}

// move file to new path
func Move(file string, to string) (bool, error) {
	// copy
	r, e := Copy(file, to)
	if e != nil {
		return r, e
	}
	// then remove
	e = os.Remove(file)
	if e != nil {
		r = false
	}
	return r, e
}

// delete file
func Unlink(file string) error {
	return os.Remove(file)
}

// rename file name
func Rename(file string, to string) error {
	return os.Rename(file, to)
}

// IsFile checks whether the path is a file,
// it returns false when it's a directory or does not exist.
func IsFile(filePath string) bool {
	f, e := os.Stat(filePath)
	if e != nil {
		return false
	}
	return !f.IsDir()
}

// IsExist returns whether a file or directory exists.
func IsExist(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}

// SaveFile saves content type '[]byte' to file by given path.
// It returns error when fail to finish operation.
func SaveFile(filePath string, b []byte) (int, error) {
	os.MkdirAll(path.Dir(filePath), os.ModePerm)
	fw, err := os.Create(filePath)
	if err != nil {
		return 0, err
	}
	defer fw.Close()
	return fw.Write(b)
}

// SaveFileS saves content type 'string' to file by given path.
// It returns error when fail to finish operation.
func SaveFileS(filePath string, s string) (int, error) {
	return SaveFile(filePath, []byte(s))
}

// ReadFile reads data type '[]byte' from file by given path.
// It returns error when fail to finish operation.
func ReadFile(filePath string) ([]byte, error) {
	b, err := ioutil.ReadFile(filePath)
	if err != nil {
		return []byte(""), err
	}
	return b, nil
}

// ReadFileS reads data type 'string' from file by given path.
// It returns error when fail to finish operation.
func ReadFileS(filePath string) (string, error) {
	b, err := ReadFile(filePath)
	return string(b), err
}

// Unzip unzips .zip file to 'destPath' and returns sub-directories.
// It returns error when fail to finish operation.
func Unzip(srcPath, destPath string) ([]string, error) {
	// Open a zip archive for reading
	r, err := zip.OpenReader(srcPath)
	if err != nil {
		return nil, err
	}
	defer r.Close()

	dirs := make([]string, 0, 5)
	// Iterate through the files in the archive
	for _, f := range r.File {
		// Get files from archive
		rc, err := f.Open()
		if err != nil {
			return nil, err
		}

		dir := path.Dir(f.FileInfo().Name())
		// Create diretory before create file
		os.MkdirAll(destPath+"/"+dir, os.ModePerm)
		dirs = AppendStr(dirs, dir)

		// Write data to file
		fw, _ := os.Create(destPath + "/" + f.FileInfo().Name())
		if err != nil {
			return nil, err
		}
		_, err = io.Copy(fw, rc)
		fw.Close()
		if err != nil {
			return nil, err
		}
	}
	return dirs, nil
}

// UnTarGz ungzips and untars .tar.gz file to 'destPath' and returns sub-directories.
// It returns error when fail to finish operation.
func UnTarGz(srcFilePath string, destDirPath string) ([]string, error) {
	// Create destination directory
	os.Mkdir(destDirPath, os.ModePerm)

	fr, err := os.Open(srcFilePath)
	if err != nil {
		return nil, err
	}
	defer fr.Close()

	// Gzip reader
	gr, err := gzip.NewReader(fr)
	if err != nil {
		return nil, err
	}
	defer gr.Close()

	// Tar reader
	tr := tar.NewReader(gr)

	dirs := make([]string, 0, 5)
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			// End of tar archive
			break
		}

		// Check if it is diretory or file
		if hdr.Typeflag != tar.TypeDir {
			// Get files from archive
			// Create diretory before create file
			dir := path.Dir(hdr.Name)
			os.MkdirAll(destDirPath+"/"+dir, os.ModePerm)
			dirs = AppendStr(dirs, dir)

			// Write data to file
			fw, _ := os.Create(destDirPath + "/" + hdr.Name)
			if err != nil {
				return nil, err
			}
			_, err = io.Copy(fw, tr)
			if err != nil {
				return nil, err
			}
		}
	}
	return dirs, nil
}
<commit_msg>Updated func: Unzip<commit_after>// Copyright 2013 com authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

package com

import (
	"archive/tar"
	"archive/zip"
	"compress/gzip"
	"io"
	"io/ioutil"
	"os"
	"path"
	"strings"
)

// get filepath base name
func Basename(file string) string {
	return path.Base(file)
}

// get filepath dir name
func Dirname(file string) string {
	return path.Dir(file)
}

// get absolute filepath, based on built excutable file
func RealPath(file string) (string, error) {
	if path.IsAbs(file) {
		return file, nil
	}
	wd, err := os.Getwd()
	return path.Join(wd, file), err
}

// get file modified time
func FileMTime(file string) (int64, error) {
	f, e := os.Stat(file)
	if e != nil {
		return 0, e
	}
	return f.ModTime().Unix(), nil
}

// get file size as how many bytes
func FileSize(file string) (int64, error) {
	f, e := os.Stat(file)
	if e != nil {
		return 0, e
	}
	return f.Size(), nil
}

// copy file to new path
func Copy(file string, to string) (bool, error) {
	sf, e := os.Open(file)
	if e != nil {
		return false, e
	}
	defer sf.Close()
	df, e2 := os.Create(to)
	if e2 != nil {
		return false, e2
	}
	defer df.Close()
	// buffer reader, do chunk transfer
	buf := make([]byte, 1024)
	for {
		// read a chunk
		n, err := sf.Read(buf)
		if err != nil && err != io.EOF {
			return false, err
		}
		if n == 0 {
			break
		}
		// write a chunk
		if _, err := df.Write(buf[:n]); err != nil {
			return false, err
		}
	}
	return true, nil
}

// move file to new path
func Move(file string, to string) (bool, error) {
	// copy
	r, e := Copy(file, to)
	if e != nil {
		return r, e
	}
	// then remove
	e = os.Remove(file)
	if e != nil {
		r = false
	}
	return r, e
}

// delete file
func Unlink(file string) error {
	return os.Remove(file)
}

// rename file name
func Rename(file string, to string) error {
	return os.Rename(file, to)
}

// IsFile checks whether the path is a file,
// it returns false when it's a directory or does not exist.
func IsFile(filePath string) bool {
	f, e := os.Stat(filePath)
	if e != nil {
		return false
	}
	return !f.IsDir()
}

// IsExist returns whether a file or directory exists.
func IsExist(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}

// SaveFile saves content type '[]byte' to file by given path.
// It returns error when fail to finish operation.
func SaveFile(filePath string, b []byte) (int, error) {
	os.MkdirAll(path.Dir(filePath), os.ModePerm)
	fw, err := os.Create(filePath)
	if err != nil {
		return 0, err
	}
	defer fw.Close()
	return fw.Write(b)
}

// SaveFileS saves content type 'string' to file by given path.
// It returns error when fail to finish operation.
func SaveFileS(filePath string, s string) (int, error) {
	return SaveFile(filePath, []byte(s))
}

// ReadFile reads data type '[]byte' from file by given path.
// It returns error when fail to finish operation.
func ReadFile(filePath string) ([]byte, error) {
	b, err := ioutil.ReadFile(filePath)
	if err != nil {
		return []byte(""), err
	}
	return b, nil
}

// ReadFileS reads data type 'string' from file by given path.
// It returns error when fail to finish operation.
func ReadFileS(filePath string) (string, error) {
	b, err := ReadFile(filePath)
	return string(b), err
}

// Unzip unzips .zip file to 'destPath' and returns sub-directories.
// It returns error when fail to finish operation.
func Unzip(srcPath, destPath string) ([]string, error) {
	// Open a zip archive for reading
	r, err := zip.OpenReader(srcPath)
	if err != nil {
		return nil, err
	}
	defer r.Close()

	dirs := make([]string, 0, 5)
	// Iterate through the files in the archive
	for _, f := range r.File {
		// Get files from archive
		rc, err := f.Open()
		if err != nil {
			return nil, err
		}

		dir := path.Dir(strings.TrimSuffix(
			f.FileInfo().Name(), "/"))
		// Create diretory before create file
		os.MkdirAll(destPath+"/"+dir, os.ModePerm)
		dirs = AppendStr(dirs, dir)

		// Write data to file
		fw, _ := os.Create(destPath + "/" + f.FileInfo().Name())
		if err != nil {
			return nil, err
		}
		_, err = io.Copy(fw, rc)
		fw.Close()
		if err != nil {
			return nil, err
		}
	}
	return dirs, nil
}

// UnTarGz ungzips and untars .tar.gz file to 'destPath' and returns sub-directories.
// It returns error when fail to finish operation.
func UnTarGz(srcFilePath string, destDirPath string) ([]string, error) {
	// Create destination directory
	os.Mkdir(destDirPath, os.ModePerm)

	fr, err := os.Open(srcFilePath)
	if err != nil {
		return nil, err
	}
	defer fr.Close()

	// Gzip reader
	gr, err := gzip.NewReader(fr)
	if err != nil {
		return nil, err
	}
	defer gr.Close()

	// Tar reader
	tr := tar.NewReader(gr)

	dirs := make([]string, 0, 5)
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			// End of tar archive
			break
		}

		// Check if it is diretory or file
		if hdr.Typeflag != tar.TypeDir {
			// Get files from archive
			// Create diretory before create file
			dir := path.Dir(hdr.Name)
			os.MkdirAll(destDirPath+"/"+dir, os.ModePerm)
			dirs = AppendStr(dirs, dir)

			// Write data to file
			fw, _ := os.Create(destDirPath + "/" + hdr.Name)
			if err != nil {
				return nil, err
			}
			_, err = io.Copy(fw, tr)
			if err != nil {
				return nil, err
			}
		}
	}
	return dirs, nil
}
<|endoftext|>


<commit_before>package rollrus

import (
	"fmt"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/stvp/roll"
)

type Hook struct {
	Client roll.Client
}

func (r *Hook) Fire(entry *log.Entry) (err error) {
	e := fmt.Errorf(entry.Message)
	m := convertFields(entry.Data)
	if _, exists := m["time"]; !exists {
		m["time"] = entry.Time.Format(time.RFC3339)
	}

	switch entry.Level {
	case log.FatalLevel, log.PanicLevel:
		_, err = r.Client.Critical(e, m)
	case log.ErrorLevel:
		_, err = r.Client.Error(e, m)
	case log.WarnLevel:
		_, err = r.Client.Warning(e, m)
	case log.InfoLevel:
		_, err = r.Client.Info(entry.Message, m)
	case log.DebugLevel:
		_, err = r.Client.Debug(entry.Message, m)
	default:
		return fmt.Errorf("Unknown level: %s", entry.Level)
	}

	return err
}

func convertFields(fields log.Fields) map[string]string {
	m := make(map[string]string)
	for k, v := range fields {
		switch t := v.(type) {
		case time.Time:
			m[k] = t.Format(time.RFC3339)
		default:
			if s, ok := v.(fmt.Stringer); ok {
				m[k] = s.String()
			} else {
				m[k] = fmt.Sprintf("%+v", t)
			}
		}
	}

	return m
}
<commit_msg>Oops, part of the Hook interface}<commit_after>package rollrus

import (
	"fmt"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/stvp/roll"
)

type Hook struct {
	Client roll.Client
}

func (r *Hook) Fire(entry *log.Entry) (err error) {
	e := fmt.Errorf(entry.Message)
	m := convertFields(entry.Data)
	if _, exists := m["time"]; !exists {
		m["time"] = entry.Time.Format(time.RFC3339)
	}

	switch entry.Level {
	case log.FatalLevel, log.PanicLevel:
		_, err = r.Client.Critical(e, m)
	case log.ErrorLevel:
		_, err = r.Client.Error(e, m)
	case log.WarnLevel:
		_, err = r.Client.Warning(e, m)
	case log.InfoLevel:
		_, err = r.Client.Info(entry.Message, m)
	case log.DebugLevel:
		_, err = r.Client.Debug(entry.Message, m)
	default:
		return fmt.Errorf("Unknown level: %s", entry.Level)
	}

	return err
}

func (r *Hook) Levels() []log.Level {
	return []log.Level{
		log.ErrorLevel,
		log.FatalLevel,
		log.PanicLevel,
	}
}

func convertFields(fields log.Fields) map[string]string {
	m := make(map[string]string)
	for k, v := range fields {
		switch t := v.(type) {
		case time.Time:
			m[k] = t.Format(time.RFC3339)
		default:
			if s, ok := v.(fmt.Stringer); ok {
				m[k] = s.String()
			} else {
				m[k] = fmt.Sprintf("%+v", t)
			}
		}
	}

	return m
}
<|endoftext|>


<commit_before>package util

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"os"
)

// 標準の FlagSet だと ContinueOnError にしても、
// エラーのところで読み込みを終えてしまうので、
// 最後まで読み込めるようにする。
type FlagSet struct {
	*flag.FlagSet
	name string
	flag.ErrorHandling
	output io.Writer
}

func NewFlagSet(name string, errorHandling flag.ErrorHandling) *FlagSet {
	return &FlagSet{
		flag.NewFlagSet(name, errorHandling),
		name,
		errorHandling,
		nil,
	}
}

func (f *FlagSet) SetOutput(output io.Writer) {
	f.output = output
	f.FlagSet.SetOutput(output)
}

func (f *FlagSet) CompleteParse(args []string) {
	usage := f.FlagSet.Usage
	f.FlagSet.Usage = func() {}
	f.FlagSet.Init(f.name, flag.ContinueOnError)

	errTokens := []string{}
	for curArgs := args; len(curArgs) > 0; curArgs = f.FlagSet.Args() {
		buff := &bytes.Buffer{}
		f.FlagSet.SetOutput(buff)
		f.FlagSet.Parse(curArgs)
		if buff.Len() == 0 {
			// 正常に最後まで読み取った。
			break
		}
		errTokens = append(errTokens, curArgs[len(curArgs)-len(f.FlagSet.Args())-1])
	}

	f.FlagSet.Usage = usage
	f.FlagSet.Init(f.name, f.ErrorHandling)
	f.FlagSet.SetOutput(f.output)

	if len(errTokens) > 0 {
		fmt.Fprintln(os.Stderr, "flag provided but not defined:")
		for _, errToken := range errTokens {
			fmt.Fprintln(os.Stderr, "  "+errToken)
		}
		f.FlagSet.Usage()
	}
}
<commit_msg>設定ファイルを共有するための型を削除<commit_after><|endoftext|>


<commit_before>// Copyright 2012 The go-gl 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 gltext

import (
	"bufio"
	"github.com/go-gl/glow/gl-core/3.3/gl"
	"github.com/go-gl/mathgl/mgl32"
	"image"
	"image/png"
	"os"
)

var fontVertexShaderSource string = `
#version 330

uniform mat4 scale_matrix;
uniform mat4 orthographic_matrix;
uniform vec2 final_position;

in vec4 centered_position;
in vec2 uv;

out vec2 fragment_uv;

// The orthographic projection uses a lower left-hand point of (0,0)
// 1) We center the text on screen.
// 2) We perform othographic transformation and then scaling.
// 3) We move the text to its final resting place.
// This is all pretty standard I would imagine, but it took me a bit to sort out what has to happen :P

void main() {
  fragment_uv = uv;
  vec4 scaled = scale_matrix * orthographic_matrix * centered_position;
  gl_Position = vec4(scaled.x + final_position.x, scaled.y + final_position.y, scaled.z, scaled.w);
}
` + "\x00"

var fontFragmentShaderSource string = `
#version 330

uniform sampler2D fragment_texture;
uniform float text_lowerbound;
uniform vec4 fragment_color_adjustment;

in vec2 fragment_uv;
out vec4 fragment_color;

void main() {
  vec4 color     = texture(fragment_texture, fragment_uv);
  color.xyz      = fragment_color_adjustment.xyz;
  fragment_color = color;
}
` + "\x00"

type Font struct {
	IsDebug bool

	config         *FontConfig // Character set for this font.
	textureID      uint32      // Holds the glyph texture id.
	maxGlyphWidth  int         // Largest glyph width.
	maxGlyphHeight int         // Largest glyph height.
	program        uint32      // program compiled from shaders

	// attributes
	centeredPosition uint32 // vertex centered_position required for scaling around the orthographic projections center
	uv               uint32 // texture position

	// The final screen position post-scaling
	finalPositionUniform int32

	// Position of the shaders fragment texture variable
	fragmentTextureUniform int32

	// The desired color of the text
	colorUniform int32

	// View matrix
	orthographicMatrixUniform int32
	orthographicMatrix        mgl32.Mat4

	// Scale the resulting text
	scaleMatrixUniform int32

	textureWidth  float32
	textureHeight float32
	WindowWidth   float32
	WindowHeight  float32
}

func loadFont(img *image.RGBA, config *FontConfig) (f *Font, err error) {
	f = new(Font)
	f.config = config

	// Resize image to next power-of-two.
	img = Pow2Image(img).(*image.RGBA)
	ib := img.Bounds()

	f.textureWidth = float32(ib.Dx())
	f.textureHeight = float32(ib.Dy())

	for _, glyph := range config.Glyphs {
		if glyph.Width > f.maxGlyphWidth {
			f.maxGlyphWidth = glyph.Width
		}
		if glyph.Height > f.maxGlyphHeight {
			f.maxGlyphHeight = glyph.Height
		}
	}

	// save to disk for testing
	if f.IsDebug {
		file, err := os.Create("out.png")
		if err != nil {
			panic(err)
		}
		defer file.Close()

		b := bufio.NewWriter(file)
		err = png.Encode(b, img)
		if err != nil {
			panic(err)
		}
		err = b.Flush()
		if err != nil {
			panic(err)
		}
	}

	// generate texture
	gl.GenTextures(1, &f.textureID)
	gl.BindTexture(gl.TEXTURE_2D, f.textureID)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
	gl.TexImage2D(
		gl.TEXTURE_2D,
		0,
		gl.RGBA,
		int32(ib.Dx()),
		int32(ib.Dy()),
		0,
		gl.RGBA,
		gl.UNSIGNED_BYTE,
		gl.Ptr(img.Pix),
	)
	gl.BindTexture(gl.TEXTURE_2D, 0)

	// create shader program and define attributes and uniforms
	f.program, err = NewProgram(fontVertexShaderSource, fontFragmentShaderSource)
	if err != nil {
		return f, err
	}

	// attributes
	f.centeredPosition = uint32(gl.GetAttribLocation(f.program, gl.Str("centered_position\x00")))
	f.uv = uint32(gl.GetAttribLocation(f.program, gl.Str("uv\x00")))

	// uniforms
	f.finalPositionUniform = gl.GetUniformLocation(f.program, gl.Str("final_position\x00"))
	f.orthographicMatrixUniform = gl.GetUniformLocation(f.program, gl.Str("orthographic_matrix\x00"))
	f.scaleMatrixUniform = gl.GetUniformLocation(f.program, gl.Str("scale_matrix\x00"))
	f.fragmentTextureUniform = gl.GetUniformLocation(f.program, gl.Str("fragment_texture\x00"))
	f.colorUniform = gl.GetUniformLocation(f.program, gl.Str("fragment_color_adjustment\x00"))
	return f, nil
}

func (f *Font) ResizeWindow(width float32, height float32) {
	f.WindowWidth = width
	f.WindowHeight = height
	f.orthographicMatrix = mgl32.Ortho2D(-f.WindowWidth/2, f.WindowWidth/2, -f.WindowHeight/2, f.WindowHeight/2)
}

func (f *Font) Release() {
	gl.DeleteTextures(1, &f.textureID)
	f.config = nil
}
<commit_msg>Access to the ortho matrix.<commit_after>// Copyright 2012 The go-gl 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 gltext

import (
	"bufio"
	"github.com/go-gl/glow/gl-core/3.3/gl"
	"github.com/go-gl/mathgl/mgl32"
	"image"
	"image/png"
	"os"
)

var fontVertexShaderSource string = `
#version 330

uniform mat4 scale_matrix;
uniform mat4 orthographic_matrix;
uniform vec2 final_position;

in vec4 centered_position;
in vec2 uv;

out vec2 fragment_uv;

// The orthographic projection uses a lower left-hand point of (0,0)
// 1) We center the text on screen.
// 2) We perform othographic transformation and then scaling.
// 3) We move the text to its final resting place.
// This is all pretty standard I would imagine, but it took me a bit to sort out what has to happen :P

void main() {
  fragment_uv = uv;
  vec4 scaled = scale_matrix * orthographic_matrix * centered_position;
  gl_Position = vec4(scaled.x + final_position.x, scaled.y + final_position.y, scaled.z, scaled.w);
}
` + "\x00"

var fontFragmentShaderSource string = `
#version 330

uniform sampler2D fragment_texture;
uniform float text_lowerbound;
uniform vec4 fragment_color_adjustment;

in vec2 fragment_uv;
out vec4 fragment_color;

void main() {
  vec4 color     = texture(fragment_texture, fragment_uv);
  color.xyz      = fragment_color_adjustment.xyz;
  fragment_color = color;
}
` + "\x00"

type Font struct {
	IsDebug bool

	config         *FontConfig // Character set for this font.
	textureID      uint32      // Holds the glyph texture id.
	maxGlyphWidth  int         // Largest glyph width.
	maxGlyphHeight int         // Largest glyph height.
	program        uint32      // program compiled from shaders

	// attributes
	centeredPosition uint32 // vertex centered_position required for scaling around the orthographic projections center
	uv               uint32 // texture position

	// The final screen position post-scaling
	finalPositionUniform int32

	// Position of the shaders fragment texture variable
	fragmentTextureUniform int32

	// The desired color of the text
	colorUniform int32

	// View matrix
	orthographicMatrixUniform int32
	orthographicMatrix        mgl32.Mat4

	// Scale the resulting text
	scaleMatrixUniform int32

	textureWidth  float32
	textureHeight float32
	WindowWidth   float32
	WindowHeight  float32
}

func loadFont(img *image.RGBA, config *FontConfig) (f *Font, err error) {
	f = new(Font)
	f.config = config

	// Resize image to next power-of-two.
	img = Pow2Image(img).(*image.RGBA)
	ib := img.Bounds()

	f.textureWidth = float32(ib.Dx())
	f.textureHeight = float32(ib.Dy())

	for _, glyph := range config.Glyphs {
		if glyph.Width > f.maxGlyphWidth {
			f.maxGlyphWidth = glyph.Width
		}
		if glyph.Height > f.maxGlyphHeight {
			f.maxGlyphHeight = glyph.Height
		}
	}

	// save to disk for testing
	if f.IsDebug {
		file, err := os.Create("out.png")
		if err != nil {
			panic(err)
		}
		defer file.Close()

		b := bufio.NewWriter(file)
		err = png.Encode(b, img)
		if err != nil {
			panic(err)
		}
		err = b.Flush()
		if err != nil {
			panic(err)
		}
	}

	// generate texture
	gl.GenTextures(1, &f.textureID)
	gl.BindTexture(gl.TEXTURE_2D, f.textureID)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
	gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
	gl.TexImage2D(
		gl.TEXTURE_2D,
		0,
		gl.RGBA,
		int32(ib.Dx()),
		int32(ib.Dy()),
		0,
		gl.RGBA,
		gl.UNSIGNED_BYTE,
		gl.Ptr(img.Pix),
	)
	gl.BindTexture(gl.TEXTURE_2D, 0)

	// create shader program and define attributes and uniforms
	f.program, err = NewProgram(fontVertexShaderSource, fontFragmentShaderSource)
	if err != nil {
		return f, err
	}

	// attributes
	f.centeredPosition = uint32(gl.GetAttribLocation(f.program, gl.Str("centered_position\x00")))
	f.uv = uint32(gl.GetAttribLocation(f.program, gl.Str("uv\x00")))

	// uniforms
	f.finalPositionUniform = gl.GetUniformLocation(f.program, gl.Str("final_position\x00"))
	f.orthographicMatrixUniform = gl.GetUniformLocation(f.program, gl.Str("orthographic_matrix\x00"))
	f.scaleMatrixUniform = gl.GetUniformLocation(f.program, gl.Str("scale_matrix\x00"))
	f.fragmentTextureUniform = gl.GetUniformLocation(f.program, gl.Str("fragment_texture\x00"))
	f.colorUniform = gl.GetUniformLocation(f.program, gl.Str("fragment_color_adjustment\x00"))
	return f, nil
}

func (f *Font) ResizeWindow(width float32, height float32) {
	f.WindowWidth = width
	f.WindowHeight = height
	f.orthographicMatrix = mgl32.Ortho2D(-f.WindowWidth/2, f.WindowWidth/2, -f.WindowHeight/2, f.WindowHeight/2)
}

func (f *Font) GetOrtho() *mgl32.Mat4 {
	return &f.orthographicMatrix
}

func (f *Font) Release() {
	gl.DeleteTextures(1, &f.textureID)
	f.config = nil
}
<|endoftext|>


<commit_before>package main

import (
	"exec"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"
)

const (
	jLo = 1
	jHi = 16
)

var testCaseRegexp = regexp.MustCompile("it_[a-zA-Z0-9_]*")

type TaskResult struct {
	task   string
	err    os.Error
	output string
}

func printUsage() {
	fmt.Printf(`roundup [options] testplan

Options:

-jN - concurrency level. For example, -j4 means parallel execution with 4 threads.
`)
}

func execute(testPlan, task string) (res *TaskResult) {
	res = new(TaskResult)
	res.task = task
	cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("set -e; . %s; %s", testPlan, task))
	cmd.Dir, _ = path.Split(testPlan)
	data, err := cmd.CombinedOutput()
	res.err = err
	res.output = string(data)
	return
}

func worker(index int, testPlan string, taskCh chan string, resCh chan *TaskResult, doneCh chan bool) {
	for task := range taskCh {
		resCh <- execute(testPlan, task)
	}
	doneCh <- true
}

func resultWorker(resCh chan *TaskResult, doneResCh chan []*TaskResult) {
	var all []*TaskResult
	for r := range resCh {
		if r.err == nil {
			fmt.Printf("%s\tPASS\n", r.task)
		} else {
			fmt.Printf("%s\n", r.output)
			fmt.Printf("%s\tFAILED\n", r.task)
		}
		all = append(all, r)
	}
	doneResCh <- all
}

func summarize(res []*TaskResult) bool {
	passed := 0
	for _, r := range res {
		if r.err == nil {
			passed++
		}
	}
	fmt.Printf("\nTests: %3d | Passed: %3d | Failed: %3d |\n", len(res), passed, len(res)-passed)
	return passed == len(res)
}

func main() {
	if len(os.Args) == 1 {
		printUsage()
		os.Exit(1)
	}
	var j = jLo
	if strings.HasPrefix(os.Args[1], "-j") {
		var err os.Error
		j, err = strconv.Atoi(os.Args[1][2:])
		if err != nil {
			fmt.Fprintf(os.Stderr, "roundup: Couldn't parse -j option. "+
				"Valid values are like -j2, -j4, -j16, etc\n")
			os.Exit(1)
		}
		if len(os.Args) == 2 {
			printUsage()
			os.Exit(1)
		}
	}
	if j < jLo || j > jHi {
		fmt.Fprintf(os.Stderr, "roundup: -j%d is invalid option. "+
			"Concurrency level from %d to %d are supported", j, jLo, jHi)
		os.Exit(1)
	}
	testPlan := os.Args[len(os.Args)-1]
	data, err := ioutil.ReadFile(testPlan)
	if err != nil {
		fmt.Fprintf(os.Stderr, "roundup: couldn't read %s: %v", testPlan, err)
		os.Exit(1)
	}
	taskCh := make(chan string)
	resCh := make(chan *TaskResult)
	doneCh := make(chan bool)
	doneResCh := make(chan []*TaskResult)
	for i := 0; i < j; i++ {
		go worker(i, testPlan, taskCh, resCh, doneCh)
	}
	go resultWorker(resCh, doneResCh)
	for _, line := range strings.Split(string(data), "\n") {
		m := testCaseRegexp.FindString(line)
		if m != "" {
			taskCh <- m
		}
	}
	close(taskCh)
	for i := 0; i < j; i++ {
		<-doneCh
	}
	close(doneCh)
	close(resCh)
	res := <-doneResCh
	close(doneResCh)
	if !summarize(res) {
		os.Exit(2)
	}
}
<commit_msg>Implement ROUNDUP_CONCURRENCY env var for backward compatibility with the mainline roundup<commit_after>package main

import (
	"exec"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"
)

const (
	jLo = 1
	jHi = 16

	jEnv = "ROUNDUP_CONCURRENCY"
)

var testCaseRegexp = regexp.MustCompile("it_[a-zA-Z0-9_]*")

type TaskResult struct {
	task   string
	err    os.Error
	output string
}

func printUsage() {
	fmt.Printf(`roundup [options] testplan

Options:

-jN - concurrency level. For example, -j4 means parallel execution with 4 threads.
`)
}

func execute(testPlan, task string) (res *TaskResult) {
	res = new(TaskResult)
	res.task = task
	cmd := exec.Command("/bin/sh", "-c", fmt.Sprintf("set -e; . %s; %s", testPlan, task))
	cmd.Dir, _ = path.Split(testPlan)
	data, err := cmd.CombinedOutput()
	res.err = err
	res.output = string(data)
	return
}

func worker(index int, testPlan string, taskCh chan string, resCh chan *TaskResult, doneCh chan bool) {
	for task := range taskCh {
		resCh <- execute(testPlan, task)
	}
	doneCh <- true
}

func resultWorker(resCh chan *TaskResult, doneResCh chan []*TaskResult) {
	var all []*TaskResult
	for r := range resCh {
		if r.err == nil {
			fmt.Printf("%s\tPASS\n", r.task)
		} else {
			fmt.Printf("%s\n", r.output)
			fmt.Printf("%s\tFAILED\n", r.task)
		}
		all = append(all, r)
	}
	doneResCh <- all
}

func summarize(res []*TaskResult) bool {
	passed := 0
	for _, r := range res {
		if r.err == nil {
			passed++
		}
	}
	fmt.Printf("\nTests: %3d | Passed: %3d | Failed: %3d |\n", len(res), passed, len(res)-passed)
	return passed == len(res)
}

func main() {
	var err os.Error
	if len(os.Args) == 1 {
		printUsage()
		os.Exit(1)
	}
	var j = jLo
	if os.Getenv(jEnv) != "" {
		j, err = strconv.Atoi(os.Getenv(jEnv))
		if err != nil {
			fmt.Fprintf(os.Stderr, "Warning: %s environment variable is set, "+
				"but has non-numeric value %s\n",
				jEnv, os.Getenv(jEnv))
			j = 1
		}
	}
	if strings.HasPrefix(os.Args[1], "-j") {
		j, err = strconv.Atoi(os.Args[1][2:])
		if err != nil {
			fmt.Fprintf(os.Stderr, "roundup: Couldn't parse -j option. "+
				"Valid values are like -j2, -j4, -j16, etc\n")
			os.Exit(1)
		}
		if len(os.Args) == 2 {
			printUsage()
			os.Exit(1)
		}
	}
	if j < jLo || j > jHi {
		fmt.Fprintf(os.Stderr, "roundup: %d is invalid value for concurrency level. "+
			"Concurrency levels from %d to %d are only supported\n", j, jLo, jHi)
		os.Exit(1)
	}
	testPlan := os.Args[len(os.Args)-1]
	data, err := ioutil.ReadFile(testPlan)
	if err != nil {
		fmt.Fprintf(os.Stderr, "roundup: couldn't read %s: %v", testPlan, err)
		os.Exit(1)
	}
	taskCh := make(chan string)
	resCh := make(chan *TaskResult)
	doneCh := make(chan bool)
	doneResCh := make(chan []*TaskResult)
	for i := 0; i < j; i++ {
		go worker(i, testPlan, taskCh, resCh, doneCh)
	}
	go resultWorker(resCh, doneResCh)
	for _, line := range strings.Split(string(data), "\n") {
		m := testCaseRegexp.FindString(line)
		if m != "" {
			taskCh <- m
		}
	}
	close(taskCh)
	for i := 0; i < j; i++ {
		<-doneCh
	}
	close(doneCh)
	close(resCh)
	res := <-doneResCh
	close(doneResCh)
	if !summarize(res) {
		os.Exit(2)
	}
}
<|endoftext|>


<commit_before>// Copyright (C) 2014 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/mssola/todo/app"
	"github.com/mssola/todo/lib"
)

// It returns true (thus, accepting the route) if the current user is
// logged in, false otherwise.
func userLogged(req *http.Request, rm *mux.RouteMatch) bool {
	var rid string

	if lib.JsonEncoding(req) {
		rid = req.URL.Query().Get("userId")
	}
	if id, ok := lib.GetCookie(req, "userId").(string); ok {
		rid = id
	}
	return app.Exists("users", rid)
}

// Returns true if this request should not let JSON requests pass.
func private(req *http.Request, rm *mux.RouteMatch) bool {
	return !lib.JsonEncoding(req)
}

// Returns the "Not found" response.
func notFound(w http.ResponseWriter, req *http.Request) {
	if lib.JsonEncoding(req) {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, lib.Response{Error: "Something wrong happened!"})
	} else {
		w.Header().Set("Content-Type", "text/plain")
		fmt.Fprint(w, "404 Not Found")
	}
}

// Handles the routing for this application. Returns a mux.Router with all our
// routes setup. This handles both the regular web page and the JSON API is.
// The endpoints open for the API are:
//
//  - sessions: login.
//  - topics: index, create, show, update, delete.
func route() *mux.Router {
	r := mux.NewRouter()

	// Let's get our own "Not Found" handler.
	r.NotFoundHandler = http.HandlerFunc(notFound)

	// The routing itself.
	r.HandleFunc("/", app.RootIndex).Methods("GET").
		MatcherFunc(private)
	r.HandleFunc("/login", app.Login).Methods("POST")
	r.HandleFunc("/login.json", app.Login).Methods("POST")
	r.HandleFunc("/logout", app.Logout).Methods("POST").
		MatcherFunc(userLogged).MatcherFunc(private)
	r.HandleFunc("/users", app.UsersCreate).Methods("POST").
		MatcherFunc(private)
	r.HandleFunc("/topics", app.TopicsIndex).Methods("GET").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics.json", app.TopicsIndex).Methods("GET").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics", app.TopicsCreate).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics.json", app.TopicsCreate).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}", app.TopicsShow).Methods("GET").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}.json", app.TopicsShow).Methods("GET").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}", app.TopicsUpdate).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}.json", app.TopicsUpdate).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}/delete", app.TopicsDestroy).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}/delete.json", app.TopicsDestroy).Methods("POST").
		MatcherFunc(userLogged)

	return r
}
<commit_msg>You're either a JSON request or the web app, not both at the same time.<commit_after>// Copyright (C) 2014 Miquel Sabaté Solà <mikisabate@gmail.com>
// This file is licensed under the MIT license.
// See the LICENSE file.

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/mssola/todo/app"
	"github.com/mssola/todo/lib"
)

// It returns true (thus, accepting the route) if the current user is
// logged in, false otherwise.
func userLogged(req *http.Request, rm *mux.RouteMatch) bool {
	var rid string

	if lib.JsonEncoding(req) {
		rid = req.URL.Query().Get("userId")
	} else if id, ok := lib.GetCookie(req, "userId").(string); ok {
		rid = id
	}
	return app.Exists("users", rid)
}

// Returns true if this request should not let JSON requests pass.
func private(req *http.Request, rm *mux.RouteMatch) bool {
	return !lib.JsonEncoding(req)
}

// Returns the "Not found" response.
func notFound(w http.ResponseWriter, req *http.Request) {
	if lib.JsonEncoding(req) {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, lib.Response{Error: "Something wrong happened!"})
	} else {
		w.Header().Set("Content-Type", "text/plain")
		fmt.Fprint(w, "404 Not Found")
	}
}

// Handles the routing for this application. Returns a mux.Router with all our
// routes setup. This handles both the regular web page and the JSON API is.
// The endpoints open for the API are:
//
//  - sessions: login.
//  - topics: index, create, show, update, delete.
func route() *mux.Router {
	r := mux.NewRouter()

	// Let's get our own "Not Found" handler.
	r.NotFoundHandler = http.HandlerFunc(notFound)

	// The routing itself.
	r.HandleFunc("/", app.RootIndex).Methods("GET").
		MatcherFunc(private)
	r.HandleFunc("/login", app.Login).Methods("POST")
	r.HandleFunc("/login.json", app.Login).Methods("POST")
	r.HandleFunc("/logout", app.Logout).Methods("POST").
		MatcherFunc(userLogged).MatcherFunc(private)
	r.HandleFunc("/users", app.UsersCreate).Methods("POST").
		MatcherFunc(private)
	r.HandleFunc("/topics", app.TopicsIndex).Methods("GET").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics.json", app.TopicsIndex).Methods("GET").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics", app.TopicsCreate).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics.json", app.TopicsCreate).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}", app.TopicsShow).Methods("GET").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}.json", app.TopicsShow).Methods("GET").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}", app.TopicsUpdate).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}.json", app.TopicsUpdate).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}/delete", app.TopicsDestroy).Methods("POST").
		MatcherFunc(userLogged)
	r.HandleFunc("/topics/{id}/delete.json", app.TopicsDestroy).Methods("POST").
		MatcherFunc(userLogged)

	return r
}
<|endoftext|>


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

package cryptica

import "bytes"

type Solution []Direction

func (solution Solution) String() string {
	var buffer bytes.Buffer
	for i, dir := range solution {
		if i > 0 {
			buffer.WriteRune(' ')
		}
		buffer.WriteString(dir.String())
	}
	return buffer.String()
}

type Game struct {
	Name     string
	Start    State
	Goal     Goal
	MinSteps int
}

type Solver interface {
	Solve(game Game) Solution
}

type DepthFirstSolver struct {
}

func (solver DepthFirstSolver) Solve(game Game) Solution {
	cache := make(map[uint64]int)
	f := func(state State, solution Solution, k interface{}) Solution {
		n := len(solution)
		if n > game.MinSteps {
			return nil
		}
		code := state.Board.Encode(state)
		if m, exists := cache[code]; exists && m <= n {
			return nil
		}
		cache[code] = n
		if state.Match(game.Goal) {
			return solution
		}
		f := k.(func(State, Solution, interface{}) Solution)
		for dir := Up; dir <= Right; dir++ {
			if newstate, changed := state.Move(dir); changed {
				if result := f(newstate, append(solution, dir), k); result != nil {
					return result
				}
			}
		}
		return nil
	}
	return f(game.Start, make(Solution, 0), f)
}

type BreadthFirstSolver struct {
}

func (solver BreadthFirstSolver) Solve(game Game) Solution {
	cache := make(map[uint64]Solution)
	var current, next []uint64
	{
		code := game.Start.Board.Encode(game.Start)
		cache[code] = make(Solution, 0)
		current = []uint64{code}
	}
	depth := 0
	for len(current) > 0 {
		next = make([]uint64, 0)
		for _, code := range current {
			solution := cache[code]
			state := game.Start.Board.Decode(code)
			if state.Match(game.Goal) {
				return solution
			}
			if depth >= game.MinSteps {
				continue
			}
			for dir := Up; dir <= Right; dir++ {
				if newstate, changed := state.Move(dir); changed {
					newcode := game.Start.Board.Encode(newstate)
					if _, exists := cache[newcode]; !exists {
						newsolution := make(Solution, len(solution))
						copy(newsolution, solution)
						newsolution = append(newsolution, dir)
						cache[newcode] = newsolution
						next = append(next, newcode)
					}
				}
			}
			cache[code] = nil
		}
		depth++
		current = next
	}
	return nil
}
<commit_msg>added package description<commit_after>// Copyright 2017 Roberto Virga. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Cryptica is a mobile game developed by Pixibots. I have no affiliation
with the company other than being a satisfied customer. Solving a
puzzle in Cryptica involves moving tiles on a 7x5 board to match a
desired configuration. All tiles move symultaneously; their movements
are, however, constrained by the board edges, and possibly also by
some additional (unmovable) barriers.
This Go package can search efficiently for solutions of Cryptica and
Cryptica-like puzzles, in either depth-first or breadth-first fashion.
Moreover, it can work on boards of arbitrary size (with some caveats).
*/
package cryptica

import "bytes"

type Solution []Direction

func (solution Solution) String() string {
	var buffer bytes.Buffer
	for i, dir := range solution {
		if i > 0 {
			buffer.WriteRune(' ')
		}
		buffer.WriteString(dir.String())
	}
	return buffer.String()
}

type Game struct {
	Name     string
	Start    State
	Goal     Goal
	MinSteps int
}

type Solver interface {
	Solve(game Game) Solution
}

type DepthFirstSolver struct {
}

func (solver DepthFirstSolver) Solve(game Game) Solution {
	cache := make(map[uint64]int)
	f := func(state State, solution Solution, k interface{}) Solution {
		n := len(solution)
		if n > game.MinSteps {
			return nil
		}
		code := state.Board.Encode(state)
		if m, exists := cache[code]; exists && m <= n {
			return nil
		}
		cache[code] = n
		if state.Match(game.Goal) {
			return solution
		}
		f := k.(func(State, Solution, interface{}) Solution)
		for dir := Up; dir <= Right; dir++ {
			if newstate, changed := state.Move(dir); changed {
				if result := f(newstate, append(solution, dir), k); result != nil {
					return result
				}
			}
		}
		return nil
	}
	return f(game.Start, make(Solution, 0), f)
}

type BreadthFirstSolver struct {
}

func (solver BreadthFirstSolver) Solve(game Game) Solution {
	cache := make(map[uint64]Solution)
	var current, next []uint64
	{
		code := game.Start.Board.Encode(game.Start)
		cache[code] = make(Solution, 0)
		current = []uint64{code}
	}
	depth := 0
	for len(current) > 0 {
		next = make([]uint64, 0)
		for _, code := range current {
			solution := cache[code]
			state := game.Start.Board.Decode(code)
			if state.Match(game.Goal) {
				return solution
			}
			if depth >= game.MinSteps {
				continue
			}
			for dir := Up; dir <= Right; dir++ {
				if newstate, changed := state.Move(dir); changed {
					newcode := game.Start.Board.Encode(newstate)
					if _, exists := cache[newcode]; !exists {
						newsolution := make(Solution, len(solution))
						copy(newsolution, solution)
						newsolution = append(newsolution, dir)
						cache[newcode] = newsolution
						next = append(next, newcode)
					}
				}
			}
			cache[code] = nil
		}
		depth++
		current = next
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
)

func readLine(scanner *bufio.Scanner, replace_lines IntSet) {

	scanner.Split(bufio.ScanLines)

	line := 1

	ra, _ := regexp.Compile("[^\\s]")

	for scanner.Scan() {
		_, s := replace_lines[line]
		if s {
			fmt.Printf("%d: %v\n", line, ra.ReplaceAllString(scanner.Text(), "-"))
		} else {
			fmt.Printf("%d: %v\n", line, scanner.Text())
		}
		line += 1
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

}

func Exists(name string) bool {
	if _, err := os.Stat(name); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}

// set of ints
type IntSet map[int]struct{}

func (i *IntSet) String() string {
	return fmt.Sprint(*i)
}

func (i *IntSet) Set(value string) error {
	if len(*i) > 0 {
		return errors.New("line flag already set")
	}

	for _, n := range strings.Split(value, ",") {
		num, err := strconv.Atoi(n)
		if err != nil {
			continue
		}
		if _, found := (*i)[num]; found {
			continue
		}
		(*i)[num] = struct{}{}

	}

	return nil
}

func main() {

	var replace_lines = IntSet{}

	flag.Var(&replace_lines, "l", "Number of the line(s) to be replaced")

	flag.Parse()

	//	if len(flag.Args()) == 0 {
	fmt.Println("--:", flag.NArg(), flag.Args(), replace_lines)
	//	}

	//if flag.NFlag() > 0 {
	//fmt.Println("lines to be replaced:")
	//for i := 0; i < len(replace_lines); i++ {
	//fmt.Printf("%d ", replace_lines[i])
	//}
	//}

	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 {
		readLine(bufio.NewScanner(os.Stdin), replace_lines)
	} else {
		if flag.NArg() > 0 {

			f := flag.Arg(0)

			if Exists(f) {
				file, err := os.Open(f)
				defer file.Close()

				if err != nil {
					log.Fatal(err)
				}

				readLine(bufio.NewScanner(file), replace_lines)
			}
		}
	}
}
<commit_msg>using NArg 	modified:   gist.go<commit_after>package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
)

func readLine(scanner *bufio.Scanner, replace_lines IntSet) {

	scanner.Split(bufio.ScanLines)

	line := 1

	ra, _ := regexp.Compile("[^\\s]")

	for scanner.Scan() {
		_, s := replace_lines[line]
		if s {
			fmt.Printf("%d: %v\n", line, ra.ReplaceAllString(scanner.Text(), "-"))
		} else {
			fmt.Printf("%d: %v\n", line, scanner.Text())
		}
		line += 1
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

}

func Exists(name string) bool {
	if _, err := os.Stat(name); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}

// set of ints
type IntSet map[int]struct{}

// set of strings
type StrSlice []string

func (i *IntSet) String() string {
	return fmt.Sprint(*i)
}

func (i *IntSet) Set(value string) error {
	if len(*i) > 0 {
		return errors.New("line flag already set")
	}
	for _, n := range strings.Split(value, ",") {
		num, err := strconv.Atoi(n)
		if err != nil {
			continue
		}
		if _, found := (*i)[num]; found {
			continue
		}
		(*i)[num] = struct{}{}
	}
	return nil
}

func (s *StrSlice) String() string {
	return fmt.Sprint(*s)
}

func (s *StrSlice) Set(value string) error {
	*s = append(*s, value)
	return nil
}

func main() {

	var replace_lines = IntSet{}
	var replace_strings StrSlice

	flag.Var(&replace_lines, "l", "Number of the line(s) to be replaced")
	flag.Var(&replace_strings, "r", "Word to be replaced")

	flag.Parse()

	fmt.Println("--:", flag.NArg(), flag.Args(), replace_lines, replace_strings)

	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 {
		readLine(bufio.NewScanner(os.Stdin), replace_lines)
	} else {
		if flag.NArg() != 1 {
			fmt.Println("No filename specified")
			os.Exit(1)
		}
		f := flag.Arg(0)
		if Exists(f) {
			file, err := os.Open(f)
			defer file.Close()
			if err != nil {
				log.Fatal(err)
			}
			readLine(bufio.NewScanner(file), replace_lines)
		}
	}
}
<|endoftext|>


<commit_before>// run

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Test the situation in which two cases of a select can
// both end up running. See http://codereview.appspot.com/180068.

package main

import (
	"flag"
	"runtime"
)

var iterations *int = flag.Int("n", 100000, "number of iterations")

// sender sends a counter to one of four different channels. If two
// cases both end up running in the same iteration, the same value will be sent
// to two different channels.
func sender(n int, c1, c2, c3, c4 chan<- int) {
	defer close(c1)
	defer close(c2)
	defer close(c3)
	defer close(c4)

	for i := 0; i < n; i++ {
		select {
		case c1 <- i:
		case c2 <- i:
		case c3 <- i:
		case c4 <- i:
		}
	}
}

// mux receives the values from sender and forwards them onto another channel.
// It would be simpler to just have sender's four cases all be the same
// channel, but this doesn't actually trigger the bug.
func mux(out chan<- int, in <-chan int, done chan<- bool) {
	for v := range in {
		out <- v
	}
	done <- true
}

// recver gets a steam of values from the four mux's and checks for duplicates.
func recver(in <-chan int) {
	seen := make(map[int]bool)

	for v := range in {
		if _, ok := seen[v]; ok {
			println("got duplicate value: ", v)
			panic("fail")
		}
		seen[v] = true
	}
}

func main() {
	runtime.GOMAXPROCS(2)

	c1 := make(chan int)
	c2 := make(chan int)
	c3 := make(chan int)
	c4 := make(chan int)
	done := make(chan bool)
	cmux := make(chan int)
	go sender(*iterations, c1, c2, c3, c4)
	go mux(cmux, c1, done)
	go mux(cmux, c2, done)
	go mux(cmux, c3, done)
	go mux(cmux, c4, done)
	go func() {
		<-done
		<-done
		<-done
		<-done
		close(cmux)
	}()
	// We keep the recver because it might catch more bugs in the future.
	// However, the result of the bug linked to at the top is that we'll
	// end up panicking with: "throw: bad g->status in ready".
	recver(cmux)
}
<commit_msg>test/chan: add missing flag.Parse in doubleselect.go<commit_after>// run

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Test the situation in which two cases of a select can
// both end up running. See http://codereview.appspot.com/180068.

package main

import (
	"flag"
	"runtime"
)

var iterations *int = flag.Int("n", 100000, "number of iterations")

// sender sends a counter to one of four different channels. If two
// cases both end up running in the same iteration, the same value will be sent
// to two different channels.
func sender(n int, c1, c2, c3, c4 chan<- int) {
	defer close(c1)
	defer close(c2)
	defer close(c3)
	defer close(c4)

	for i := 0; i < n; i++ {
		select {
		case c1 <- i:
		case c2 <- i:
		case c3 <- i:
		case c4 <- i:
		}
	}
}

// mux receives the values from sender and forwards them onto another channel.
// It would be simpler to just have sender's four cases all be the same
// channel, but this doesn't actually trigger the bug.
func mux(out chan<- int, in <-chan int, done chan<- bool) {
	for v := range in {
		out <- v
	}
	done <- true
}

// recver gets a steam of values from the four mux's and checks for duplicates.
func recver(in <-chan int) {
	seen := make(map[int]bool)

	for v := range in {
		if _, ok := seen[v]; ok {
			println("got duplicate value: ", v)
			panic("fail")
		}
		seen[v] = true
	}
}

func main() {
	runtime.GOMAXPROCS(2)

	flag.Parse()
	c1 := make(chan int)
	c2 := make(chan int)
	c3 := make(chan int)
	c4 := make(chan int)
	done := make(chan bool)
	cmux := make(chan int)
	go sender(*iterations, c1, c2, c3, c4)
	go mux(cmux, c1, done)
	go mux(cmux, c2, done)
	go mux(cmux, c3, done)
	go mux(cmux, c4, done)
	go func() {
		<-done
		<-done
		<-done
		<-done
		close(cmux)
	}()
	// We keep the recver because it might catch more bugs in the future.
	// However, the result of the bug linked to at the top is that we'll
	// end up panicking with: "throw: bad g->status in ready".
	recver(cmux)
}
<|endoftext|>