<commit_before>package messages

import (
	"bytes"
	"fmt"
	"io"
	"strings"
)

const (
	maxLineLength = 80
)

var (
	newLine = []byte{'\n'}
)

func writeString(w io.Writer, prefix, str string) error {
	quoted := fmt.Sprintf("%q", str)
	if len(quoted)+len(prefix)+2 < maxLineLength {
		// No splitting
		_, err := io.WriteString(w, fmt.Sprintf("%s %s\n", prefix, quoted))
		return err
	}
	// Splitting
	if _, err := io.WriteString(w, fmt.Sprintf("%s \"\"\n", prefix)); err != nil {
		return err
	}
	quoted = quoted[1 : len(quoted)-1]
	return writeSuffixLines(w, "\"", "\"", quoted)
}

func startLine(w io.Writer, prefix, suffix string, nl bool) (int, error) {
	if nl {
		if _, err := io.WriteString(w, suffix); err != nil {
			return 0, err
		}
		if _, err := w.Write(newLine); err != nil {
			return 0, err
		}
	}
	return io.WriteString(w, prefix)
}

func writeLines(w io.Writer, prefix, str string) error {
	return writeSuffixLines(w, prefix, "", str)
}

func writeSuffixLines(w io.Writer, prefix, suffix, str string) error {
	count, err := startLine(w, prefix, suffix, false)
	if err != nil {
		return err
	}
	sl := len(suffix)
	bs := []byte(str)
	t := len(bs)
	nl := true
	ii := 0
	for ii < t {
		b := bs[ii]
		if nl {
			if b == ' ' || b == '\t' {
				ii++
				continue
			}
			nl = false
		}
		slice := bs[ii:]
		next := bytes.IndexAny(slice, " \n")
		if next == 0 {
			ii++
			continue
		}
		if next == -1 {
			next = len(slice) - 1
		}
		if count+sl+next >= maxLineLength {
			count, err = startLine(w, prefix, suffix, true)
			if err != nil {
				return err
			}
			nl = true
		}
		c, err := w.Write(slice[:next+1])
		if err != nil {
			return err
		}
		count += c
		ii += c
		if slice[next] == '\n' {
			count, err = startLine(w, prefix, suffix, false)
			if err != nil {
				return err
			}
			nl = true
		}
	}
	if suffix != "" {
		if _, err := io.WriteString(w, suffix); err != nil {
			return err
		}
	}
	_, err = w.Write(newLine)
	return err
}

func Write(w io.Writer, messages []*Message) error {
	for _, m := range messages {
		if _, err := w.Write([]byte{'\n'}); err != nil {
			return err
		}
		if m.TranslatorComment != "" {
			if err := writeLines(w, "# ", m.TranslatorComment); err != nil {
				return err
			}
		}
		if len(m.Positions) > 1 {
			var comments []string
			positions := make([]string, len(m.Positions))
			for ii, v := range m.Positions {
				s := v.String()
				if v.Comment != "" {
					comments = append(comments, fmt.Sprintf("(%s) %s", s, v.Comment))
				}
				positions[ii] = s
			}
			if comments != nil {
				if err := writeLines(w, "#. ", strings.Join(comments, "\n")); err != nil {
					return err
				}
			}
			if err := writeLines(w, "#: ", strings.Join(positions, " ")); err != nil {
				return err
			}
		} else {
			p := m.Positions[0]
			if p.Comment != "" {
				if err := writeLines(w, "#. ", p.Comment); err != nil {
					return err
				}
			}
			if err := writeLines(w, "#: ", p.String()); err != nil {
				return err
			}
		}
		if m.Context != "" {
			if _, err := io.WriteString(w, fmt.Sprintf("msgctxt %q\n", m.Context)); err != nil {
				return err
			}
		}
		if err := writeString(w, "msgid", m.Singular); err != nil {
			return err
		}
		if m.Plural != "" {
			if err := writeString(w, "msgid_plural", m.Plural); err != nil {
				return err
			}
			tn := 2
			tl := len(m.Translations)
			if tl > tn {
				tn = tl
			}
			for ii := 0; ii < tn; ii++ {
				msgstr := ""
				if ii < tl {
					msgstr = m.Translations[ii]
				}
				if err := writeString(w, fmt.Sprintf("msgstr[%d]", ii), msgstr); err != nil {
					return err
				}
			}
		} else {
			msgstr := ""
			if len(m.Translations) > 0 {
				msgstr = m.Translations[0]
			}
			if err := writeString(w, "msgstr", msgstr); err != nil {
				return err
			}
		}
	}
	return nil
}
<commit_msg>Write the newline after the message rather than before<commit_after>package messages

import (
	"bytes"
	"fmt"
	"io"
	"strings"
)

const (
	maxLineLength = 80
)

var (
	newLine = []byte{'\n'}
)

func writeString(w io.Writer, prefix, str string) error {
	quoted := fmt.Sprintf("%q", str)
	if len(quoted)+len(prefix)+2 < maxLineLength {
		// No splitting
		_, err := io.WriteString(w, fmt.Sprintf("%s %s\n", prefix, quoted))
		return err
	}
	// Splitting
	if _, err := io.WriteString(w, fmt.Sprintf("%s \"\"\n", prefix)); err != nil {
		return err
	}
	quoted = quoted[1 : len(quoted)-1]
	return writeSuffixLines(w, "\"", "\"", quoted)
}

func startLine(w io.Writer, prefix, suffix string, nl bool) (int, error) {
	if nl {
		if _, err := io.WriteString(w, suffix); err != nil {
			return 0, err
		}
		if _, err := w.Write(newLine); err != nil {
			return 0, err
		}
	}
	return io.WriteString(w, prefix)
}

func writeLines(w io.Writer, prefix, str string) error {
	return writeSuffixLines(w, prefix, "", str)
}

func writeSuffixLines(w io.Writer, prefix, suffix, str string) error {
	count, err := startLine(w, prefix, suffix, false)
	if err != nil {
		return err
	}
	sl := len(suffix)
	bs := []byte(str)
	t := len(bs)
	nl := true
	ii := 0
	for ii < t {
		b := bs[ii]
		if nl {
			if b == ' ' || b == '\t' {
				ii++
				continue
			}
			nl = false
		}
		slice := bs[ii:]
		next := bytes.IndexAny(slice, " \n")
		if next == 0 {
			ii++
			continue
		}
		if next == -1 {
			next = len(slice) - 1
		}
		if count+sl+next >= maxLineLength {
			count, err = startLine(w, prefix, suffix, true)
			if err != nil {
				return err
			}
			nl = true
		}
		c, err := w.Write(slice[:next+1])
		if err != nil {
			return err
		}
		count += c
		ii += c
		if slice[next] == '\n' {
			count, err = startLine(w, prefix, suffix, false)
			if err != nil {
				return err
			}
			nl = true
		}
	}
	if suffix != "" {
		if _, err := io.WriteString(w, suffix); err != nil {
			return err
		}
	}
	_, err = w.Write(newLine)
	return err
}

func Write(w io.Writer, messages []*Message) error {
	for _, m := range messages {
		if m.TranslatorComment != "" {
			if err := writeLines(w, "# ", m.TranslatorComment); err != nil {
				return err
			}
		}
		if len(m.Positions) > 1 {
			var comments []string
			positions := make([]string, len(m.Positions))
			for ii, v := range m.Positions {
				s := v.String()
				if v.Comment != "" {
					comments = append(comments, fmt.Sprintf("(%s) %s", s, v.Comment))
				}
				positions[ii] = s
			}
			if comments != nil {
				if err := writeLines(w, "#. ", strings.Join(comments, "\n")); err != nil {
					return err
				}
			}
			if err := writeLines(w, "#: ", strings.Join(positions, " ")); err != nil {
				return err
			}
		} else {
			p := m.Positions[0]
			if p.Comment != "" {
				if err := writeLines(w, "#. ", p.Comment); err != nil {
					return err
				}
			}
			if err := writeLines(w, "#: ", p.String()); err != nil {
				return err
			}
		}
		if m.Context != "" {
			if _, err := io.WriteString(w, fmt.Sprintf("msgctxt %q\n", m.Context)); err != nil {
				return err
			}
		}
		if err := writeString(w, "msgid", m.Singular); err != nil {
			return err
		}
		if m.Plural != "" {
			if err := writeString(w, "msgid_plural", m.Plural); err != nil {
				return err
			}
			tn := 2
			tl := len(m.Translations)
			if tl > tn {
				tn = tl
			}
			for ii := 0; ii < tn; ii++ {
				msgstr := ""
				if ii < tl {
					msgstr = m.Translations[ii]
				}
				if err := writeString(w, fmt.Sprintf("msgstr[%d]", ii), msgstr); err != nil {
					return err
				}
			}
		} else {
			msgstr := ""
			if len(m.Translations) > 0 {
				msgstr = m.Translations[0]
			}
			if err := writeString(w, "msgstr", msgstr); err != nil {
				return err
			}
		}
		if _, err := w.Write([]byte{'\n'}); err != nil {
			return err
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package youtube

import (
	"errors"
	"fmt"
)

var (
	ErrCipherNotFound             = errors.New("cipher not found")
	ErrInvalidCharactersInVideoID = errors.New("invalid characters in video id")
	ErrVideoIDMinLength           = errors.New("the video id must be at least 10 characters long")
	ErrReadOnClosedResBody        = errors.New("http: read on closed response body")
	ErrNotPlayableInEmbed         = errors.New("embedding of this video has been disabled")
	ErrInvalidPlaylist            = errors.New("no playlist detected or invalid playlist ID")
)

type ErrResponseStatus struct {
	Status string
	Reason string
}

func (err ErrResponseStatus) Error() string {
	if err.Status == "" {
		return "no response status found in the server's answer"
	}

	if err.Reason == "" {
		return fmt.Sprintf("response status: '%s', no reason given", err.Status)
	}

	return fmt.Sprintf("response status: '%s', reason: '%s'", err.Status, err.Reason)
}

type ErrPlayabiltyStatus struct {
	Status string
	Reason string
}

func (err ErrPlayabiltyStatus) Error() string {
	return fmt.Sprintf("cannot playback and download, status: %s, reason: %s", err.Status, err.Reason)
}

// ErrUnexpectedStatusCode is returned on unexpected HTTP status codes
type ErrUnexpectedStatusCode int

func (err ErrUnexpectedStatusCode) Error() string {
	return fmt.Sprintf("unexpected status code: %d", err)
}
<commit_msg>Use const sentinel errors<commit_after>package youtube

import (
	"fmt"
)

const (
	ErrCipherNotFound             = constError("cipher not found")
	ErrInvalidCharactersInVideoID = constError("invalid characters in video id")
	ErrVideoIDMinLength           = constError("the video id must be at least 10 characters long")
	ErrReadOnClosedResBody        = constError("http: read on closed response body")
	ErrNotPlayableInEmbed         = constError("embedding of this video has been disabled")
	ErrInvalidPlaylist            = constError("no playlist detected or invalid playlist ID")
)

type constError string

func (e constError) Error() string {
	return string(e)
}

type ErrResponseStatus struct {
	Status string
	Reason string
}

func (err ErrResponseStatus) Error() string {
	if err.Status == "" {
		return "no response status found in the server's answer"
	}

	if err.Reason == "" {
		return fmt.Sprintf("response status: '%s', no reason given", err.Status)
	}

	return fmt.Sprintf("response status: '%s', reason: '%s'", err.Status, err.Reason)
}

type ErrPlayabiltyStatus struct {
	Status string
	Reason string
}

func (err ErrPlayabiltyStatus) Error() string {
	return fmt.Sprintf("cannot playback and download, status: %s, reason: %s", err.Status, err.Reason)
}

// ErrUnexpectedStatusCode is returned on unexpected HTTP status codes
type ErrUnexpectedStatusCode int

func (err ErrUnexpectedStatusCode) Error() string {
	return fmt.Sprintf("unexpected status code: %d", err)
}
<|endoftext|>


<commit_before>/* Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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 siesta

import "errors"

//signals that an end of file or stream has been reached unexpectedly
var EOF = errors.New("End of file reached")

//happens when given value to decode as string has either negative or undecodable length
var InvalidStringLength = errors.New("Invalid string length")

//happens when given value to decode as bytes has either negative or undecodable length
var InvalidBytesLength = errors.New("Invalid bytes length")
<commit_msg>Added possible broker errors and error code mapping.<commit_after>/* Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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 siesta

import "errors"

//signals that an end of file or stream has been reached unexpectedly
var EOF = errors.New("End of file reached")

//happens when given value to decode as string has either negative or undecodable length
var InvalidStringLength = errors.New("Invalid string length")

//happens when given value to decode as bytes has either negative or undecodable length
var InvalidBytesLength = errors.New("Invalid bytes length")

var NoError = errors.New("No error - it worked!")

var Unknown = errors.New("An unexpected server error")

var OffsetOutOfRange = errors.New("The requested offset is outside the range of offsets maintained by the server for the given topic/partition.")

var InvalidMessage = errors.New("Message contents does not match its CRC")

var UnknownTopicOrPartition = errors.New("This request is for a topic or partition that does not exist on this broker.")

var InvalidMessageSize = errors.New("The message has a negative size")

var LeaderNotAvailable = errors.New("In the middle of a leadership election and there is currently no leader for this partition and hence it is unavailable for writes.")

var NotLeaderForPartition = errors.New("You've just attempted to send messages to a replica that is not the leader for some partition. It indicates that the clients metadata is out of date.")

var RequestTimedOut = errors.New("Request exceeds the user-specified time limit in the request.")

var BrokerNotAvailable = errors.New("Broker is likely not alive.")

var ReplicaNotAvailable = errors.New("Replica is expected on a broker, but is not (this can be safely ignored).")

var MessageSizeTooLarge = errors.New("You've just attempted to produce a message of size larger than broker is allowed to accept.")

var StaleControllerEpochCode = errors.New("Broker-to-broker communication fault.")

var OffsetMetadataTooLargeCode = errors.New("You've jsut specified a string larger than configured maximum for offset metadata.")

var OffsetsLoadInProgressCode = errors.New("Offset loading is in progress. (Usually happens after a leader change for that offsets topic partition).")

var ConsumerCoordinatorNotAvailableCode = errors.New("Offsets topic has not yet been created.")

var NotCoordinatorForConsumerCode = errors.New("There is no coordinator for this consumer.")

var BrokerErrors = map[int]error {
	-1: Unknown,
	0: NoError,
	1: OffsetOutOfRange,
	2: InvalidMessage,
	3: UnknownTopicOrPartition,
	4: InvalidMessageSize,
	5: LeaderNotAvailable,
	6: NotLeaderForPartition,
	7: RequestTimedOut,
	8: BrokerNotAvailable,
	9: ReplicaNotAvailable,
	10: MessageSizeTooLarge,
	11: StaleControllerEpochCode,
	12: OffsetMetadataTooLargeCode,
	14: OffsetsLoadInProgressCode,
	15: ConsumerCoordinatorNotAvailableCode,
	16: NotCoordinatorForConsumerCode,
}
<|endoftext|>


<commit_before>package util

import (
	"log"
	"runtime"
)

func CheckErr(err error) {
	if err != nil {
		log.SetFlags(0)
		_, filename, lineno, ok := runtime.Caller(1)
		if ok {
			log.Fatalf("%v:%v: %v\n", filename, lineno, err)
		} else {
			log.Fatalln(err)
		}
	}
}

func WarnErr(err error) {
	if err != nil {
		f := log.Flags()
		log.SetFlags(0)
		_, filename, lineno, ok := runtime.Caller(1)
		if ok {
			log.Printf("%v:%v: %v\n", filename, lineno, err)
		} else {
			log.Println(err)
		}
		log.SetFlags(f)
	}
}
<commit_msg>WarnError() : return original error<commit_after>package util

import (
	"log"
	"runtime"
)

func CheckErr(err error) {
	if err != nil {
		log.SetFlags(0)
		_, filename, lineno, ok := runtime.Caller(1)
		if ok {
			log.Fatalf("%v:%v: %v\n", filename, lineno, err)
		} else {
			log.Fatalln(err)
		}
	}
}

func WarnErr(err error) error {
	if err != nil {
		f := log.Flags()
		log.SetFlags(0)
		_, filename, lineno, ok := runtime.Caller(1)
		if ok {
			log.Printf("%v:%v: %v\n", filename, lineno, err)
		} else {
			log.Println(err)
		}
		log.SetFlags(f)
	}
	return err
}
<|endoftext|>


<commit_before>package jwt

import (
	"errors"
)

// Error constants
var (
	ErrInvalidKey      = errors.New("key is invalid")
	ErrInvalidKeyType  = errors.New("key is of invalid type")
	ErrHashUnavailable = errors.New("the requested hash function is unavailable")
)

// The errors that might occur when parsing and validating a token
const (
	ValidationErrorMalformed        uint32 = 1 << iota // Token is malformed
	ValidationErrorUnverifiable                        // Token could not be verified because of signing problems
	ValidationErrorSignatureInvalid                    // Signature validation failed

	// Standard Claim validation errors
	ValidationErrorAudience      // AUD validation failed
	ValidationErrorExpired       // EXP validation failed
	ValidationErrorIssuedAt      // IAT validation failed
	ValidationErrorIssuer        // ISS validation failed
	ValidationErrorNotValidYet   // NBF validation failed
	ValidationErrorId            // JTI validation failed
	ValidationErrorClaimsInvalid // Generic claims validation error
)

// Helper for constructing a ValidationError with a string error message
func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
	return &ValidationError{
		Inner:  errors.New(errorText),
		Errors: errorFlags,
	}
}

// The error from Parse if token is not valid
type ValidationError struct {
	Inner  error  // stores the error returned by external dependencies, i.e.: KeyFunc
	Errors uint32 // bitfield.  see ValidationError... constants
}

// Validation error is an error type
func (e ValidationError) Error() string {
	if e.Inner == nil {
		return "token is invalid"
	}
	return e.Inner.Error()
}

// No errors
func (e *ValidationError) valid() bool {
	if e.Errors > 0 {
		return false
	}
	return true
}
<commit_msg>errors only have an exposed Inner property if the error was generated by another library<commit_after>package jwt

import (
	"errors"
)

// Error constants
var (
	ErrInvalidKey      = errors.New("key is invalid")
	ErrInvalidKeyType  = errors.New("key is of invalid type")
	ErrHashUnavailable = errors.New("the requested hash function is unavailable")
)

// The errors that might occur when parsing and validating a token
const (
	ValidationErrorMalformed        uint32 = 1 << iota // Token is malformed
	ValidationErrorUnverifiable                        // Token could not be verified because of signing problems
	ValidationErrorSignatureInvalid                    // Signature validation failed

	// Standard Claim validation errors
	ValidationErrorAudience      // AUD validation failed
	ValidationErrorExpired       // EXP validation failed
	ValidationErrorIssuedAt      // IAT validation failed
	ValidationErrorIssuer        // ISS validation failed
	ValidationErrorNotValidYet   // NBF validation failed
	ValidationErrorId            // JTI validation failed
	ValidationErrorClaimsInvalid // Generic claims validation error
)

// Helper for constructing a ValidationError with a string error message
func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
	return &ValidationError{
		text:   errorText,
		Errors: errorFlags,
	}
}

// The error from Parse if token is not valid
type ValidationError struct {
	Inner  error  // stores the error returned by external dependencies, i.e.: KeyFunc
	Errors uint32 // bitfield.  see ValidationError... constants
	text   string // errors that do not have a valid error just have text
}

// Validation error is an error type
func (e ValidationError) Error() string {
	if e.Inner != nil {
		return e.Inner.Error()
	} else if e.text != "" {
		return e.text
	} else {
		return "token is invalid"
	}
	return e.Inner.Error()
}

// No errors
func (e *ValidationError) valid() bool {
	if e.Errors > 0 {
		return false
	}
	return true
}
<|endoftext|>


<commit_before>// Package errors provides simple error handling primitives.
//
// The traditional error handling idiom in Go is roughly akin to
//
//     if err != nil {
//             return err
//     }
//
// which applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error.
//
// Adding context to an error
//
// The errors.Wrap function returns a new error that adds context to the
// original error. For example
//
//     _, err := ioutil.ReadAll(r)
//     if err != nil {
//             return errors.Wrap(err, "read failed")
//     }
//
// Retrieving the cause of an error
//
// Using errors.Wrap constructs a stack of errors, adding context to the
// preceding error. Depending on the nature of the error it may be necessary
// to reverse the operation of errors.Wrap to retrieve the original error
// for inspection. Any error value which implements this interface
//
//     type causer interface {
//             Cause() error
//     }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be
// the original cause. For example:
//
//     switch err := errors.Cause(err).(type) {
//     case *MyError:
//             // handle specifically
//     default:
//             // unknown error
//     }
//
// causer interface is not exported by this package, but is considered a part
// of stable public API.
//
// Formatted printing of errors
//
// All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported
//
//     %s    print the error. If the error has a Cause it will be
//           printed recursively
//     %v    see %s
//     %+v   extended format. Each Frame of the error's StackTrace will
//           be printed in detail.
//
// Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface.
//
//     type stackTracer interface {
//             StackTrace() errors.StackTrace
//     }
//
// Where errors.StackTrace is defined as
//
//     type StackTrace []Frame
//
// The Frame type represents a call site in the stack trace. Frame supports
// the fmt.Formatter interface that can be used for printing information about
// the stack trace of this error. For example:
//
//     if err, ok := err.(stackTracer); ok {
//             for _, f := range err.StackTrace() {
//                     fmt.Printf("%+s:%d", f)
//             }
//     }
//
// stackTracer interface is not exported by this package, but is considered a part
// of stable public API.
//
// See the documentation for Frame.Format for more details.
package errors

import (
	"fmt"
	"io"
)

// New returns an error with the supplied message.
// New also records the stack trace at the point it was called.
func New(message string) error {
	return &fundamental{
		msg:   message,
		stack: callers(),
	}
}

// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
// Errorf also records the stack trace at the point it was called.
func Errorf(format string, args ...interface{}) error {
	return &fundamental{
		msg:   fmt.Sprintf(format, args...),
		stack: callers(),
	}
}

// fundamental is an error that has a message and a stack, but no caller.
type fundamental struct {
	msg string
	*stack
}

func (f *fundamental) Error() string { return f.msg }

func (f *fundamental) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			io.WriteString(s, f.msg)
			f.stack.Format(s, verb)
			return
		}
		fallthrough
	case 's':
		io.WriteString(s, f.msg)
	case 'q':
		fmt.Fprintf(s, "%q", f.msg)
	}
}

// WithStack annotates err with a stack trace at the point WithStack was called.
// If err is nil, WithStack returns nil.
func WithStack(err error) error {
	if err == nil {
		return nil
	}
	return &withStack{
		err,
		callers(),
	}
}

type withStack struct {
	error
	*stack
}

func (w *withStack) Cause() error { return w.error }

func (w *withStack) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			fmt.Fprintf(s, "%+v", w.Cause())
			w.stack.Format(s, verb)
			return
		}
		fallthrough
	case 's':
		io.WriteString(s, w.Error())
	case 'q':
		fmt.Fprintf(s, "%q", w.Error())
	}
}

// Wrap returns an error annotating err with message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
	if err == nil {
		return nil
	}
	err = &withMessage{
		cause: err,
		msg:   message,
	}
	return &withStack{
		err,
		callers(),
	}
}

// Wrapf returns an error annotating err with the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
	if err == nil {
		return nil
	}
	err = &withMessage{
		cause: err,
		msg:   fmt.Sprintf(format, args...),
	}
	return &withStack{
		err,
		callers(),
	}
}

// WithMessage annotates err with a new message.
// If err is nil, WithStack returns nil.
func WithMessage(err error, message string) error {
	if err == nil {
		return nil
	}
	return &withMessage{
		cause: err,
		msg:   message,
	}
}

type withMessage struct {
	cause error
	msg   string
}

func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
func (w *withMessage) Cause() error  { return w.cause }

func (w *withMessage) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			fmt.Fprintf(s, "%+v\n", w.Cause())
			io.WriteString(s, w.msg)
			return
		}
		fallthrough
	case 's', 'q':
		io.WriteString(s, w.Error())
	}
}

// Cause returns the underlying cause of the error, if possible.
// An error value has a cause if it implements the following
// interface:
//
//     type causer interface {
//            Cause() error
//     }
//
// If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further
// investigation.
func Cause(err error) error {
	type causer interface {
		Cause() error
	}

	for err != nil {
		cause, ok := err.(causer)
		if !ok {
			break
		}
		err = cause.Cause()
	}
	return err
}
<commit_msg>Fix comment on WithMessage function (#86)<commit_after>// Package errors provides simple error handling primitives.
//
// The traditional error handling idiom in Go is roughly akin to
//
//     if err != nil {
//             return err
//     }
//
// which applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error.
//
// Adding context to an error
//
// The errors.Wrap function returns a new error that adds context to the
// original error. For example
//
//     _, err := ioutil.ReadAll(r)
//     if err != nil {
//             return errors.Wrap(err, "read failed")
//     }
//
// Retrieving the cause of an error
//
// Using errors.Wrap constructs a stack of errors, adding context to the
// preceding error. Depending on the nature of the error it may be necessary
// to reverse the operation of errors.Wrap to retrieve the original error
// for inspection. Any error value which implements this interface
//
//     type causer interface {
//             Cause() error
//     }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be
// the original cause. For example:
//
//     switch err := errors.Cause(err).(type) {
//     case *MyError:
//             // handle specifically
//     default:
//             // unknown error
//     }
//
// causer interface is not exported by this package, but is considered a part
// of stable public API.
//
// Formatted printing of errors
//
// All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported
//
//     %s    print the error. If the error has a Cause it will be
//           printed recursively
//     %v    see %s
//     %+v   extended format. Each Frame of the error's StackTrace will
//           be printed in detail.
//
// Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface.
//
//     type stackTracer interface {
//             StackTrace() errors.StackTrace
//     }
//
// Where errors.StackTrace is defined as
//
//     type StackTrace []Frame
//
// The Frame type represents a call site in the stack trace. Frame supports
// the fmt.Formatter interface that can be used for printing information about
// the stack trace of this error. For example:
//
//     if err, ok := err.(stackTracer); ok {
//             for _, f := range err.StackTrace() {
//                     fmt.Printf("%+s:%d", f)
//             }
//     }
//
// stackTracer interface is not exported by this package, but is considered a part
// of stable public API.
//
// See the documentation for Frame.Format for more details.
package errors

import (
	"fmt"
	"io"
)

// New returns an error with the supplied message.
// New also records the stack trace at the point it was called.
func New(message string) error {
	return &fundamental{
		msg:   message,
		stack: callers(),
	}
}

// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
// Errorf also records the stack trace at the point it was called.
func Errorf(format string, args ...interface{}) error {
	return &fundamental{
		msg:   fmt.Sprintf(format, args...),
		stack: callers(),
	}
}

// fundamental is an error that has a message and a stack, but no caller.
type fundamental struct {
	msg string
	*stack
}

func (f *fundamental) Error() string { return f.msg }

func (f *fundamental) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			io.WriteString(s, f.msg)
			f.stack.Format(s, verb)
			return
		}
		fallthrough
	case 's':
		io.WriteString(s, f.msg)
	case 'q':
		fmt.Fprintf(s, "%q", f.msg)
	}
}

// WithStack annotates err with a stack trace at the point WithStack was called.
// If err is nil, WithStack returns nil.
func WithStack(err error) error {
	if err == nil {
		return nil
	}
	return &withStack{
		err,
		callers(),
	}
}

type withStack struct {
	error
	*stack
}

func (w *withStack) Cause() error { return w.error }

func (w *withStack) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			fmt.Fprintf(s, "%+v", w.Cause())
			w.stack.Format(s, verb)
			return
		}
		fallthrough
	case 's':
		io.WriteString(s, w.Error())
	case 'q':
		fmt.Fprintf(s, "%q", w.Error())
	}
}

// Wrap returns an error annotating err with message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
	if err == nil {
		return nil
	}
	err = &withMessage{
		cause: err,
		msg:   message,
	}
	return &withStack{
		err,
		callers(),
	}
}

// Wrapf returns an error annotating err with the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
	if err == nil {
		return nil
	}
	err = &withMessage{
		cause: err,
		msg:   fmt.Sprintf(format, args...),
	}
	return &withStack{
		err,
		callers(),
	}
}

// WithMessage annotates err with a new message.
// If err is nil, WithMessage returns nil.
func WithMessage(err error, message string) error {
	if err == nil {
		return nil
	}
	return &withMessage{
		cause: err,
		msg:   message,
	}
}

type withMessage struct {
	cause error
	msg   string
}

func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
func (w *withMessage) Cause() error  { return w.cause }

func (w *withMessage) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		if s.Flag('+') {
			fmt.Fprintf(s, "%+v\n", w.Cause())
			io.WriteString(s, w.msg)
			return
		}
		fallthrough
	case 's', 'q':
		io.WriteString(s, w.Error())
	}
}

// Cause returns the underlying cause of the error, if possible.
// An error value has a cause if it implements the following
// interface:
//
//     type causer interface {
//            Cause() error
//     }
//
// If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further
// investigation.
func Cause(err error) error {
	type causer interface {
		Cause() error
	}

	for err != nil {
		cause, ok := err.(causer)
		if !ok {
			break
		}
		err = cause.Cause()
	}
	return err
}
<|endoftext|>


<commit_before>package raft

import "reflect"

// Callback list    args
// init::done
// state::changed   old, new string
// term::changed    old, new int64

// Javascript events style
// All methods are safe
// Since it is thread safe and only one action
// can take place at the time, adding, executing,
// removing callbacks will may not be in the order
// you want to.
// TODO: keep the global channel for global actions,
// like adding or removing events, but I should add
// a local channel to edit or execute events without
// blocking all the other events.
type Events struct {
  Maps map[string][]*Event
  //Callbacks map[string]*struct{
    //C chan struct{}

  //}
  C chan struct{}
}

type Event struct {
  CallbackFunc CallbackFunc
  Once bool
  Executed bool
}

type CallbackFunc func(args ...interface{})

// .On appends a function to an array
// The function Callback should be pass as a reference
// ie: blih := func(args ...interface{}) {}
// sm.State.On("someState", blih)
// sm.State.Off("someState", blih)
// If it is passed like sm.State.On("someState", func(args ...interface{}){})
// the function will never be removable.
func (e *Events) On(name string, cb CallbackFunc) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if cbs, found := e.Maps[name]; found {
    event := &Event{
      CallbackFunc: cb,
      Once: false,
      Executed: false,
    }

    e.Maps[name] = append(cbs, event)
  } else {
    e.Maps[name] = make([]*Event, 0, 0)

    event := &Event{
      CallbackFunc: cb,
      Once: false,
      Executed: false,
    }

    e.Maps[name] = append(e.Maps[name], event)
  }
}

// .Once appends a function to an array
// When the function is executed, it will be deferenced.
// The function Callback should be pass as a reference
// ie: blih := func(args ...interface{}) {}
// sm.State.Once("someState", blih)
// sm.State.Off("someState", blih)
// If it is passed like sm.State.Once("someState", func(args ...interface{}){})
// the function will never be removable.
func (e *Events) Once(name string, cb CallbackFunc) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if cbs, found := e.Maps[name]; found {
    event := &Event{
      CallbackFunc: cb,
      Once: true,
      Executed: false,
    }

    e.Maps[name] = append(cbs, event)
  } else {
    e.Maps[name] = make([]*Event, 0, 0)

    event := &Event{
      CallbackFunc: cb,
      Once: true,
      Executed: false,
    }

    e.Maps[name] = append(e.Maps[name], event)
  }
}

// Remove a callback from the array
// The function Callback should be pass as a reference
// ie: blih := func(args ...interface{}) {}
// sm.State.On("someState", blih)
// sm.State.Off("someState", blih)
// If it is passed like sm.State.On("someState", func(args ...interface{}){})
// the function will never be removable.
func (e *Events) Off(name string, cb CallbackFunc) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if cbs, found := e.Maps[name]; found {
    length := len(cbs)

    foundAt := -1

    for i, event := range cbs{
      if reflect.ValueOf(event.CallbackFunc).Pointer() == reflect.ValueOf(cb).Pointer() {
        foundAt = i
        break
      }
    }

    if foundAt == -1 {
      return
    }

    tmp := make([]*Event, length -1)

    index := 0

    for i := 0; i < length; i++ {
      // Compare two pointer value
      if reflect.ValueOf(cbs[i].CallbackFunc).Pointer() == reflect.ValueOf(cb).Pointer() {
        continue
      }

      tmp[index] = cbs[i]
      index = index + 1
    }

    e.Maps[name] = tmp
  }
}

// Execute async all the callbacks that was registered with .On
func (e *Events) Exec(name string, args ...interface{}) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if cbs, found := e.Maps[name]; found {
    length := len(cbs)

    for i := 0; i < length; i++ {
      go func(event *Event) {
        if event.Once == true  && event.Executed == true {
        } else {
          event.CallbackFunc(args...)
          event.Executed = true

          if event.Once == true {
            e.Off(name, event.CallbackFunc)
          }
        }
      }(cbs[i])
    }
  }
}

// Execute sync all the callbacks that was registered with .On
func (e *Events) ExecSync(name string, args ...interface{}) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if cbs, found := e.Maps[name]; found {
    length := len(cbs)

    for i := 0; i < length; i++ {
      event := cbs[i]

      if event.Once == true  && event.Executed == true {
      } else {
        event.CallbackFunc(args...)
        event.Executed = true

        if event.Once == true {
          // Unlock, unspool, lock
          // Otherwise we get a deadlock
          // I know that unspooling could take time because some
          // other events could be waiting, but I need to create
          // a lock for each name to avoid global locking.
          <- e.C
          e.Off(name, event.CallbackFunc)
          e.C <- struct{}{}
        }
      }
    }
  }
}

// Creates a callback array
func NewEvents() *Events {
  e := &Events{
    Maps: make(map[string][]*Event, 0),
    C: make(chan struct{}, 1),
  }

  return e
}
<commit_msg>Renaming vars<commit_after>package raft

import "reflect"

// Callback list    args
// init::done
// state::changed   old, new string
// term::changed    old, new int64

// Javascript events style
// All methods are safe
// Since it is thread safe and only one action
// can take place at the time, adding, executing,
// removing callbacks will may not be in the order
// you want to.
// TODO: keep the global channel for global actions,
// like adding or removing callbacks, but I should add
// a local channel to edit or execute callbacks without
// blocking all the other callbacks.
type Events struct {
  Maps map[string][]*Callback
  //Maps map[string]*struct{
    //C chan struct{}
    //Callbacks []Callback
  //}
  C chan struct{}
}

type Callback struct {
  CallbackFunc CallbackFunc
  Once bool
  Executed bool
}

type CallbackFunc func(args ...interface{})

// .On appends a function to an array
// The function Callback should be pass as a reference
// ie: blih := func(args ...interface{}) {}
// sm.State.On("someState", blih)
// sm.State.Off("someState", blih)
// If it is passed like sm.State.On("someState", func(args ...interface{}){})
// the function will never be removable.
func (e *Events) On(name string, cb CallbackFunc) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if cbs, found := e.Maps[name]; found {
    callback := &Callback{
      CallbackFunc: cb,
      Once: false,
      Executed: false,
    }

    e.Maps[name] = append(cbs, callback)
  } else {
    e.Maps[name] = make([]*Callback, 0, 0)

    callback := &Callback{
      CallbackFunc: cb,
      Once: false,
      Executed: false,
    }

    e.Maps[name] = append(e.Maps[name], callback)
  }
}

// .Once appends a function to an array
// When the function is executed, it will be deferenced.
// The function Callback should be pass as a reference
// ie: blih := func(args ...interface{}) {}
// sm.State.Once("someState", blih)
// sm.State.Off("someState", blih)
// If it is passed like sm.State.Once("someState", func(args ...interface{}){})
// the function will never be removable.
func (e *Events) Once(name string, cb CallbackFunc) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if cbs, found := e.Maps[name]; found {
    callback := &Callback{
      CallbackFunc: cb,
      Once: true,
      Executed: false,
    }

    e.Maps[name] = append(cbs, callback)
  } else {
    e.Maps[name] = make([]*Callback, 0, 0)

    callback := &Callback{
      CallbackFunc: cb,
      Once: true,
      Executed: false,
    }

    e.Maps[name] = append(e.Maps[name], callback)
  }
}

// Remove a callback from the array
// The function Callback should be pass as a reference
// ie: blih := func(args ...interface{}) {}
// sm.State.On("someState", blih)
// sm.State.Off("someState", blih)
// If it is passed like sm.State.On("someState", func(args ...interface{}){})
// the function will never be removable.
func (e *Events) Off(name string, cb CallbackFunc) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if callbacks, found := e.Maps[name]; found {
    length := len(callbacks)

    foundAt := -1

    for i, callback := range callbacks {
      if reflect.ValueOf(callback.CallbackFunc).Pointer() == reflect.ValueOf(cb).Pointer() {
        foundAt = i
        break
      }
    }

    if foundAt == -1 {
      return
    }

    tmp := make([]*Callback, length -1)

    index := 0

    for i := 0; i < length; i++ {
      // Compare two pointer value
      if reflect.ValueOf(callbacks[i].CallbackFunc).Pointer() == reflect.ValueOf(cb).Pointer() {
        continue
      }

      tmp[index] = callbacks[i]
      index = index + 1
    }

    e.Maps[name] = tmp
  }
}

// Execute async all the callbacks that was registered with .On
func (e *Events) Exec(name string, args ...interface{}) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if cbs, found := e.Maps[name]; found {
    length := len(cbs)

    for i := 0; i < length; i++ {
      go func(callback *Callback) {
        if callback.Once == true  && callback.Executed == true {
        } else {
          callback.CallbackFunc(args...)
          callback.Executed = true

          if callback.Once == true {
            e.Off(name, callback.CallbackFunc)
          }
        }
      }(cbs[i])
    }
  }
}

// Execute sync all the callbacks that was registered with .On
func (e *Events) ExecSync(name string, args ...interface{}) {
  e.C <- struct{}{}
  defer func() {
    <- e.C
  }()

  if callbacks, found := e.Maps[name]; found {
    length := len(callbacks)

    for i := 0; i < length; i++ {
      callback := callbacks[i]

      if callback.Once == true  && callback.Executed == true {
      } else {
        callback.CallbackFunc(args...)
        callback.Executed = true

        if callback.Once == true {
          // Unlock, unspool, lock
          // Otherwise we get a deadlock
          // I know that unspooling could take time because some
          // other callbacks could be waiting, but I need to create
          // a lock for each name to avoid global locking.
          <- e.C
          e.Off(name, callback.CallbackFunc)
          e.C <- struct{}{}
        }
      }
    }
  }
}

// Creates a callback array
func NewEvents() *Events {
  e := &Events{
    Maps: make(map[string][]*Callback, 0),
    C: make(chan struct{}, 1),
  }

  return e
}
<|endoftext|>


<commit_before>package dom

import (
	"time"

	"github.com/gopherjs/gopherjs/js"
)

func WrapEvent(o *js.Object) Event {
	return wrapEvent(o)
}

func wrapEvent(o *js.Object) Event {
	if o == nil || o == js.Undefined {
		return nil
	}
	ev := &BasicEvent{o}
	c := o.Get("constructor")
	switch c {
	case js.Global.Get("AnimationEvent"):
		return &AnimationEvent{ev}
	case js.Global.Get("AudioProcessingEvent"):
		return &AudioProcessingEvent{ev}
	case js.Global.Get("BeforeInputEvent"):
		return &BeforeInputEvent{ev}
	case js.Global.Get("BeforeUnloadEvent"):
		return &BeforeUnloadEvent{ev}
	case js.Global.Get("BlobEvent"):
		return &BlobEvent{ev}
	case js.Global.Get("ClipboardEvent"):
		return &ClipboardEvent{ev}
	case js.Global.Get("CloseEvent"):
		return &CloseEvent{BasicEvent: ev}
	case js.Global.Get("CompositionEvent"):
		return &CompositionEvent{ev}
	case js.Global.Get("CSSFontFaceLoadEvent"):
		return &CSSFontFaceLoadEvent{ev}
	case js.Global.Get("CustomEvent"):
		return &CustomEvent{ev}
	case js.Global.Get("DeviceLightEvent"):
		return &DeviceLightEvent{ev}
	case js.Global.Get("DeviceMotionEvent"):
		return &DeviceMotionEvent{ev}
	case js.Global.Get("DeviceOrientationEvent"):
		return &DeviceOrientationEvent{ev}
	case js.Global.Get("DeviceProximityEvent"):
		return &DeviceProximityEvent{ev}
	case js.Global.Get("DOMTransactionEvent"):
		return &DOMTransactionEvent{ev}
	case js.Global.Get("DragEvent"):
		return &DragEvent{ev}
	case js.Global.Get("EditingBeforeInputEvent"):
		return &EditingBeforeInputEvent{ev}
	case js.Global.Get("ErrorEvent"):
		return &ErrorEvent{ev}
	case js.Global.Get("FocusEvent"):
		return &FocusEvent{ev}
	case js.Global.Get("GamepadEvent"):
		return &GamepadEvent{ev}
	case js.Global.Get("HashChangeEvent"):
		return &HashChangeEvent{ev}
	case js.Global.Get("IDBVersionChangeEvent"):
		return &IDBVersionChangeEvent{ev}
	case js.Global.Get("KeyboardEvent"):
		return &KeyboardEvent{BasicEvent: ev}
	case js.Global.Get("MediaStreamEvent"):
		return &MediaStreamEvent{ev}
	case js.Global.Get("MessageEvent"):
		return &MessageEvent{BasicEvent: ev}
	case js.Global.Get("MouseEvent"):
		return &MouseEvent{UIEvent: &UIEvent{ev}}
	case js.Global.Get("MutationEvent"):
		return &MutationEvent{ev}
	case js.Global.Get("OfflineAudioCompletionEvent"):
		return &OfflineAudioCompletionEvent{ev}
	case js.Global.Get("PageTransitionEvent"):
		return &PageTransitionEvent{ev}
	case js.Global.Get("PointerEvent"):
		return &PointerEvent{ev}
	case js.Global.Get("PopStateEvent"):
		return &PopStateEvent{ev}
	case js.Global.Get("ProgressEvent"):
		return &ProgressEvent{ev}
	case js.Global.Get("RelatedEvent"):
		return &RelatedEvent{ev}
	case js.Global.Get("RTCPeerConnectionIceEvent"):
		return &RTCPeerConnectionIceEvent{ev}
	case js.Global.Get("SensorEvent"):
		return &SensorEvent{ev}
	case js.Global.Get("StorageEvent"):
		return &StorageEvent{ev}
	case js.Global.Get("SVGEvent"):
		return &SVGEvent{ev}
	case js.Global.Get("SVGZoomEvent"):
		return &SVGZoomEvent{ev}
	case js.Global.Get("TimeEvent"):
		return &TimeEvent{ev}
	case js.Global.Get("TouchEvent"):
		return &TouchEvent{ev}
	case js.Global.Get("TrackEvent"):
		return &TrackEvent{ev}
	case js.Global.Get("TransitionEvent"):
		return &TransitionEvent{ev}
	case js.Global.Get("UIEvent"):
		return &UIEvent{ev}
	case js.Global.Get("UserProximityEvent"):
		return &UserProximityEvent{ev}
	case js.Global.Get("WheelEvent"):
		return &WheelEvent{BasicEvent: ev}
	default:
		return ev
	}
}

const (
	EvPhaseNone      = 0
	EvPhaseCapturing = 1
	EvPhaseAtTarget  = 2
	EvPhaseBubbling  = 3
)

type Event interface {
	Bubbles() bool
	Cancelable() bool
	CurrentTarget() Element
	DefaultPrevented() bool
	EventPhase() int
	Target() Element
	Timestamp() time.Time
	Type() string
	PreventDefault()
	StopImmediatePropagation()
	StopPropagation()
	Underlying() *js.Object
}

// Type BasicEvent implements the Event interface and is embedded by
// concrete event types.
type BasicEvent struct{ *js.Object }

type EventOptions struct {
	Bubbles    bool
	Cancelable bool
}

func CreateEvent(typ string, opts EventOptions) *BasicEvent {
	var event = js.Global.Get("Event").New(typ, js.M{
		"bubbles":    opts.Bubbles,
		"cancelable": opts.Cancelable,
	})
	return &BasicEvent{event}
}

func (ev *BasicEvent) Bubbles() bool {
	return ev.Get("bubbles").Bool()
}

func (ev *BasicEvent) Cancelable() bool {
	return ev.Get("cancelable").Bool()
}

func (ev *BasicEvent) CurrentTarget() Element {
	return wrapElement(ev.Get("currentTarget"))
}

func (ev *BasicEvent) DefaultPrevented() bool {
	return ev.Get("defaultPrevented").Bool()
}

func (ev *BasicEvent) EventPhase() int {
	return ev.Get("eventPhase").Int()
}

func (ev *BasicEvent) Target() Element {
	return wrapElement(ev.Get("target"))
}

func (ev *BasicEvent) Timestamp() time.Time {
	ms := ev.Get("timeStamp").Int()
	s := ms / 1000
	ns := (ms % 1000 * 1e6)
	return time.Unix(int64(s), int64(ns))
}

func (ev *BasicEvent) Type() string {
	return ev.Get("type").String()
}

func (ev *BasicEvent) PreventDefault() {
	ev.Call("preventDefault")
}

func (ev *BasicEvent) StopImmediatePropagation() {
	ev.Call("stopImmediatePropagation")
}

func (ev *BasicEvent) StopPropagation() {
	ev.Call("stopPropagation")
}

func (ev *BasicEvent) Underlying() *js.Object {
	return ev.Object
}

type AnimationEvent struct{ *BasicEvent }
type AudioProcessingEvent struct{ *BasicEvent }
type BeforeInputEvent struct{ *BasicEvent }
type BeforeUnloadEvent struct{ *BasicEvent }
type BlobEvent struct{ *BasicEvent }
type ClipboardEvent struct{ *BasicEvent }

type CloseEvent struct {
	*BasicEvent
	Code     int    `js:"code"`
	Reason   string `js:"reason"`
	WasClean bool   `js:"wasClean"`
}

type CompositionEvent struct{ *BasicEvent }
type CSSFontFaceLoadEvent struct{ *BasicEvent }
type CustomEvent struct{ *BasicEvent }
type DeviceLightEvent struct{ *BasicEvent }
type DeviceMotionEvent struct{ *BasicEvent }
type DeviceOrientationEvent struct{ *BasicEvent }
type DeviceProximityEvent struct{ *BasicEvent }
type DOMTransactionEvent struct{ *BasicEvent }
type DragEvent struct{ *BasicEvent }
type EditingBeforeInputEvent struct{ *BasicEvent }
type ErrorEvent struct{ *BasicEvent }

type FocusEvent struct{ *BasicEvent }

func (ev *FocusEvent) RelatedTarget() Element {
	return wrapElement(ev.Get("relatedTarget"))
}

type GamepadEvent struct{ *BasicEvent }
type HashChangeEvent struct{ *BasicEvent }
type IDBVersionChangeEvent struct{ *BasicEvent }

const (
	KeyLocationStandard = 0
	KeyLocationLeft     = 1
	KeyLocationRight    = 2
	KeyLocationNumpad   = 3
)

type KeyboardEvent struct {
	*BasicEvent
	AltKey        bool   `js:"altKey"`
	CharCode      int    `js:"charCode"`
	CtrlKey       bool   `js:"ctrlKey"`
	Key           string `js:"key"`
	KeyIdentifier string `js:"keyIdentifier"`
	KeyCode       int    `js:"keyCode"`
	Locale        string `js:"locale"`
	Location      int    `js:"location"`
	KeyLocation   int    `js:"keyLocation"`
	MetaKey       bool   `js:"metaKey"`
	Repeat        bool   `js:"repeat"`
	ShiftKey      bool   `js:"shiftKey"`
}

func (ev *KeyboardEvent) ModifierState(mod string) bool {
	return ev.Call("getModifierState", mod).Bool()
}

type MediaStreamEvent struct{ *BasicEvent }

type MessageEvent struct {
	*BasicEvent
	Data *js.Object `js:"data"`
}

type MouseEvent struct {
	*UIEvent
	AltKey    bool `js:"altKey"`
	Button    int  `js:"button"`
	ClientX   int  `js:"clientX"`
	ClientY   int  `js:"clientY"`
	CtrlKey   bool `js:"ctrlKey"`
	MetaKey   bool `js:"metaKey"`
	MovementX int  `js:"movementX"`
	MovementY int  `js:"movementY"`
	ScreenX   int  `js:"screenX"`
	ScreenY   int  `js:"screenY"`
	ShiftKey  bool `js:"shiftKey"`
}

func (ev *MouseEvent) RelatedTarget() Element {
	return wrapElement(ev.Get("relatedTarget"))
}

func (ev *MouseEvent) ModifierState(mod string) bool {
	return ev.Call("getModifierState", mod).Bool()
}

type MutationEvent struct{ *BasicEvent }
type OfflineAudioCompletionEvent struct{ *BasicEvent }
type PageTransitionEvent struct{ *BasicEvent }
type PointerEvent struct{ *BasicEvent }
type PopStateEvent struct{ *BasicEvent }
type ProgressEvent struct{ *BasicEvent }
type RelatedEvent struct{ *BasicEvent }
type RTCPeerConnectionIceEvent struct{ *BasicEvent }
type SensorEvent struct{ *BasicEvent }
type StorageEvent struct{ *BasicEvent }
type SVGEvent struct{ *BasicEvent }
type SVGZoomEvent struct{ *BasicEvent }
type TimeEvent struct{ *BasicEvent }
type TouchEvent struct{ *BasicEvent }
type TrackEvent struct{ *BasicEvent }
type TransitionEvent struct{ *BasicEvent }
type UIEvent struct{ *BasicEvent }
type UserProximityEvent struct{ *BasicEvent }

const (
	DeltaPixel = 0
	DeltaLine  = 1
	DeltaPage  = 2
)

type WheelEvent struct {
	*BasicEvent
	DeltaX    float64 `js:"deltaX"`
	DeltaY    float64 `js:"deltaY"`
	DeltaZ    float64 `js:"deltaZ"`
	DeltaMode int     `js:"deltaMode"`
}

type EventTarget interface {
	// AddEventListener adds a new event listener and returns the
	// wrapper function it generated. If using RemoveEventListener,
	// that wrapper has to be used.
	AddEventListener(typ string, useCapture bool, listener func(Event)) func(*js.Object)
	RemoveEventListener(typ string, useCapture bool, listener func(*js.Object))
	DispatchEvent(event Event) bool
}
<commit_msg>Implement TouchEvent internals; add Touch<commit_after>package dom

import (
	"time"

	"github.com/gopherjs/gopherjs/js"
)

func WrapEvent(o *js.Object) Event {
	return wrapEvent(o)
}

func wrapEvent(o *js.Object) Event {
	if o == nil || o == js.Undefined {
		return nil
	}
	ev := &BasicEvent{o}
	c := o.Get("constructor")
	switch c {
	case js.Global.Get("AnimationEvent"):
		return &AnimationEvent{ev}
	case js.Global.Get("AudioProcessingEvent"):
		return &AudioProcessingEvent{ev}
	case js.Global.Get("BeforeInputEvent"):
		return &BeforeInputEvent{ev}
	case js.Global.Get("BeforeUnloadEvent"):
		return &BeforeUnloadEvent{ev}
	case js.Global.Get("BlobEvent"):
		return &BlobEvent{ev}
	case js.Global.Get("ClipboardEvent"):
		return &ClipboardEvent{ev}
	case js.Global.Get("CloseEvent"):
		return &CloseEvent{BasicEvent: ev}
	case js.Global.Get("CompositionEvent"):
		return &CompositionEvent{ev}
	case js.Global.Get("CSSFontFaceLoadEvent"):
		return &CSSFontFaceLoadEvent{ev}
	case js.Global.Get("CustomEvent"):
		return &CustomEvent{ev}
	case js.Global.Get("DeviceLightEvent"):
		return &DeviceLightEvent{ev}
	case js.Global.Get("DeviceMotionEvent"):
		return &DeviceMotionEvent{ev}
	case js.Global.Get("DeviceOrientationEvent"):
		return &DeviceOrientationEvent{ev}
	case js.Global.Get("DeviceProximityEvent"):
		return &DeviceProximityEvent{ev}
	case js.Global.Get("DOMTransactionEvent"):
		return &DOMTransactionEvent{ev}
	case js.Global.Get("DragEvent"):
		return &DragEvent{ev}
	case js.Global.Get("EditingBeforeInputEvent"):
		return &EditingBeforeInputEvent{ev}
	case js.Global.Get("ErrorEvent"):
		return &ErrorEvent{ev}
	case js.Global.Get("FocusEvent"):
		return &FocusEvent{ev}
	case js.Global.Get("GamepadEvent"):
		return &GamepadEvent{ev}
	case js.Global.Get("HashChangeEvent"):
		return &HashChangeEvent{ev}
	case js.Global.Get("IDBVersionChangeEvent"):
		return &IDBVersionChangeEvent{ev}
	case js.Global.Get("KeyboardEvent"):
		return &KeyboardEvent{BasicEvent: ev}
	case js.Global.Get("MediaStreamEvent"):
		return &MediaStreamEvent{ev}
	case js.Global.Get("MessageEvent"):
		return &MessageEvent{BasicEvent: ev}
	case js.Global.Get("MouseEvent"):
		return &MouseEvent{UIEvent: &UIEvent{ev}}
	case js.Global.Get("MutationEvent"):
		return &MutationEvent{ev}
	case js.Global.Get("OfflineAudioCompletionEvent"):
		return &OfflineAudioCompletionEvent{ev}
	case js.Global.Get("PageTransitionEvent"):
		return &PageTransitionEvent{ev}
	case js.Global.Get("PointerEvent"):
		return &PointerEvent{ev}
	case js.Global.Get("PopStateEvent"):
		return &PopStateEvent{ev}
	case js.Global.Get("ProgressEvent"):
		return &ProgressEvent{ev}
	case js.Global.Get("RelatedEvent"):
		return &RelatedEvent{ev}
	case js.Global.Get("RTCPeerConnectionIceEvent"):
		return &RTCPeerConnectionIceEvent{ev}
	case js.Global.Get("SensorEvent"):
		return &SensorEvent{ev}
	case js.Global.Get("StorageEvent"):
		return &StorageEvent{ev}
	case js.Global.Get("SVGEvent"):
		return &SVGEvent{ev}
	case js.Global.Get("SVGZoomEvent"):
		return &SVGZoomEvent{ev}
	case js.Global.Get("TimeEvent"):
		return &TimeEvent{ev}
	case js.Global.Get("TouchEvent"):
		return &TouchEvent{BasicEvent: ev}
	case js.Global.Get("TrackEvent"):
		return &TrackEvent{ev}
	case js.Global.Get("TransitionEvent"):
		return &TransitionEvent{ev}
	case js.Global.Get("UIEvent"):
		return &UIEvent{ev}
	case js.Global.Get("UserProximityEvent"):
		return &UserProximityEvent{ev}
	case js.Global.Get("WheelEvent"):
		return &WheelEvent{BasicEvent: ev}
	default:
		return ev
	}
}

const (
	EvPhaseNone      = 0
	EvPhaseCapturing = 1
	EvPhaseAtTarget  = 2
	EvPhaseBubbling  = 3
)

type Event interface {
	Bubbles() bool
	Cancelable() bool
	CurrentTarget() Element
	DefaultPrevented() bool
	EventPhase() int
	Target() Element
	Timestamp() time.Time
	Type() string
	PreventDefault()
	StopImmediatePropagation()
	StopPropagation()
	Underlying() *js.Object
}

// Type BasicEvent implements the Event interface and is embedded by
// concrete event types.
type BasicEvent struct{ *js.Object }

type EventOptions struct {
	Bubbles    bool
	Cancelable bool
}

func CreateEvent(typ string, opts EventOptions) *BasicEvent {
	var event = js.Global.Get("Event").New(typ, js.M{
		"bubbles":    opts.Bubbles,
		"cancelable": opts.Cancelable,
	})
	return &BasicEvent{event}
}

func (ev *BasicEvent) Bubbles() bool {
	return ev.Get("bubbles").Bool()
}

func (ev *BasicEvent) Cancelable() bool {
	return ev.Get("cancelable").Bool()
}

func (ev *BasicEvent) CurrentTarget() Element {
	return wrapElement(ev.Get("currentTarget"))
}

func (ev *BasicEvent) DefaultPrevented() bool {
	return ev.Get("defaultPrevented").Bool()
}

func (ev *BasicEvent) EventPhase() int {
	return ev.Get("eventPhase").Int()
}

func (ev *BasicEvent) Target() Element {
	return wrapElement(ev.Get("target"))
}

func (ev *BasicEvent) Timestamp() time.Time {
	ms := ev.Get("timeStamp").Int()
	s := ms / 1000
	ns := (ms % 1000 * 1e6)
	return time.Unix(int64(s), int64(ns))
}

func (ev *BasicEvent) Type() string {
	return ev.Get("type").String()
}

func (ev *BasicEvent) PreventDefault() {
	ev.Call("preventDefault")
}

func (ev *BasicEvent) StopImmediatePropagation() {
	ev.Call("stopImmediatePropagation")
}

func (ev *BasicEvent) StopPropagation() {
	ev.Call("stopPropagation")
}

func (ev *BasicEvent) Underlying() *js.Object {
	return ev.Object
}

type AnimationEvent struct{ *BasicEvent }
type AudioProcessingEvent struct{ *BasicEvent }
type BeforeInputEvent struct{ *BasicEvent }
type BeforeUnloadEvent struct{ *BasicEvent }
type BlobEvent struct{ *BasicEvent }
type ClipboardEvent struct{ *BasicEvent }

type CloseEvent struct {
	*BasicEvent
	Code     int    `js:"code"`
	Reason   string `js:"reason"`
	WasClean bool   `js:"wasClean"`
}

type CompositionEvent struct{ *BasicEvent }
type CSSFontFaceLoadEvent struct{ *BasicEvent }
type CustomEvent struct{ *BasicEvent }
type DeviceLightEvent struct{ *BasicEvent }
type DeviceMotionEvent struct{ *BasicEvent }
type DeviceOrientationEvent struct{ *BasicEvent }
type DeviceProximityEvent struct{ *BasicEvent }
type DOMTransactionEvent struct{ *BasicEvent }
type DragEvent struct{ *BasicEvent }
type EditingBeforeInputEvent struct{ *BasicEvent }
type ErrorEvent struct{ *BasicEvent }

type FocusEvent struct{ *BasicEvent }

func (ev *FocusEvent) RelatedTarget() Element {
	return wrapElement(ev.Get("relatedTarget"))
}

type GamepadEvent struct{ *BasicEvent }
type HashChangeEvent struct{ *BasicEvent }
type IDBVersionChangeEvent struct{ *BasicEvent }

const (
	KeyLocationStandard = 0
	KeyLocationLeft     = 1
	KeyLocationRight    = 2
	KeyLocationNumpad   = 3
)

type KeyboardEvent struct {
	*BasicEvent
	AltKey        bool   `js:"altKey"`
	CharCode      int    `js:"charCode"`
	CtrlKey       bool   `js:"ctrlKey"`
	Key           string `js:"key"`
	KeyIdentifier string `js:"keyIdentifier"`
	KeyCode       int    `js:"keyCode"`
	Locale        string `js:"locale"`
	Location      int    `js:"location"`
	KeyLocation   int    `js:"keyLocation"`
	MetaKey       bool   `js:"metaKey"`
	Repeat        bool   `js:"repeat"`
	ShiftKey      bool   `js:"shiftKey"`
}

func (ev *KeyboardEvent) ModifierState(mod string) bool {
	return ev.Call("getModifierState", mod).Bool()
}

type MediaStreamEvent struct{ *BasicEvent }

type MessageEvent struct {
	*BasicEvent
	Data *js.Object `js:"data"`
}

type MouseEvent struct {
	*UIEvent
	AltKey    bool `js:"altKey"`
	Button    int  `js:"button"`
	ClientX   int  `js:"clientX"`
	ClientY   int  `js:"clientY"`
	CtrlKey   bool `js:"ctrlKey"`
	MetaKey   bool `js:"metaKey"`
	MovementX int  `js:"movementX"`
	MovementY int  `js:"movementY"`
	ScreenX   int  `js:"screenX"`
	ScreenY   int  `js:"screenY"`
	ShiftKey  bool `js:"shiftKey"`
}

func (ev *MouseEvent) RelatedTarget() Element {
	return wrapElement(ev.Get("relatedTarget"))
}

func (ev *MouseEvent) ModifierState(mod string) bool {
	return ev.Call("getModifierState", mod).Bool()
}

type MutationEvent struct{ *BasicEvent }
type OfflineAudioCompletionEvent struct{ *BasicEvent }
type PageTransitionEvent struct{ *BasicEvent }
type PointerEvent struct{ *BasicEvent }
type PopStateEvent struct{ *BasicEvent }
type ProgressEvent struct{ *BasicEvent }
type RelatedEvent struct{ *BasicEvent }
type RTCPeerConnectionIceEvent struct{ *BasicEvent }
type SensorEvent struct{ *BasicEvent }
type StorageEvent struct{ *BasicEvent }
type SVGEvent struct{ *BasicEvent }
type SVGZoomEvent struct{ *BasicEvent }
type TimeEvent struct{ *BasicEvent }

// TouchEvent represents an event sent when the state of contacts with a touch-sensitive
// surface changes. This surface can be a touch screen or trackpad, for example. The event
// can describe one or more points of contact with the screen and includes support for
// detecting movement, addition and removal of contact points, and so forth.
//
// Reference: https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent.
type TouchEvent struct {
	*BasicEvent
	AltKey   bool `js:"altKey"`
	CtrlKey  bool `js:"ctrlKey"`
	MetaKey  bool `js:"metaKey"`
	ShiftKey bool `js:"shiftKey"`
}

// ChangedTouches lists all individual points of contact whose states changed between
// the previous touch event and this one.
//
// Reference: https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches.
func (ev *TouchEvent) ChangedTouches() []*Touch {
	return touchListToTouches(ev.Get("changedTouches"))
}

// TargetTouches lists all points of contact that are both currently in contact with the
// touch surface and were also started on the same element that is the target of the event.
//
// Reference: https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/targetTouches.
func (ev *TouchEvent) TargetTouches() []*Touch {
	return touchListToTouches(ev.Get("targetTouches"))
}

// Touches lists all current points of contact with the surface, regardless of target
// or changed status.
//
// Reference: https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches.
func (ev *TouchEvent) Touches() []*Touch {
	return touchListToTouches(ev.Get("touches"))
}

func touchListToTouches(tl *js.Object) []*Touch {
	out := make([]*Touch, tl.Length())
	for i := range out {
		out[i] = &Touch{Object: tl.Index(i)}
	}
	return out
}

// Touch represents a single contact point on a touch-sensitive device. The contact point
// is commonly a finger or stylus and the device may be a touchscreen or trackpad.
//
// Reference: https://developer.mozilla.org/en-US/docs/Web/API/Touch.
type Touch struct {
	*js.Object
	Identifier    int     `js:"identifier"`
	ScreenX       float64 `js:"screenX"`
	ScreenY       float64 `js:"screenY"`
	ClientX       float64 `js:"clientX"`
	ClientY       float64 `js:"clientY"`
	PageX         float64 `js:"pageX"`
	PageY         float64 `js:"pageY"`
	RadiusX       float64 `js:"radiusX"`
	RadiusY       float64 `js:"radiusY"`
	RotationAngle float64 `js:"rotationAngle"`
	Force         float64 `js:"force"`
}

// Target returns the Element on which the touch point started when it was first placed
// on the surface, even if the touch point has since moved outside the interactive area
// of that element or even been removed from the document.
//
// Reference: https://developer.mozilla.org/en-US/docs/Web/API/Touch/target.
func (t *Touch) Target() Element {
	return wrapElement(t.Get("target"))
}

type TrackEvent struct{ *BasicEvent }
type TransitionEvent struct{ *BasicEvent }
type UIEvent struct{ *BasicEvent }
type UserProximityEvent struct{ *BasicEvent }

const (
	DeltaPixel = 0
	DeltaLine  = 1
	DeltaPage  = 2
)

type WheelEvent struct {
	*BasicEvent
	DeltaX    float64 `js:"deltaX"`
	DeltaY    float64 `js:"deltaY"`
	DeltaZ    float64 `js:"deltaZ"`
	DeltaMode int     `js:"deltaMode"`
}

type EventTarget interface {
	// AddEventListener adds a new event listener and returns the
	// wrapper function it generated. If using RemoveEventListener,
	// that wrapper has to be used.
	AddEventListener(typ string, useCapture bool, listener func(Event)) func(*js.Object)
	RemoveEventListener(typ string, useCapture bool, listener func(*js.Object))
	DispatchEvent(event Event) bool
}
<|endoftext|>


<commit_before>package githttp

import (
	"fmt"
	"net/http"
)

// An event (triggered on push/pull)
type Event struct {
	// One of tag/push/fetch
	Type EventType `json:"type"`

	////
	// Set for pushes and pulls
	////

	// SHA of commit
	Commit string `json:"commit"`

	// Path to bare repo
	Dir string

	////
	// Set for pushes or tagging
	////
	Tag    string `json:"tag,omitempty"`
	Last   string `json:"last,omitempty"`
	Branch string `json:"branch,omitempty"`

	// Error contains the error that happened (if any)
	// during this action/event
	Error error

	// Http stuff
	Request *http.Request
}

type EventType int

// Possible event types
const (
	TAG = iota + 1
	PUSH
	FETCH
)

func (e EventType) String() string {
	switch e {
	case TAG:
		return "tag"
	case PUSH:
		return "push"
	case FETCH:
		return "fetch"
	}
	return "unknown"
}

func (e EventType) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%s"`, e)), nil
}

func (e EventType) UnmarshalJSON(data []byte) error {
	str := string(data[:])
	switch str {
	case "tag":
		e = TAG
	case "push":
		e = PUSH
	case "fetch":
		e = FETCH
	default:
		return fmt.Errorf("'%s' is not a known git event type")
	}
	return nil
}
<commit_msg>Leave PUSH_FORCE variable for backwards compatibility<commit_after>package githttp

import (
	"fmt"
	"net/http"
)

// An event (triggered on push/pull)
type Event struct {
	// One of tag/push/fetch
	Type EventType `json:"type"`

	////
	// Set for pushes and pulls
	////

	// SHA of commit
	Commit string `json:"commit"`

	// Path to bare repo
	Dir string

	////
	// Set for pushes or tagging
	////
	Tag    string `json:"tag,omitempty"`
	Last   string `json:"last,omitempty"`
	Branch string `json:"branch,omitempty"`

	// Error contains the error that happened (if any)
	// during this action/event
	Error error

	// Http stuff
	Request *http.Request
}

type EventType int

// Possible event types
const (
	TAG = iota + 1
	PUSH
	FETCH
	PUSH_FORCE
)

func (e EventType) String() string {
	switch e {
	case TAG:
		return "tag"
	case PUSH:
		return "push"
	case PUSH_FORCE:
		return "push-force"
	case FETCH:
		return "fetch"
	}
	return "unknown"
}

func (e EventType) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf(`"%s"`, e)), nil
}

func (e EventType) UnmarshalJSON(data []byte) error {
	str := string(data[:])
	switch str {
	case "tag":
		e = TAG
	case "push":
		e = PUSH
	case "push-force":
		e = PUSH_FORCE
	case "fetch":
		e = FETCH
	default:
		return fmt.Errorf("'%s' is not a known git event type")
	}
	return nil
}
<|endoftext|>


<commit_before>package dockerguard

const (
	DiskSpaceLimitReached   = iota
	MemorySpaceLimitReached = iota
	ContainerStarted        = iota
	ContainerStopped        = iota
	ContainerRemoved        = iota
	DiskIOOverload          = iota
	NetBandwithOverload     = iota
	CPUUsageOverload        = iota
)

type Event struct {
	Type   int
	Target string
	Data   string
}

func (e *Event) TypeToString() string {
	switch e.Type {
	case DiskSpaceLimitReached:
		return "DiskSpaceLimitReached"
	case MemorySpaceLimitReached:
		return "MemorySpaceLimitReached"
	case ContainerStarted:
		return "ContainerStarted"
	case ContainerStopped:
		return "ContainerStopped"
	case ContainerRemoved:
		return "ContainerRemoved"
	case DiskIOOverload:
		return "DiskIOOverload"
	case NetBandwithOverload:
		return "NetBandwithOverload"
	case CPUUsageOverload:
		return "CPUUsageOverload"
	}

	return "UnknownType"
}
<commit_msg>Improve event struct<commit_after>package dockerguard

const (
	EventNotice = iota
	EventWarning
	EventCritical

	EventDiskSpaceLimitReached = iota
	EventMemorySpaceLimitReached
	EventContainerStarted
	EventContainerStopped
	EventContainerRemoved
	EventDiskIOOverload
	EventNetBandwithOverload
	EventCPUUsageOverload
)

type Event struct {
	Severity int
	Type     int
	Target   string
	Probe    string
	Data     string
}

func (e *Event) TypeToString() string {
	switch e.Type {
	case EventDiskSpaceLimitReached:
		return "DiskSpaceLimitReached"
	case EventMemorySpaceLimitReached:
		return "MemorySpaceLimitReached"
	case EventContainerStarted:
		return "ContainerStarted"
	case EventContainerStopped:
		return "ContainerStopped"
	case EventContainerRemoved:
		return "ContainerRemoved"
	case EventDiskIOOverload:
		return "DiskIOOverload"
	case EventNetBandwithOverload:
		return "NetBandwithOverload"
	case EventCPUUsageOverload:
		return "CPUUsageOverload"
	}

	return "UnknownType"
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"regexp"
)

type Command func(*Changelog, []string)

type Release struct {
	Version    string
	Date       string
	Summary    string
	Added      []string
	Changed    []string
	Deprecated []string
	Removed    []string
	Fixed      []string
	Security   []string
}

type Changelog []Release

var REGEXP_FILENAME = regexp.MustCompile(`^(?i)change(-|_)?log(.yml|.yaml)?$`)
var DEFAULT_COMMAND = "release"
var COMMAND_MAPPING = map[string]Command{
	"release": release,
}
var ERROR_READING = 1
var ERROR_PARSING = 2
var ERROR_RELEASE = 3
var REGEXP_DATE = regexp.MustCompile(`^\d\d\d\d-\d\d-\d\d$`)
var REGEXP_VERSION = regexp.MustCompile(`^\d+(\.\d+)?(\.\d+)?$`)

func Error(code int, message string) {
	fmt.Println(message)
	os.Exit(code)
}

func Errorf(code int, message string, args ...interface{}) {
	Error(code, fmt.Sprintf(message, args...))
}

func readChangelog() []byte {
	files, err := ioutil.ReadDir(".")
	if err != nil {
		Error(ERROR_READING, "Could not list current directory")
	}
	for _, file := range files {
		if !file.IsDir() && REGEXP_FILENAME.MatchString(file.Name()) {
			source, err := ioutil.ReadFile(file.Name())
			if err != nil {
				Errorf(ERROR_READING, "Error reading changelog file '%s'\n", file.Name())
			}
			return source
		}
	}
	Error(ERROR_READING, "No changelog file found")
	return []byte{}
}

func parseChangelog(source []byte) *Changelog {
	var changelog Changelog
	err := yaml.Unmarshal(source, &changelog)
	if err != nil {
		Errorf(ERROR_PARSING, "Error parsing changelog: %s\n", err.Error())
	}
	return &changelog
}

////////////////////////////////////////////////////////////////////////////////
//                                  COMMANDS                                  //
////////////////////////////////////////////////////////////////////////////////

func checkRelease(release Release) {
	if release.Version == "" {
		Error(ERROR_RELEASE, "Release version is empty")
	}
	if !REGEXP_VERSION.MatchString(release.Version) {
		Errorf(ERROR_RELEASE, "Release version '%s' is not a valid semantic version number", release.Version)
	}
	if release.Date == "" {
		Error(ERROR_RELEASE, "Release date is empty")
	}
	if !REGEXP_DATE.MatchString(release.Date) {
		Errorf(ERROR_RELEASE, "Release date '%s' is not valid ISO format", release.Date)
	}
	if release.Summary == "" {
		Error(ERROR_RELEASE, "Release summary is empty")
	}
}

func checkChangelog(changelog *Changelog) {
	if len(*changelog) == 0 {
		Error(ERROR_RELEASE, "Release is empy")
	}
	for _, release := range *changelog {
		checkRelease(release)
	}
}

func release(changelog *Changelog, args []string) {
	checkChangelog(changelog)
	if len(args) > 0 {
		if args[0] == "summary" {
			fmt.Println((*changelog)[0].Summary)
		} else if args[0] == "date" {
			fmt.Println((*changelog)[0].Date)
		}
	}
}

func main() {
	changelog := parseChangelog(readChangelog())
	var command string
	var args []string
	if len(os.Args) < 2 {
		command = DEFAULT_COMMAND
		args = []string(nil)
	} else {
		command = os.Args[1]
		args = os.Args[2:]
	}
	function := COMMAND_MAPPING[command]
	if function != nil {
		function(changelog, args)
	} else {
		fmt.Printf("Command %s unknown\n", command)
		os.Exit(3)
	}
}
<commit_msg>Added to html command<commit_after>package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
	"regexp"
	"text/template"
)

type Command func(*Changelog, []string)

type Release struct {
	Version    string
	Date       string
	Summary    string
	Added      []string
	Changed    []string
	Deprecated []string
	Removed    []string
	Fixed      []string
	Security   []string
}

type Changelog []Release

var REGEXP_FILENAME = regexp.MustCompile(`^(?i)change(-|_)?log(.yml|.yaml)?$`)
var DEFAULT_COMMAND = "release"
var COMMAND_MAPPING = map[string]Command{
	"release": release,
	"to":      to,
}
var ERROR_READING = 1
var ERROR_PARSING = 2
var ERROR_RELEASE = 3
var ERROR_TO = 4
var REGEXP_DATE = regexp.MustCompile(`^\d\d\d\d-\d\d-\d\d$`)
var REGEXP_VERSION = regexp.MustCompile(`^\d+(\.\d+)?(\.\d+)?$`)
var HTML_TEMPLATE = `

Change Log

{{ range $release := . }}

Release {{ .Version }} ({{ .Date }})

{{ .Summary }}

{{ if .Added }}

Added

{{ range $entry := .Added }}

{{ . }}

{{ end }}

{{ end }}
{{ if .Changed }}

Changed

{{ range $entry := .Changed }}

{{ . }}

{{ end }}

{{ end }}
{{ if .Deprecated }}

Deprecated

{{ range $entry := .Deprecated }}

{{ . }}

{{ end }}

{{ end }}
{{ if .Removed }}

Removed

{{ range $entry := .Removed }}

{{ . }}

{{ end }}

{{ end }}
{{ if .Fixed }}

Fixed

{{ range $entry := .Fixed }}

{{ . }}

{{ end }}

{{ end }}
{{ if .Security }}

Security

{{ range $entry := .Security }}

{{ . }}

{{ end }}

{{ end }}
{{ end }}

`

func Error(code int, message string) {
	fmt.Println(message)
	os.Exit(code)
}

func Errorf(code int, message string, args ...interface{}) {
	Error(code, fmt.Sprintf(message, args...))
}

func readChangelog() []byte {
	files, err := ioutil.ReadDir(".")
	if err != nil {
		Error(ERROR_READING, "Could not list current directory")
	}
	for _, file := range files {
		if !file.IsDir() && REGEXP_FILENAME.MatchString(file.Name()) {
			source, err := ioutil.ReadFile(file.Name())
			if err != nil {
				Errorf(ERROR_READING, "Error reading changelog file '%s'\n", file.Name())
			}
			return source
		}
	}
	Error(ERROR_READING, "No changelog file found")
	return []byte{}
}

func parseChangelog(source []byte) *Changelog {
	var changelog Changelog
	err := yaml.Unmarshal(source, &changelog)
	if err != nil {
		Errorf(ERROR_PARSING, "Error parsing changelog: %s\n", err.Error())
	}
	return &changelog
}

////////////////////////////////////////////////////////////////////////////////
//                                  COMMANDS                                  //
////////////////////////////////////////////////////////////////////////////////

func checkRelease(release Release) {
	if release.Version == "" {
		Error(ERROR_RELEASE, "Release version is empty")
	}
	if !REGEXP_VERSION.MatchString(release.Version) {
		Errorf(ERROR_RELEASE, "Release version '%s' is not a valid semantic version number", release.Version)
	}
	if release.Date == "" {
		Error(ERROR_RELEASE, "Release date is empty")
	}
	if !REGEXP_DATE.MatchString(release.Date) {
		Errorf(ERROR_RELEASE, "Release date '%s' is not valid ISO format", release.Date)
	}
	if release.Summary == "" {
		Error(ERROR_RELEASE, "Release summary is empty")
	}
}

func checkChangelog(changelog *Changelog) {
	if len(*changelog) == 0 {
		Error(ERROR_RELEASE, "Release is empy")
	}
	for _, release := range *changelog {
		checkRelease(release)
	}
}

func release(changelog *Changelog, args []string) {
	checkChangelog(changelog)
	if len(args) > 0 {
		if args[0] == "summary" {
			fmt.Println((*changelog)[0].Summary)
		} else if args[0] == "date" {
			fmt.Println((*changelog)[0].Date)
		}
	}
}

func toHtml(changelog *Changelog) {
	t := template.Must(template.New("changelog").Parse(HTML_TEMPLATE))
	err := t.Execute(os.Stdout, changelog)
	if err != nil {
		Errorf(ERROR_TO, "Error processing template: %s", err)
	}
}

func to(changelog *Changelog, args []string) {
	checkChangelog(changelog)
	if len(args) != 1 {
		Error(ERROR_TO, "You must pass format to convert to")
	}
	format := args[0]
	if format != "html" {
		Errorf(ERROR_TO, "Unknown format %s", args[0])
	}
	toHtml(changelog)
}

func main() {
	changelog := parseChangelog(readChangelog())
	var command string
	var args []string
	if len(os.Args) < 2 {
		command = DEFAULT_COMMAND
		args = []string(nil)
	} else {
		command = os.Args[1]
		args = os.Args[2:]
	}
	function := COMMAND_MAPPING[command]
	if function != nil {
		function(changelog, args)
	} else {
		fmt.Printf("Command %s unknown\n", command)
		os.Exit(3)
	}
}
<|endoftext|>


<commit_before>package common

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"

	log "github.com/Sirupsen/logrus"
	"github.com/ayufan/gitlab-ci-multi-runner/helpers"
)

type UpdateState int

const (
	UpdateSucceeded UpdateState = iota
	UpdateAbort
	UpdateFailed
)

type GetBuildRequest struct {
	Token string `json:"token,omitempty"`
}

type GetBuildResponse struct {
	Id            int    `json:"id,omitempty"`
	ProjectId     int    `json:"project_id,omitempty"`
	Commands      string `json:"commands,omitempty"`
	RepoURL       string `json:"repo_url,omitempty"`
	Sha           string `json:"sha,omitempty"`
	RefName       string `json:"ref,omitempty"`
	BeforeSha     string `json:"before_sha,omitempty"`
	AllowGitFetch bool   `json:"allow_git_fetch,omitempty"`
	Timeout       int    `json:"timeout,omitempty"`
}

type RegisterRunnerRequest struct {
	Token       string `json:"token,omitempty"`
	Description string `json:"description,omitempty"`
	Tags        string `json:"tag_list,omitempty"`
}

type RegisterRunnerResponse struct {
	Token string `json:"token,omitempty"`
}

type UpdateBuildRequest struct {
	Token string     `json:"token,omitempty"`
	State BuildState `json:"state,omitempty"`
	Trace string     `json:"trace,omitempty"`
}

func sendJsonRequest(url string, method string, statusCode int, request interface{}, response interface{}) int {
	var body []byte
	var err error

	if request != nil {
		body, err = json.Marshal(request)
		if err != nil {
			log.Errorf("Failed to marshal project object: %v", err)
			return -1
		}
	}

	req, err := http.NewRequest(method, url, bytes.NewReader(body))
	if err != nil {
		log.Errorf("Failed to create NewRequest", err)
		return -1
	}

	if request != nil {
		req.Header.Set("Content-Type", "application/json")
	}

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Errorf("Couldn't execute %v against %s: %v", req.Method, req.URL, err)
		return -1
	}
	defer res.Body.Close()

	if res.StatusCode == statusCode {
		if response != nil {
			d := json.NewDecoder(res.Body)
			err = d.Decode(response)
			if err != nil {
				log.Errorf("Error decoding json payload %v", err)
				return -1
			}
		}
	}

	return res.StatusCode
}

func getJson(url string, statusCode int, response interface{}) int {
	return sendJsonRequest(url, "GET", statusCode, nil, response)
}

func postJson(url string, statusCode int, request interface{}, response interface{}) int {
	return sendJsonRequest(url, "POST", statusCode, request, response)
}

func putJson(url string, statusCode int, request interface{}, response interface{}) int {
	return sendJsonRequest(url, "PUT", statusCode, request, response)
}

func readPayload(r io.Reader) ([]byte, error) {
	maxPayloadSize := int64(1<<63 - 1)
	maxPayloadSize = int64(10 << 20) // 10 MB is a lot of text.
	b, err := ioutil.ReadAll(io.LimitReader(r, maxPayloadSize+1))
	if err != nil {
		return nil, err
	}
	if int64(len(b)) > maxPayloadSize {
		err = errors.New("http: POST too large")
		return nil, err
	}
	return b, nil
}

func getUrl(baseURL string, request string, a ...interface{}) string {
	return fmt.Sprintf("%s/api/v1/%s", baseURL, fmt.Sprintf(request, a...))
}

func GetBuild(config RunnerConfig) (*GetBuildResponse, bool) {
	request := GetBuildRequest{
		Token: config.Token,
	}

	var response GetBuildResponse
	result := postJson(getUrl(config.URL, "builds/register.json"), 201, &request, &response)

	switch result {
	case 201:
		log.Println(config.ShortDescription(), "Checking for builds...", "received")
		return &response, true
	case 403:
		log.Errorln(config.ShortDescription(), "Checking for builds...", "forbidden")
		return nil, false
	case 404:
		log.Infoln(config.ShortDescription(), "Checking for builds...", "nothing")
		return nil, true
	default:
		log.Warningln(config.ShortDescription(), "Checking for builds...", "failed")
		return nil, true
	}
}

func RegisterRunner(url, token, description, tags string) *RegisterRunnerResponse {
	request := RegisterRunnerRequest{
		Token:       token,
		Description: description,
		Tags:        tags,
	}

	var response RegisterRunnerResponse
	result := postJson(getUrl(url, "runners/register.json"), 201, &request, &response)
	shortToken := helpers.ShortenToken(token)

	switch result {
	case 201:
		log.Println(shortToken, "Registering runner...", "succeeded")
		return &response
	case 403:
		log.Errorln(shortToken, "Registering runner...", "forbidden")
		return nil
	default:
		log.Errorln(shortToken, "Registering runner...", "failed")
		return nil
	}
}

func UpdateBuild(config RunnerConfig, id int, state BuildState, trace io.Reader) UpdateState {
	data, err := readPayload(trace)
	if err != nil {
		return UpdateFailed
	}

	request := UpdateBuildRequest{
		Token: config.Token,
		State: state,
		Trace: string(data),
	}

	result := putJson(getUrl(config.URL, "builds/%d.json", id), 200, &request, nil)
	switch result {
	case 200:
		log.Println(config.ShortDescription(), id, "Submitting build to coordinator...", "ok")
		return UpdateSucceeded
	case 404:
		log.Warningln(config.ShortDescription(), id, "Submitting build to coordinator...", "aborted")
		return UpdateAbort
	case 403:
		log.Errorln(config.ShortDescription(), id, "Submitting build to coordinator...", "forbidden")
		return UpdateAbort
	default:
		log.Warningln(config.ShortDescription(), id, "Submitting build to coordinator...", "failed")
		return UpdateFailed
	}
}
<commit_msg>Added API to delete runner<commit_after>package common

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"

	log "github.com/Sirupsen/logrus"
	"github.com/ayufan/gitlab-ci-multi-runner/helpers"
)

type UpdateState int

const (
	UpdateSucceeded UpdateState = iota
	UpdateAbort
	UpdateFailed
)

type GetBuildRequest struct {
	Token string `json:"token,omitempty"`
}

type GetBuildResponse struct {
	Id            int    `json:"id,omitempty"`
	ProjectId     int    `json:"project_id,omitempty"`
	Commands      string `json:"commands,omitempty"`
	RepoURL       string `json:"repo_url,omitempty"`
	Sha           string `json:"sha,omitempty"`
	RefName       string `json:"ref,omitempty"`
	BeforeSha     string `json:"before_sha,omitempty"`
	AllowGitFetch bool   `json:"allow_git_fetch,omitempty"`
	Timeout       int    `json:"timeout,omitempty"`
}

type RegisterRunnerRequest struct {
	Token       string `json:"token,omitempty"`
	Description string `json:"description,omitempty"`
	Tags        string `json:"tag_list,omitempty"`
}

type RegisterRunnerResponse struct {
	Token string `json:"token,omitempty"`
}

type UpdateBuildRequest struct {
	Token string     `json:"token,omitempty"`
	State BuildState `json:"state,omitempty"`
	Trace string     `json:"trace,omitempty"`
}

func sendJsonRequest(url string, method string, statusCode int, request interface{}, response interface{}) int {
	var body []byte
	var err error

	if request != nil {
		body, err = json.Marshal(request)
		if err != nil {
			log.Errorf("Failed to marshal project object: %v", err)
			return -1
		}
	}

	req, err := http.NewRequest(method, url, bytes.NewReader(body))
	if err != nil {
		log.Errorf("Failed to create NewRequest", err)
		return -1
	}

	if request != nil {
		req.Header.Set("Content-Type", "application/json")
	}

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Errorf("Couldn't execute %v against %s: %v", req.Method, req.URL, err)
		return -1
	}
	defer res.Body.Close()

	if res.StatusCode == statusCode {
		if response != nil {
			d := json.NewDecoder(res.Body)
			err = d.Decode(response)
			if err != nil {
				log.Errorf("Error decoding json payload %v", err)
				return -1
			}
		}
	}

	return res.StatusCode
}

func getJson(url string, statusCode int, response interface{}) int {
	return sendJsonRequest(url, "GET", statusCode, nil, response)
}

func postJson(url string, statusCode int, request interface{}, response interface{}) int {
	return sendJsonRequest(url, "POST", statusCode, request, response)
}

func putJson(url string, statusCode int, request interface{}, response interface{}) int {
	return sendJsonRequest(url, "PUT", statusCode, request, response)
}

func deleteJson(url string, statusCode int, response interface{}) int {
	return sendJsonRequest(url, "DELETE", statusCode, nil, response)
}

func readPayload(r io.Reader) ([]byte, error) {
	maxPayloadSize := int64(1<<63 - 1)
	maxPayloadSize = int64(10 << 20) // 10 MB is a lot of text.
	b, err := ioutil.ReadAll(io.LimitReader(r, maxPayloadSize+1))
	if err != nil {
		return nil, err
	}
	if int64(len(b)) > maxPayloadSize {
		err = errors.New("http: POST too large")
		return nil, err
	}
	return b, nil
}

func getUrl(baseURL string, request string, a ...interface{}) string {
	return fmt.Sprintf("%s/api/v1/%s", baseURL, fmt.Sprintf(request, a...))
}

func GetBuild(config RunnerConfig) (*GetBuildResponse, bool) {
	request := GetBuildRequest{
		Token: config.Token,
	}

	var response GetBuildResponse
	result := postJson(getUrl(config.URL, "builds/register.json"), 201, &request, &response)

	switch result {
	case 201:
		log.Println(config.ShortDescription(), "Checking for builds...", "received")
		return &response, true
	case 403:
		log.Errorln(config.ShortDescription(), "Checking for builds...", "forbidden")
		return nil, false
	case 404:
		log.Infoln(config.ShortDescription(), "Checking for builds...", "nothing")
		return nil, true
	default:
		log.Warningln(config.ShortDescription(), "Checking for builds...", "failed")
		return nil, true
	}
}

func RegisterRunner(url, token, description, tags string) *RegisterRunnerResponse {
	request := RegisterRunnerRequest{
		Token:       token,
		Description: description,
		Tags:        tags,
	}

	var response RegisterRunnerResponse
	result := postJson(getUrl(url, "runners/register.json"), 201, &request, &response)
	shortToken := helpers.ShortenToken(token)

	switch result {
	case 201:
		log.Println(shortToken, "Registering runner...", "succeeded")
		return &response
	case 403:
		log.Errorln(shortToken, "Registering runner...", "forbidden")
		return nil
	default:
		log.Errorln(shortToken, "Registering runner...", "failed")
		return nil
	}
}

func DeleteRunner(url, token string) bool {
	result := deleteJson(getUrl(url, "runners/delete?token=%v", token), 200, nil)
	shortToken := helpers.ShortenToken(token)

	switch result {
	case 201:
		log.Println(shortToken, "Deleting runner...", "succeeded")
		return true
	case 403:
		log.Errorln(shortToken, "Deleting runner...", "forbidden")
		return false
	default:
		log.Errorln(shortToken, "Deleting runner...", "failed", result)
		return false
	}
}

func UpdateBuild(config RunnerConfig, id int, state BuildState, trace io.Reader) UpdateState {
	data, err := readPayload(trace)
	if err != nil {
		return UpdateFailed
	}

	request := UpdateBuildRequest{
		Token: config.Token,
		State: state,
		Trace: string(data),
	}

	result := putJson(getUrl(config.URL, "builds/%d.json", id), 200, &request, nil)
	switch result {
	case 200:
		log.Println(config.ShortDescription(), id, "Submitting build to coordinator...", "ok")
		return UpdateSucceeded
	case 404:
		log.Warningln(config.ShortDescription(), id, "Submitting build to coordinator...", "aborted")
		return UpdateAbort
	case 403:
		log.Errorln(config.ShortDescription(), id, "Submitting build to coordinator...", "forbidden")
		return UpdateAbort
	default:
		log.Warningln(config.ShortDescription(), id, "Submitting build to coordinator...", "failed")
		return UpdateFailed
	}
}
<|endoftext|>