<commit_before>/*
Copyright 2015 Gravitational, Inc.

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 trace

import (
	"crypto/x509"
	"fmt"
	"net"
	"net/url"
	"os"
)

// NotFound returns new instance of not found error
func NotFound(message string, args ...interface{}) error {
	return wrap(&NotFoundError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// NotFoundError indicates that object has not been found
type NotFoundError struct {
	Message string `json:"message"`
}

// IsNotFoundError returns true to indicate that is NotFoundError
func (e *NotFoundError) IsNotFoundError() bool {
	return true
}

// Error returns log friendly description of an error
func (e *NotFoundError) Error() string {
	if e.Message != "" {
		return e.Message
	}
	return "object not found"
}

// OrigError returns original error (in this case this is the error itself)
func (e *NotFoundError) OrigError() error {
	return e
}

// IsNotFound returns whether this error is of NotFoundError type
func IsNotFound(e error) bool {
	type nf interface {
		IsNotFoundError() bool
	}
	_, ok := Unwrap(e).(nf)
	return ok
}

// AlreadyExists returns a new instance of AlreadyExists error
func AlreadyExists(message string, args ...interface{}) error {
	return wrap(&AlreadyExistsError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// AlreadyExistsError indicates that there's a duplicate object that already
// exists in the storage/system
type AlreadyExistsError struct {
	// Message is user-friendly error message
	Message string `json:"message"`
}

// Error returns log friendly description of an error
func (n *AlreadyExistsError) Error() string {
	if n.Message != "" {
		return n.Message
	}
	return "object already exists"
}

// IsAlreadyExistsError indicates that this error of the AlreadyExistsError type
func (AlreadyExistsError) IsAlreadyExistsError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (e *AlreadyExistsError) OrigError() error {
	return e
}

// IsAlreadyExists returns whether this is error indicating that object
// already exists
func IsAlreadyExists(e error) bool {
	type ae interface {
		IsAlreadyExistsError() bool
	}
	_, ok := Unwrap(e).(ae)
	return ok
}

// BadParameter returns a new instance of BadParameterError
func BadParameter(message string, args ...interface{}) error {
	return wrap(&BadParameterError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// BadParameterError indicates that something is wrong with passed
// parameter to API method
type BadParameterError struct {
	Message string `json:"message"`
}

// Error returns log friendly description of an error
func (b *BadParameterError) Error() string {
	return b.Message
}

// OrigError returns original error (in this case this is the error itself)
func (b *BadParameterError) OrigError() error {
	return b
}

// IsBadParameterError indicates that this error is of BadParameterError type
func (b *BadParameterError) IsBadParameterError() bool {
	return true
}

// IsBadParameter returns whether this error is of BadParameterType
func IsBadParameter(e error) bool {
	type bp interface {
		IsBadParameterError() bool
	}
	_, ok := Unwrap(e).(bp)
	return ok
}

// CompareFailed returns new instance of CompareFailedError
func CompareFailed(message string, args ...interface{}) error {
	return wrap(&CompareFailedError{Message: fmt.Sprintf(message, args...)}, 2)
}

// CompareFailedError indicates a failed comparison (e.g. bad password or hash)
type CompareFailedError struct {
	// Message is user-friendly error message
	Message string `json:"message"`
}

// Error is debug - friendly message
func (e *CompareFailedError) Error() string {
	if e.Message != "" {
		return e.Message
	}
	return "compare failed"
}

// OrigError returns original error (in this case this is the error itself)
func (e *CompareFailedError) OrigError() error {
	return e
}

// IsCompareFailedError indicates that this is CompareFailedError
func (e *CompareFailedError) IsCompareFailedError() bool {
	return true
}

// IsCompareFailed detects if this error is of CompareFailed type
func IsCompareFailed(e error) bool {
	type cf interface {
		IsCompareFailedError() bool
	}
	_, ok := Unwrap(e).(cf)
	return ok
}

// AccessDenied returns new instance of AccessDeniedError
func AccessDenied(message string, args ...interface{}) error {
	return wrap(&AccessDeniedError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// AccessDeniedError indicates denied access
type AccessDeniedError struct {
	Message string `json:"message"`
}

// Error is debug - friendly error message
func (e *AccessDeniedError) Error() string {
	if e.Message != "" {
		return e.Message
	}
	return "access denied"
}

// IsAccessDeniedError indicates that this error is of AccessDeniedError type
func (e *AccessDeniedError) IsAccessDeniedError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (e *AccessDeniedError) OrigError() error {
	return e
}

// IsAccessDenied detects if this error is of AccessDeniedError type
func IsAccessDenied(e error) bool {
	type ad interface {
		IsAccessDeniedError() bool
	}
	_, ok := Unwrap(e).(ad)
	return ok
}

// ConvertSystemError converts system error to appropriate trace error
// if it is possible, otherwise, returns original error
func ConvertSystemError(err error) error {
	innerError := Unwrap(err)

	if os.IsNotExist(innerError) {
		return wrap(&NotFoundError{Message: innerError.Error()}, 2)
	}
	if os.IsPermission(innerError) {
		return wrap(&AccessDeniedError{Message: innerError.Error()}, 2)
	}
	switch realErr := innerError.(type) {
	case *net.OpError:
		return wrap(&ConnectionProblemError{
			Message: fmt.Sprintf("failed to connect to server %v", realErr.Addr),
			Err:     realErr}, 2)
	case *os.PathError:
		return wrap(&AccessDeniedError{
			Message: fmt.Sprintf("failed to execute command %v error:  %v", realErr.Path, realErr.Err),
		}, 2)
	case x509.SystemRootsError, x509.UnknownAuthorityError:
		return wrap(&TrustError{Err: innerError}, 2)
	default:
		return err
	}
}

// ConnectionProblem returns new instance of ConnectionProblemError
func ConnectionProblem(err error, message string, args ...interface{}) error {
	return wrap(&ConnectionProblemError{
		Message: fmt.Sprintf(message, args...),
		Err:     err,
	}, 2)
}

// ConnectionProblemError indicates a network related problem
type ConnectionProblemError struct {
	Message string `json:"message"`
	Err     error  `json:"-"`
}

// Error is debug - friendly error message
func (c *ConnectionProblemError) Error() string {
	return fmt.Sprintf("%v: %v", c.Message, c.Err)
}

// IsConnectionProblemError indicates that this error is of ConnectionProblemError type
func (c *ConnectionProblemError) IsConnectionProblemError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (c *ConnectionProblemError) OrigError() error {
	return c
}

// IsConnectionProblem returns whether this error is of ConnectionProblemError
func IsConnectionProblem(e error) bool {
	type ad interface {
		IsConnectionProblemError() bool
	}
	_, ok := Unwrap(e).(ad)
	return ok
}

// LimitExceeded returns whether new instance of LimitExceededError
func LimitExceeded(message string, args ...interface{}) error {
	return wrap(&LimitExceededError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// LimitExceededError indicates rate limit or connection limit problem
type LimitExceededError struct {
	Message string `json:"message"`
}

// Error is debug - friendly error message
func (c *LimitExceededError) Error() string {
	return c.Message
}

// IsLimitExceededError indicates that this error is of ConnectionProblem
func (c *LimitExceededError) IsLimitExceededError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (c *LimitExceededError) OrigError() error {
	return c
}

// IsLimitExceeded detects if this error is of LimitExceededError
func IsLimitExceeded(e error) bool {
	type ad interface {
		IsLimitExceededError() bool
	}
	_, ok := Unwrap(e).(ad)
	return ok
}

// TrustError indicates trust-related validation error (e.g. untrusted cert)
type TrustError struct {
	// Err is original error
	Err     error `json:"error"`
	Message string
}

// Error returns log-friendly error description
func (t *TrustError) Error() string {
	return t.Err.Error()
}

// IsTrustError indicates that this error is of TrustError type
func (*TrustError) IsTrustError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (t *TrustError) OrigError() error {
	return t
}

// IsTrustError returns if this is a trust error
func IsTrustError(e error) bool {
	type te interface {
		IsTrustError() bool
	}
	_, ok := Unwrap(e).(te)
	return ok
}

// OAuth2 returns new instance of OAuth2Error
func OAuth2(code, message string, query url.Values) Error {
	return wrap(&OAuth2Error{
		Code:    code,
		Message: message,
		Query:   query,
	}, 2)
}

// OAuth2Error defined an error used in OpenID Connect Flow (OIDC)
type OAuth2Error struct {
	Code    string     `json:"code"`
	Message string     `json:"message"`
	Query   url.Values `json:"query"`
}

//Error returns log friendly description of an error
func (o *OAuth2Error) Error() string {
	return fmt.Sprintf("OAuth2 error code=%v, message=%v", o.Code, o.Message)
}

// IsOAuth2Error returns whether this error of OAuth2Error type
func (o *OAuth2Error) IsOAuth2Error() bool {
	return true
}

// IsOAuth2 returns if this is a OAuth2-related error
func IsOAuth2(e error) bool {
	type oe interface {
		IsOAuth2Error() bool
	}
	_, ok := Unwrap(e).(oe)
	return ok
}
<commit_msg>trace.IsNotFound() now supports os errors<commit_after>/*
Copyright 2015 Gravitational, Inc.

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 trace

import (
	"crypto/x509"
	"fmt"
	"net"
	"net/url"
	"os"
)

// NotFound returns new instance of not found error
func NotFound(message string, args ...interface{}) error {
	return wrap(&NotFoundError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// NotFoundError indicates that object has not been found
type NotFoundError struct {
	Message string `json:"message"`
}

// IsNotFoundError returns true to indicate that is NotFoundError
func (e *NotFoundError) IsNotFoundError() bool {
	return true
}

// Error returns log friendly description of an error
func (e *NotFoundError) Error() string {
	if e.Message != "" {
		return e.Message
	}
	return "object not found"
}

// OrigError returns original error (in this case this is the error itself)
func (e *NotFoundError) OrigError() error {
	return e
}

// IsNotFound returns whether this error is of NotFoundError type
func IsNotFound(e error) bool {
	type nf interface {
		IsNotFoundError() bool
	}
	err := Unwrap(e)
	_, ok := err.(nf)
	if !ok {
		return os.IsNotExist(err)
	}
	return ok
}

// AlreadyExists returns a new instance of AlreadyExists error
func AlreadyExists(message string, args ...interface{}) error {
	return wrap(&AlreadyExistsError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// AlreadyExistsError indicates that there's a duplicate object that already
// exists in the storage/system
type AlreadyExistsError struct {
	// Message is user-friendly error message
	Message string `json:"message"`
}

// Error returns log friendly description of an error
func (n *AlreadyExistsError) Error() string {
	if n.Message != "" {
		return n.Message
	}
	return "object already exists"
}

// IsAlreadyExistsError indicates that this error of the AlreadyExistsError type
func (AlreadyExistsError) IsAlreadyExistsError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (e *AlreadyExistsError) OrigError() error {
	return e
}

// IsAlreadyExists returns whether this is error indicating that object
// already exists
func IsAlreadyExists(e error) bool {
	type ae interface {
		IsAlreadyExistsError() bool
	}
	_, ok := Unwrap(e).(ae)
	return ok
}

// BadParameter returns a new instance of BadParameterError
func BadParameter(message string, args ...interface{}) error {
	return wrap(&BadParameterError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// BadParameterError indicates that something is wrong with passed
// parameter to API method
type BadParameterError struct {
	Message string `json:"message"`
}

// Error returns log friendly description of an error
func (b *BadParameterError) Error() string {
	return b.Message
}

// OrigError returns original error (in this case this is the error itself)
func (b *BadParameterError) OrigError() error {
	return b
}

// IsBadParameterError indicates that this error is of BadParameterError type
func (b *BadParameterError) IsBadParameterError() bool {
	return true
}

// IsBadParameter returns whether this error is of BadParameterType
func IsBadParameter(e error) bool {
	type bp interface {
		IsBadParameterError() bool
	}
	_, ok := Unwrap(e).(bp)
	return ok
}

// CompareFailed returns new instance of CompareFailedError
func CompareFailed(message string, args ...interface{}) error {
	return wrap(&CompareFailedError{Message: fmt.Sprintf(message, args...)}, 2)
}

// CompareFailedError indicates a failed comparison (e.g. bad password or hash)
type CompareFailedError struct {
	// Message is user-friendly error message
	Message string `json:"message"`
}

// Error is debug - friendly message
func (e *CompareFailedError) Error() string {
	if e.Message != "" {
		return e.Message
	}
	return "compare failed"
}

// OrigError returns original error (in this case this is the error itself)
func (e *CompareFailedError) OrigError() error {
	return e
}

// IsCompareFailedError indicates that this is CompareFailedError
func (e *CompareFailedError) IsCompareFailedError() bool {
	return true
}

// IsCompareFailed detects if this error is of CompareFailed type
func IsCompareFailed(e error) bool {
	type cf interface {
		IsCompareFailedError() bool
	}
	_, ok := Unwrap(e).(cf)
	return ok
}

// AccessDenied returns new instance of AccessDeniedError
func AccessDenied(message string, args ...interface{}) error {
	return wrap(&AccessDeniedError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// AccessDeniedError indicates denied access
type AccessDeniedError struct {
	Message string `json:"message"`
}

// Error is debug - friendly error message
func (e *AccessDeniedError) Error() string {
	if e.Message != "" {
		return e.Message
	}
	return "access denied"
}

// IsAccessDeniedError indicates that this error is of AccessDeniedError type
func (e *AccessDeniedError) IsAccessDeniedError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (e *AccessDeniedError) OrigError() error {
	return e
}

// IsAccessDenied detects if this error is of AccessDeniedError type
func IsAccessDenied(e error) bool {
	type ad interface {
		IsAccessDeniedError() bool
	}
	_, ok := Unwrap(e).(ad)
	return ok
}

// ConvertSystemError converts system error to appropriate trace error
// if it is possible, otherwise, returns original error
func ConvertSystemError(err error) error {
	innerError := Unwrap(err)

	if os.IsNotExist(innerError) {
		return wrap(&NotFoundError{Message: innerError.Error()}, 2)
	}
	if os.IsPermission(innerError) {
		return wrap(&AccessDeniedError{Message: innerError.Error()}, 2)
	}
	switch realErr := innerError.(type) {
	case *net.OpError:
		return wrap(&ConnectionProblemError{
			Message: fmt.Sprintf("failed to connect to server %v", realErr.Addr),
			Err:     realErr}, 2)
	case *os.PathError:
		return wrap(&AccessDeniedError{
			Message: fmt.Sprintf("failed to execute command %v error:  %v", realErr.Path, realErr.Err),
		}, 2)
	case x509.SystemRootsError, x509.UnknownAuthorityError:
		return wrap(&TrustError{Err: innerError}, 2)
	default:
		return err
	}
}

// ConnectionProblem returns new instance of ConnectionProblemError
func ConnectionProblem(err error, message string, args ...interface{}) error {
	return wrap(&ConnectionProblemError{
		Message: fmt.Sprintf(message, args...),
		Err:     err,
	}, 2)
}

// ConnectionProblemError indicates a network related problem
type ConnectionProblemError struct {
	Message string `json:"message"`
	Err     error  `json:"-"`
}

// Error is debug - friendly error message
func (c *ConnectionProblemError) Error() string {
	return fmt.Sprintf("%v: %v", c.Message, c.Err)
}

// IsConnectionProblemError indicates that this error is of ConnectionProblemError type
func (c *ConnectionProblemError) IsConnectionProblemError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (c *ConnectionProblemError) OrigError() error {
	return c
}

// IsConnectionProblem returns whether this error is of ConnectionProblemError
func IsConnectionProblem(e error) bool {
	type ad interface {
		IsConnectionProblemError() bool
	}
	_, ok := Unwrap(e).(ad)
	return ok
}

// LimitExceeded returns whether new instance of LimitExceededError
func LimitExceeded(message string, args ...interface{}) error {
	return wrap(&LimitExceededError{
		Message: fmt.Sprintf(message, args...),
	}, 2)
}

// LimitExceededError indicates rate limit or connection limit problem
type LimitExceededError struct {
	Message string `json:"message"`
}

// Error is debug - friendly error message
func (c *LimitExceededError) Error() string {
	return c.Message
}

// IsLimitExceededError indicates that this error is of ConnectionProblem
func (c *LimitExceededError) IsLimitExceededError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (c *LimitExceededError) OrigError() error {
	return c
}

// IsLimitExceeded detects if this error is of LimitExceededError
func IsLimitExceeded(e error) bool {
	type ad interface {
		IsLimitExceededError() bool
	}
	_, ok := Unwrap(e).(ad)
	return ok
}

// TrustError indicates trust-related validation error (e.g. untrusted cert)
type TrustError struct {
	// Err is original error
	Err     error `json:"error"`
	Message string
}

// Error returns log-friendly error description
func (t *TrustError) Error() string {
	return t.Err.Error()
}

// IsTrustError indicates that this error is of TrustError type
func (*TrustError) IsTrustError() bool {
	return true
}

// OrigError returns original error (in this case this is the error itself)
func (t *TrustError) OrigError() error {
	return t
}

// IsTrustError returns if this is a trust error
func IsTrustError(e error) bool {
	type te interface {
		IsTrustError() bool
	}
	_, ok := Unwrap(e).(te)
	return ok
}

// OAuth2 returns new instance of OAuth2Error
func OAuth2(code, message string, query url.Values) Error {
	return wrap(&OAuth2Error{
		Code:    code,
		Message: message,
		Query:   query,
	}, 2)
}

// OAuth2Error defined an error used in OpenID Connect Flow (OIDC)
type OAuth2Error struct {
	Code    string     `json:"code"`
	Message string     `json:"message"`
	Query   url.Values `json:"query"`
}

//Error returns log friendly description of an error
func (o *OAuth2Error) Error() string {
	return fmt.Sprintf("OAuth2 error code=%v, message=%v", o.Code, o.Message)
}

// IsOAuth2Error returns whether this error of OAuth2Error type
func (o *OAuth2Error) IsOAuth2Error() bool {
	return true
}

// IsOAuth2 returns if this is a OAuth2-related error
func IsOAuth2(e error) bool {
	type oe interface {
		IsOAuth2Error() bool
	}
	_, ok := Unwrap(e).(oe)
	return ok
}
<|endoftext|>


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

package gin

import (
	"bytes"
	"encoding/json"
	"fmt"
	"reflect"
)

type ErrorType uint64

const (
	ErrorTypeBind    ErrorType = 1 << 63 // used when c.Bind() fails
	ErrorTypeRender  ErrorType = 1 << 62 // used when c.Render() fails
	ErrorTypePrivate ErrorType = 1 << 0
	ErrorTypePublic  ErrorType = 1 << 1

	ErrorTypeAny ErrorType = 1<<64 - 1
	ErrorTypeNu            = 2
)

type (
	Error struct {
		Err  error
		Type ErrorType
		Meta interface{}
	}

	errorMsgs []*Error
)

var _ error = &Error{}

func (msg *Error) SetType(flags ErrorType) *Error {
	msg.Type = flags
	return msg
}

func (msg *Error) SetMeta(data interface{}) *Error {
	msg.Meta = data
	return msg
}

func (msg *Error) JSON() interface{} {
	json := H{}
	if msg.Meta != nil {
		value := reflect.ValueOf(msg.Meta)
		switch value.Kind() {
		case reflect.Struct:
			return msg.Meta
		case reflect.Map:
			for _, key := range value.MapKeys() {
				json[key.String()] = value.MapIndex(key).Interface()
			}
		default:
			json["meta"] = msg.Meta
		}
	}
	if _, ok := json["error"]; !ok {
		json["error"] = msg.Error()
	}
	return json
}

// Implements the json.Marshaller interface
func (msg *Error) MarshalJSON() ([]byte, error) {
	return json.Marshal(msg.JSON())
}

// Implements the error interface
func (msg *Error) Error() string {
	return msg.Err.Error()
}

func (msg *Error) IsType(flags ErrorType) bool {
	return (msg.Type & flags) > 0
}

// Returns a readonly copy filterd the byte.
// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic
func (a errorMsgs) ByType(typ ErrorType) errorMsgs {
	if len(a) == 0 {
		return nil
	}
	var result errorMsgs = nil
	for _, msg := range a {
		if msg.Type&typ > 0 {
			result = append(result, msg)
		}
	}
	return result
}

// Returns the last error in the slice. It returns nil if the array is empty.
// Shortcut for errors[len(errors)-1]
func (a errorMsgs) Last() *Error {
	length := len(a)
	if length == 0 {
		return nil
	}
	return a[length-1]
}

// Returns an array will all the error messages.
// Example
// ```
// c.Error(errors.New("first"))
// c.Error(errors.New("second"))
// c.Error(errors.New("third"))
// c.Errors.Errors() // == []string{"first", "second", "third"}
// ``
func (a errorMsgs) Errors() []string {
	if len(a) == 0 {
		return nil
	}
	errorStrings := make([]string, len(a))
	for i, err := range a {
		errorStrings[i] = err.Error()
	}
	return errorStrings
}

func (a errorMsgs) JSON() interface{} {
	switch len(a) {
	case 0:
		return nil
	case 1:
		return a.Last().JSON()
	default:
		json := make([]interface{}, len(a))
		for i, err := range a {
			json[i] = err.JSON()
		}
		return json
	}
}

func (a errorMsgs) MarshalJSON() ([]byte, error) {
	return json.Marshal(a.JSON())
}

func (a errorMsgs) String() string {
	if len(a) == 0 {
		return ""
	}
	var buffer bytes.Buffer
	for i, msg := range a {
		fmt.Fprintf(&buffer, "Error #%02d: %s\n", (i + 1), msg.Err)
		if msg.Meta != nil {
			fmt.Fprintf(&buffer, "     Meta: %v\n", msg.Meta)
		}
	}
	return buffer.String()
}
<commit_msg>Improves errors.ByType() implementation<commit_after>// Copyright 2014 Manu Martinez-Almeida.  All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package gin

import (
	"bytes"
	"encoding/json"
	"fmt"
	"reflect"
)

type ErrorType uint64

const (
	ErrorTypeBind    ErrorType = 1 << 63 // used when c.Bind() fails
	ErrorTypeRender  ErrorType = 1 << 62 // used when c.Render() fails
	ErrorTypePrivate ErrorType = 1 << 0
	ErrorTypePublic  ErrorType = 1 << 1

	ErrorTypeAny ErrorType = 1<<64 - 1
	ErrorTypeNu            = 2
)

type (
	Error struct {
		Err  error
		Type ErrorType
		Meta interface{}
	}

	errorMsgs []*Error
)

var _ error = &Error{}

func (msg *Error) SetType(flags ErrorType) *Error {
	msg.Type = flags
	return msg
}

func (msg *Error) SetMeta(data interface{}) *Error {
	msg.Meta = data
	return msg
}

func (msg *Error) JSON() interface{} {
	json := H{}
	if msg.Meta != nil {
		value := reflect.ValueOf(msg.Meta)
		switch value.Kind() {
		case reflect.Struct:
			return msg.Meta
		case reflect.Map:
			for _, key := range value.MapKeys() {
				json[key.String()] = value.MapIndex(key).Interface()
			}
		default:
			json["meta"] = msg.Meta
		}
	}
	if _, ok := json["error"]; !ok {
		json["error"] = msg.Error()
	}
	return json
}

// Implements the json.Marshaller interface
func (msg *Error) MarshalJSON() ([]byte, error) {
	return json.Marshal(msg.JSON())
}

// Implements the error interface
func (msg *Error) Error() string {
	return msg.Err.Error()
}

func (msg *Error) IsType(flags ErrorType) bool {
	return (msg.Type & flags) > 0
}

// Returns a readonly copy filterd the byte.
// ie ByType(gin.ErrorTypePublic) returns a slice of errors with type=ErrorTypePublic
func (a errorMsgs) ByType(typ ErrorType) errorMsgs {
	if len(a) == 0 {
		return nil
	}
	if typ == ErrorTypeAny {
		return a
	}
	var result errorMsgs = nil
	for _, msg := range a {
		if msg.IsType(typ) {
			result = append(result, msg)
		}
	}
	return result
}

// Returns the last error in the slice. It returns nil if the array is empty.
// Shortcut for errors[len(errors)-1]
func (a errorMsgs) Last() *Error {
	length := len(a)
	if length == 0 {
		return nil
	}
	return a[length-1]
}

// Returns an array will all the error messages.
// Example
// ```
// c.Error(errors.New("first"))
// c.Error(errors.New("second"))
// c.Error(errors.New("third"))
// c.Errors.Errors() // == []string{"first", "second", "third"}
// ``
func (a errorMsgs) Errors() []string {
	if len(a) == 0 {
		return nil
	}
	errorStrings := make([]string, len(a))
	for i, err := range a {
		errorStrings[i] = err.Error()
	}
	return errorStrings
}

func (a errorMsgs) JSON() interface{} {
	switch len(a) {
	case 0:
		return nil
	case 1:
		return a.Last().JSON()
	default:
		json := make([]interface{}, len(a))
		for i, err := range a {
			json[i] = err.JSON()
		}
		return json
	}
}

func (a errorMsgs) MarshalJSON() ([]byte, error) {
	return json.Marshal(a.JSON())
}

func (a errorMsgs) String() string {
	if len(a) == 0 {
		return ""
	}
	var buffer bytes.Buffer
	for i, msg := range a {
		fmt.Fprintf(&buffer, "Error #%02d: %s\n", (i + 1), msg.Err)
		if msg.Meta != nil {
			fmt.Fprintf(&buffer, "     Meta: %v\n", msg.Meta)
		}
	}
	return buffer.String()
}
<|endoftext|>


<commit_before>package crypto

// xlattice_go/crypto/errors.go

import (
	e "errors"
)

var (
	CantAddToSignedList  = e.New("can't add, list has been signed")
	EmptyTitle              = e.New("empty title parameter")
	ImpossibleBlockSize     = e.New("impossible block size")
	IncorrectPKCS7Padding   = e.New("incorrectly padded data")
	ListAlreadySigned       = e.New("list has already been signed")
	MissingContentStart     = e.New("missing CONTENT START line")
	NdxOutOfRange           = e.New("list index out of range")
	NilData                 = e.New("nil data argument")
	NilPrivateKey           = e.New("nil private key parameter")
	NilPublicKey            = e.New("nil public key parameter")
	NotAnRSAPrivateKey      = e.New("Not an RSA private key")
	NotImplemented          = e.New("not implemented")
	NotAnRSAPublicKey       = e.New("Not an RSA public key")
	PemEncodeDecodeFailure  = e.New("Pem encode/decode failure")
	UnsignedList            = e.New("list has not been signed")
	X509ParseOrMarshalError = e.New("X509 parse/marshal error")
)
<commit_msg>consolidating use of version number, corrected misuse of rnglib/NextBytes()<commit_after>package crypto

// xlattice_go/crypto/errors.go

import (
	e "errors"
)

var (
	CantAddToSignedList     = e.New("can't add, list has been signed")
	EmptyTitle              = e.New("empty title parameter")
	ImpossibleBlockSize     = e.New("impossible block size")
	IncorrectPKCS7Padding   = e.New("incorrectly padded data")
	ListAlreadySigned       = e.New("list has already been signed")
	MissingContentStart     = e.New("missing CONTENT START line")
	NdxOutOfRange           = e.New("list index out of range")
	NilData                 = e.New("nil data argument")
	NilPrivateKey           = e.New("nil private key parameter")
	NilPublicKey            = e.New("nil public key parameter")
	NotAnRSAPrivateKey      = e.New("Not an RSA private key")
	NotImplemented          = e.New("not implemented")
	NotAnRSAPublicKey       = e.New("Not an RSA public key")
	PemEncodeDecodeFailure  = e.New("Pem encode/decode failure")
	UnsignedList            = e.New("list has not been signed")
	X509ParseOrMarshalError = e.New("X509 parse/marshal error")
)
<|endoftext|>


<commit_before>// Copyright 2014 Arne Roomann-Kurrik
//
// 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 twodee

import (
	glfw "github.com/go-gl/glfw/v3.1/glfw"
)

type EventHandler struct {
	Events chan Event
	window *glfw.Window
}

func NewEventHandler(w *glfw.Window) (e *EventHandler) {
	e = &EventHandler{
		Events: make(chan Event, 100),
		window: w,
	}
	// See http://www.glfw.org/docs/latest/input.html#input_keyboard
	w.SetInputMode(glfw.StickyKeysMode, 1)
	w.SetCursorPosCallback(e.onMouseMove)
	w.SetKeyCallback(e.onKey)
	w.SetMouseButtonCallback(e.onMouseButton)
	return
}

func (e *EventHandler) GetKey(code KeyCode) Action {
	return Action(e.window.GetKey(glfw.Key(code)))
}

func (e *EventHandler) Poll() {
	glfw.PollEvents()
}

func (e *EventHandler) onKey(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
	event := &KeyEvent{
		Code: KeyCode(key),
		Type: Action(action),
	}
	e.enqueue(event)
}

func (e *EventHandler) onMouseMove(w *glfw.Window, xoff float64, yoff float64) {
	event := &MouseMoveEvent{
		X: float32(xoff),
		Y: float32(yoff),
	}
	e.enqueue(event)
}

func (e *EventHandler) onMouseButton(w *glfw.Window, button glfw.MouseButton, action glfw.Action, mod glfw.ModifierKey) {
	event := &MouseButtonEvent{
		Type:   Action(action),
		Button: MouseButton(button),
	}
	e.enqueue(event)
}

func (e *EventHandler) enqueue(event Event) {
	select {
	case e.Events <- event:
		// Added to events
	default:
		// Events buffer is too full, not being read.
		// Drop the event on the floor.
		// TODO: Warn?
	}
}

type Event interface{}

type MouseMoveEvent struct {
	X float32
	Y float32
}

type MouseButtonEvent struct {
	Button MouseButton
	Type   Action
}

type KeyEvent struct {
	Code KeyCode
	Type Action
}

type KeyCode int

const (
	KeyUp     = KeyCode(glfw.KeyUp)
	KeyDown   = KeyCode(glfw.KeyDown)
	KeyLeft   = KeyCode(glfw.KeyLeft)
	KeyRight  = KeyCode(glfw.KeyRight)
	KeyEnter  = KeyCode(glfw.KeyEnter)
	KeyEscape = KeyCode(glfw.KeyEscape)
	KeySpace  = KeyCode(glfw.KeySpace)
	KeyA      = KeyCode(glfw.KeyA)
	KeyB      = KeyCode(glfw.KeyB)
	KeyC      = KeyCode(glfw.KeyC)
	KeyD      = KeyCode(glfw.KeyD)
	KeyE      = KeyCode(glfw.KeyE)
	KeyF      = KeyCode(glfw.KeyF)
	KeyG      = KeyCode(glfw.KeyG)
	KeyH      = KeyCode(glfw.KeyH)
	KeyI      = KeyCode(glfw.KeyI)
	KeyJ      = KeyCode(glfw.KeyJ)
	KeyK      = KeyCode(glfw.KeyK)
	KeyL      = KeyCode(glfw.KeyL)
	KeyM      = KeyCode(glfw.KeyM)
	KeyN      = KeyCode(glfw.KeyN)
	KeyO      = KeyCode(glfw.KeyO)
	KeyP      = KeyCode(glfw.KeyP)
	KeyQ      = KeyCode(glfw.KeyQ)
	KeyR      = KeyCode(glfw.KeyR)
	KeyS      = KeyCode(glfw.KeyS)
	KeyT      = KeyCode(glfw.KeyT)
	KeyU      = KeyCode(glfw.KeyU)
	KeyV      = KeyCode(glfw.KeyV)
	KeyW      = KeyCode(glfw.KeyW)
	KeyX      = KeyCode(glfw.KeyX)
	KeyY      = KeyCode(glfw.KeyY)
	KeyZ      = KeyCode(glfw.KeyZ)
)

type Action int

const (
	Release = Action(glfw.Release)
	Press   = Action(glfw.Press)
	Repeat  = Action(glfw.Repeat)
)

type MouseButton int

const (
	MouseButton1      = MouseButton(glfw.MouseButton1)
	MouseButton2      = MouseButton(glfw.MouseButton2)
	MouseButton3      = MouseButton(glfw.MouseButton3)
	MouseButton4      = MouseButton(glfw.MouseButton4)
	MouseButton5      = MouseButton(glfw.MouseButton5)
	MouseButton6      = MouseButton(glfw.MouseButton6)
	MouseButton7      = MouseButton(glfw.MouseButton7)
	MouseButton8      = MouseButton(glfw.MouseButton8)
	MouseButtonLast   = MouseButton(glfw.MouseButtonLast)
	MouseButtonLeft   = MouseButton(glfw.MouseButtonLeft)
	MouseButtonRight  = MouseButton(glfw.MouseButtonRight)
	MouseButtonMiddle = MouseButton(glfw.MouseButtonMiddle)
)
<commit_msg>Added number keys<commit_after>// Copyright 2014 Arne Roomann-Kurrik
//
// 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 twodee

import (
	glfw "github.com/go-gl/glfw/v3.1/glfw"
)

type EventHandler struct {
	Events chan Event
	window *glfw.Window
}

func NewEventHandler(w *glfw.Window) (e *EventHandler) {
	e = &EventHandler{
		Events: make(chan Event, 100),
		window: w,
	}
	// See http://www.glfw.org/docs/latest/input.html#input_keyboard
	w.SetInputMode(glfw.StickyKeysMode, 1)
	w.SetCursorPosCallback(e.onMouseMove)
	w.SetKeyCallback(e.onKey)
	w.SetMouseButtonCallback(e.onMouseButton)
	return
}

func (e *EventHandler) GetKey(code KeyCode) Action {
	return Action(e.window.GetKey(glfw.Key(code)))
}

func (e *EventHandler) Poll() {
	glfw.PollEvents()
}

func (e *EventHandler) onKey(w *glfw.Window, key glfw.Key, scancode int, action glfw.Action, mods glfw.ModifierKey) {
	event := &KeyEvent{
		Code: KeyCode(key),
		Type: Action(action),
	}
	e.enqueue(event)
}

func (e *EventHandler) onMouseMove(w *glfw.Window, xoff float64, yoff float64) {
	event := &MouseMoveEvent{
		X: float32(xoff),
		Y: float32(yoff),
	}
	e.enqueue(event)
}

func (e *EventHandler) onMouseButton(w *glfw.Window, button glfw.MouseButton, action glfw.Action, mod glfw.ModifierKey) {
	event := &MouseButtonEvent{
		Type:   Action(action),
		Button: MouseButton(button),
	}
	e.enqueue(event)
}

func (e *EventHandler) enqueue(event Event) {
	select {
	case e.Events <- event:
		// Added to events
	default:
		// Events buffer is too full, not being read.
		// Drop the event on the floor.
		// TODO: Warn?
	}
}

type Event interface{}

type MouseMoveEvent struct {
	X float32
	Y float32
}

type MouseButtonEvent struct {
	Button MouseButton
	Type   Action
}

type KeyEvent struct {
	Code KeyCode
	Type Action
}

type KeyCode int

const (
	KeyUp     = KeyCode(glfw.KeyUp)
	KeyDown   = KeyCode(glfw.KeyDown)
	KeyLeft   = KeyCode(glfw.KeyLeft)
	KeyRight  = KeyCode(glfw.KeyRight)
	KeyEnter  = KeyCode(glfw.KeyEnter)
	KeyEscape = KeyCode(glfw.KeyEscape)
	KeySpace  = KeyCode(glfw.KeySpace)
	KeyA      = KeyCode(glfw.KeyA)
	KeyB      = KeyCode(glfw.KeyB)
	KeyC      = KeyCode(glfw.KeyC)
	KeyD      = KeyCode(glfw.KeyD)
	KeyE      = KeyCode(glfw.KeyE)
	KeyF      = KeyCode(glfw.KeyF)
	KeyG      = KeyCode(glfw.KeyG)
	KeyH      = KeyCode(glfw.KeyH)
	KeyI      = KeyCode(glfw.KeyI)
	KeyJ      = KeyCode(glfw.KeyJ)
	KeyK      = KeyCode(glfw.KeyK)
	KeyL      = KeyCode(glfw.KeyL)
	KeyM      = KeyCode(glfw.KeyM)
	KeyN      = KeyCode(glfw.KeyN)
	KeyO      = KeyCode(glfw.KeyO)
	KeyP      = KeyCode(glfw.KeyP)
	KeyQ      = KeyCode(glfw.KeyQ)
	KeyR      = KeyCode(glfw.KeyR)
	KeyS      = KeyCode(glfw.KeyS)
	KeyT      = KeyCode(glfw.KeyT)
	KeyU      = KeyCode(glfw.KeyU)
	KeyV      = KeyCode(glfw.KeyV)
	KeyW      = KeyCode(glfw.KeyW)
	KeyX      = KeyCode(glfw.KeyX)
	KeyY      = KeyCode(glfw.KeyY)
	KeyZ      = KeyCode(glfw.KeyZ)
	Key1      = KeyCode(glfw.Key1)
	Key2      = KeyCode(glfw.Key2)
	Key3      = KeyCode(glfw.Key3)
	Key4      = KeyCode(glfw.Key4)
	Key5      = KeyCode(glfw.Key5)
	Key6      = KeyCode(glfw.Key6)
	Key7      = KeyCode(glfw.Key7)
	Key8      = KeyCode(glfw.Key8)
	Key9      = KeyCode(glfw.Key9)
	Key0      = KeyCode(glfw.Key0)
)

type Action int

const (
	Release = Action(glfw.Release)
	Press   = Action(glfw.Press)
	Repeat  = Action(glfw.Repeat)
)

type MouseButton int

const (
	MouseButton1      = MouseButton(glfw.MouseButton1)
	MouseButton2      = MouseButton(glfw.MouseButton2)
	MouseButton3      = MouseButton(glfw.MouseButton3)
	MouseButton4      = MouseButton(glfw.MouseButton4)
	MouseButton5      = MouseButton(glfw.MouseButton5)
	MouseButton6      = MouseButton(glfw.MouseButton6)
	MouseButton7      = MouseButton(glfw.MouseButton7)
	MouseButton8      = MouseButton(glfw.MouseButton8)
	MouseButtonLast   = MouseButton(glfw.MouseButtonLast)
	MouseButtonLeft   = MouseButton(glfw.MouseButtonLeft)
	MouseButtonRight  = MouseButton(glfw.MouseButtonRight)
	MouseButtonMiddle = MouseButton(glfw.MouseButtonMiddle)
)
<|endoftext|>


<commit_before>package gerrit

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/url"
	"time"
)

// PatchSet contains detailed information about a specific patch set.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/json.html#patchSet
type PatchSet struct {
	Number    string      `json:"number"`
	Revision  string      `json:"revision"`
	Parents   []string    `json:"parents"`
	Ref       string      `json:"ref"`
	Uploader  AccountInfo `json:"uploader"`
	Author    AccountInfo `json:"author"`
	CreatedOn int         `json:"createdOn"`
	IsDraft   bool        `json:"isDraft"`
	Kind      string      `json:"kind"`
}

// RefUpdate contains data about a reference update.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/json.html#refUpdate
type RefUpdate struct {
	OldRev  string `json:"oldRev"`
	NewRev  string `json:"newRev"`
	RefName string `json:"refName"`
	Project string `json:"project"`
}

// EventInfo contains information about an event emitted by Gerrit.  This
// structure can be used either when parsing streamed events or when reading
// the output of the events-log plugin.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/cmd-stream-events.html#events
type EventInfo struct {
	Type           string        `json:"type"`
	Change         ChangeInfo    `json:"change,omitempty"`
	ChangeKey      ChangeInfo    `json:"changeKey,omitempty"`
	PatchSet       PatchSet      `json:"patchSet,omitempty"`
	EventCreatedOn int           `json:"eventCreatedOn,omitempty"`
	Reason         string        `json:"reason,omitempty"`
	Abandoner      AccountInfo   `json:"abandoner,omitempty"`
	Restorer       AccountInfo   `json:"restorer,omitempty"`
	Submitter      AccountInfo   `json:"submitter,omitempty"`
	Author         AccountInfo   `json:"author,omitempty"`
	Uploader       AccountInfo   `json:"uploader,omitempty"`
	Approvals      []AccountInfo `json:"approvals,omitempty"`
	Comment        string        `json:"comment,omitempty"`
	Editor         AccountInfo   `json:"editor,omitempty"`
	Added          []string      `json:"added,omitempty"`
	Removed        []string      `json:"removed,omitempty"`
	Hashtags       []string      `json:"hashtags,omitempty"`
	RefUpdate      RefUpdate     `json:"refUpdate,omitempty"`
	Project        ProjectInfo   `json:"project,omitempty"`
	Reviewer       AccountInfo   `json:"reviewer,omitempty"`
	OldTopic       string        `json:"oldTopic,omitempty"`
	Changer        AccountInfo   `json:"changer,omitempty"`
}

// EventsLogService contains functions for querying the API provided
// by the optional events-log plugin.
type EventsLogService struct {
	client *Client
}

// EventsLogOptions contains options for querying events from the events-logs
// plugin.
type EventsLogOptions struct {
	From time.Time
	To   time.Time
}

// getURL returns the url that should be used in the request.  This will vary
// depending on the options provided to GetEvents.
func (events *EventsLogService) getURL(options *EventsLogOptions) (string, error) {
	parsed, err := url.Parse("/plugins/events-log/events/")
	if err != nil {
		return "", err
	}

	query := parsed.Query()

	if !options.From.IsZero() {
		query.Set("t1", options.From.Format("2006-01-02 15:04:05"))
	}

	if !options.To.IsZero() {
		query.Set("t2", options.To.Format("2006-01-02 15:04:05"))
	}

	encoded := query.Encode()
	if len(encoded) > 0 {
		parsed.RawQuery = encoded
	}

	return parsed.String(), nil
}

// GetEvents returns a list of events for the given input options.  Use of this
// function an authenticated user.
//
// Gerrit API docs: https://<yourserver>/plugins/events-log/Documentation/rest-api-events.html
func (events *EventsLogService) GetEvents(options *EventsLogOptions) (*[]EventInfo, *Response, error) {
	requestURL, err := events.getURL(options)
	if err != nil {
		return nil, nil, err
	}

	request, err := events.client.NewRequest("GET", requestURL, nil)
	if err != nil {
		return nil, nil, err
	}

	// Perform the request but do not pass in a structure to unpack
	// the response into.  The format of the response is one EventInfo
	// object per line so we need to manually handle the response here.
	response, err := events.client.Do(request, nil)
	if err != nil {
		return nil, nil, err
	}

	body, err := ioutil.ReadAll(response.Body)

	defer response.Body.Close()
	if err != nil {
		return nil, nil, err
	}

	eventInfo := new([]EventInfo)
	for _, line := range bytes.Split(body, []byte("\n")) {
		if len(line) > 0 {
			event := EventInfo{}
			err := json.Unmarshal(line, &event)
			if err != nil {
				return nil, nil, err
			}
			*eventInfo = append(*eventInfo, event)
		}
	}

	return eventInfo, response, err
}
<commit_msg>adding EventsLogOptions.IgnoreUnmarshalErrors (see comment in code)<commit_after>package gerrit

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/url"
	"time"
)

// PatchSet contains detailed information about a specific patch set.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/json.html#patchSet
type PatchSet struct {
	Number    string      `json:"number"`
	Revision  string      `json:"revision"`
	Parents   []string    `json:"parents"`
	Ref       string      `json:"ref"`
	Uploader  AccountInfo `json:"uploader"`
	Author    AccountInfo `json:"author"`
	CreatedOn int         `json:"createdOn"`
	IsDraft   bool        `json:"isDraft"`
	Kind      string      `json:"kind"`
}

// RefUpdate contains data about a reference update.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/json.html#refUpdate
type RefUpdate struct {
	OldRev  string `json:"oldRev"`
	NewRev  string `json:"newRev"`
	RefName string `json:"refName"`
	Project string `json:"project"`
}

// EventInfo contains information about an event emitted by Gerrit.  This
// structure can be used either when parsing streamed events or when reading
// the output of the events-log plugin.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/cmd-stream-events.html#events
type EventInfo struct {
	Type           string        `json:"type"`
	Change         ChangeInfo    `json:"change,omitempty"`
	ChangeKey      ChangeInfo    `json:"changeKey,omitempty"`
	PatchSet       PatchSet      `json:"patchSet,omitempty"`
	EventCreatedOn int           `json:"eventCreatedOn,omitempty"`
	Reason         string        `json:"reason,omitempty"`
	Abandoner      AccountInfo   `json:"abandoner,omitempty"`
	Restorer       AccountInfo   `json:"restorer,omitempty"`
	Submitter      AccountInfo   `json:"submitter,omitempty"`
	Author         AccountInfo   `json:"author,omitempty"`
	Uploader       AccountInfo   `json:"uploader,omitempty"`
	Approvals      []AccountInfo `json:"approvals,omitempty"`
	Comment        string        `json:"comment,omitempty"`
	Editor         AccountInfo   `json:"editor,omitempty"`
	Added          []string      `json:"added,omitempty"`
	Removed        []string      `json:"removed,omitempty"`
	Hashtags       []string      `json:"hashtags,omitempty"`
	RefUpdate      RefUpdate     `json:"refUpdate,omitempty"`
	Project        ProjectInfo   `json:"project,omitempty"`
	Reviewer       AccountInfo   `json:"reviewer,omitempty"`
	OldTopic       string        `json:"oldTopic,omitempty"`
	Changer        AccountInfo   `json:"changer,omitempty"`
}

// EventsLogService contains functions for querying the API provided
// by the optional events-log plugin.
type EventsLogService struct {
	client *Client
}

// EventsLogOptions contains options for querying events from the events-logs
// plugin.
type EventsLogOptions struct {
	From time.Time
	To   time.Time

	// IgnoreUnmarshalErrors will cause GetEvents to ignore any errors
	// that come up when calling json.Unmarshal. This can be useful in
	// cases where the events-log plugin was not kept up to date with
	// the Gerrit version for some reason. In these cases the events-log
	// plugin will return data structs that don't match the EventInfo
	// struct which in turn causes issues for json.Unmarshal.
	IgnoreUnmarshalErrors bool
}

// getURL returns the url that should be used in the request.  This will vary
// depending on the options provided to GetEvents.
func (events *EventsLogService) getURL(options *EventsLogOptions) (string, error) {
	parsed, err := url.Parse("/plugins/events-log/events/")
	if err != nil {
		return "", err
	}

	query := parsed.Query()

	if !options.From.IsZero() {
		query.Set("t1", options.From.Format("2006-01-02 15:04:05"))
	}

	if !options.To.IsZero() {
		query.Set("t2", options.To.Format("2006-01-02 15:04:05"))
	}

	encoded := query.Encode()
	if len(encoded) > 0 {
		parsed.RawQuery = encoded
	}

	return parsed.String(), nil
}

// GetEvents returns a list of events for the given input options.  Use of this
// function an authenticated user.
//
// Gerrit API docs: https://<yourserver>/plugins/events-log/Documentation/rest-api-events.html
func (events *EventsLogService) GetEvents(options *EventsLogOptions) (*[]EventInfo, *Response, error) {
	requestURL, err := events.getURL(options)
	if err != nil {
		return nil, nil, err
	}

	request, err := events.client.NewRequest("GET", requestURL, nil)
	if err != nil {
		return nil, nil, err
	}

	// Perform the request but do not pass in a structure to unpack
	// the response into.  The format of the response is one EventInfo
	// object per line so we need to manually handle the response here.
	response, err := events.client.Do(request, nil)
	if err != nil {
		return nil, nil, err
	}

	body, err := ioutil.ReadAll(response.Body)

	defer response.Body.Close()
	if err != nil {
		return nil, nil, err
	}

	eventInfo := new([]EventInfo)
	for _, line := range bytes.Split(body, []byte("\n")) {
		if len(line) > 0 {
			event := EventInfo{}
			err := json.Unmarshal(line, &event)
			if err != nil && !options.IgnoreUnmarshalErrors {
				return nil, nil, err
			}
			*eventInfo = append(*eventInfo, event)
		}
	}

	return eventInfo, response, err
}
<|endoftext|>


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

package user

import (
	"bytes"
	"fmt"

	"github.com/Unknwon/com"
	"github.com/Unknwon/paginater"

	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/modules/base"
	"github.com/gogits/gogs/modules/middleware"
	"github.com/gogits/gogs/modules/setting"
)

const (
	DASHBOARD base.TplName = "user/dashboard/dashboard"
	ISSUES    base.TplName = "user/dashboard/issues"
	PROFILE   base.TplName = "user/profile"
	ORG_HOME  base.TplName = "org/home"
)

func getDashboardContextUser(ctx *middleware.Context) *models.User {
	ctxUser := ctx.User
	orgName := ctx.Params(":org")
	if len(orgName) > 0 {
		// Organization.
		org, err := models.GetUserByName(orgName)
		if err != nil {
			if models.IsErrUserNotExist(err) {
				ctx.Handle(404, "GetUserByName", err)
			} else {
				ctx.Handle(500, "GetUserByName", err)
			}
			return nil
		}
		ctxUser = org
	}
	ctx.Data["ContextUser"] = ctxUser

	if err := ctx.User.GetOrganizations(true); err != nil {
		ctx.Handle(500, "GetOrganizations", err)
		return nil
	}
	ctx.Data["Orgs"] = ctx.User.Orgs

	return ctxUser
}

func retrieveFeeds(ctx *middleware.Context, ctxUserID, userID, offset int64, isProfile bool) {
	actions, err := models.GetFeeds(ctxUserID, userID, offset, isProfile)
	if err != nil {
		ctx.Handle(500, "GetFeeds", err)
		return
	}

	// Check access of private repositories.
	feeds := make([]*models.Action, 0, len(actions))
	unameAvatars := make(map[string]string)
	for _, act := range actions {
		// Cache results to reduce queries.
		_, ok := unameAvatars[act.ActUserName]
		if !ok {
			u, err := models.GetUserByName(act.ActUserName)
			if err != nil {
				if models.IsErrUserNotExist(err) {
					continue
				}
				ctx.Handle(500, "GetUserByName", err)
				return
			}
			unameAvatars[act.ActUserName] = u.AvatarLink()
		}

		act.ActAvatar = unameAvatars[act.ActUserName]
		feeds = append(feeds, act)
	}
	ctx.Data["Feeds"] = feeds
}

func Dashboard(ctx *middleware.Context) {
  ctxUser := getDashboardContextUser(ctx)
	ctx.Data["Title"] = ctxUser.DisplayName() + " " + ctx.Tr("dashboard")
	ctx.Data["PageIsDashboard"] = true
	ctx.Data["PageIsNews"] = true

	if ctx.Written() {
		return
	}

	if !ctxUser.IsOrganization() {
		collaborateRepos, err := ctx.User.GetAccessibleRepositories()
		if err != nil {
			ctx.Handle(500, "GetAccessibleRepositories", err)
			return
		}

		for i := range collaborateRepos {
			if err = collaborateRepos[i].GetOwner(); err != nil {
				ctx.Handle(500, "GetOwner: "+collaborateRepos[i].Name, err)
				return
			}
		}
		ctx.Data["CollaborateCount"] = len(collaborateRepos)
		ctx.Data["CollaborativeRepos"] = collaborateRepos
	}

	var repos []*models.Repository
	if ctxUser.IsOrganization() {
		if err := ctxUser.GetUserRepositories(ctx.User.Id); err != nil {
			ctx.Handle(500, "GetUserRepositories", err)
			return
		}
		repos = ctxUser.Repos
	} else {
		var err error
		repos, err = models.GetRepositories(ctxUser.Id, true)
		if err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	}
	ctx.Data["Repos"] = repos

	// Get mirror repositories.
	mirrors := make([]*models.Repository, 0, 5)
	for _, repo := range repos {
		if repo.IsMirror {
			if err := repo.GetMirror(); err != nil {
				ctx.Handle(500, "GetMirror: "+repo.Name, err)
				return
			}
			mirrors = append(mirrors, repo)
		}
	}
	ctx.Data["MirrorCount"] = len(mirrors)
	ctx.Data["Mirrors"] = mirrors

	retrieveFeeds(ctx, ctxUser.Id, ctx.User.Id, 0, false)
	if ctx.Written() {
		return
	}
	ctx.HTML(200, DASHBOARD)
}

func Issues(ctx *middleware.Context) {
	isPullList := ctx.Params(":type") == "pulls"
	if isPullList {
		ctx.Data["Title"] = ctx.Tr("pull_requests")
		ctx.Data["PageIsPulls"] = true
	} else {
		ctx.Data["Title"] = ctx.Tr("issues")
		ctx.Data["PageIsIssues"] = true
	}

	ctxUser := getDashboardContextUser(ctx)
	if ctx.Written() {
		return
	}

	// Organization does not have view type and filter mode.
	var (
		viewType   string
		sortType   = ctx.Query("sort")
		filterMode = models.FM_ALL
		assigneeID int64
		posterID   int64
	)
	if ctxUser.IsOrganization() {
		viewType = "all"
	} else {
		viewType = ctx.Query("type")
		types := []string{"assigned", "created_by"}
		if !com.IsSliceContainsStr(types, viewType) {
			viewType = "all"
		}

		switch viewType {
		case "assigned":
			filterMode = models.FM_ASSIGN
			assigneeID = ctxUser.Id
		case "created_by":
			filterMode = models.FM_CREATE
			posterID = ctxUser.Id
		}
	}

	repoID := ctx.QueryInt64("repo")
	isShowClosed := ctx.Query("state") == "closed"

	// Get repositories.
	if ctxUser.IsOrganization() {
		if err := ctxUser.GetUserRepositories(ctx.User.Id); err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	} else {
		if err := ctxUser.GetRepositories(); err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	}
	repos := ctxUser.Repos

	allCount := 0
	repoIDs := make([]int64, 0, len(repos))
	showRepos := make([]*models.Repository, 0, len(repos))
	for _, repo := range repos {
		if (isPullList && repo.NumPulls == 0) ||
			(!isPullList && repo.NumIssues == 0) {
			continue
		}

		repoIDs = append(repoIDs, repo.ID)

		if isPullList {
			allCount += repo.NumOpenPulls
			repo.NumOpenIssues = repo.NumOpenPulls
			repo.NumClosedIssues = repo.NumClosedPulls
		} else {
			allCount += repo.NumOpenIssues
		}

		if filterMode != models.FM_ALL {
			// Calculate repository issue count with filter mode.
			numOpen, numClosed := repo.IssueStats(ctxUser.Id, filterMode, isPullList)
			repo.NumOpenIssues, repo.NumClosedIssues = int(numOpen), int(numClosed)
		}

		if repo.ID == repoID ||
			(isShowClosed && repo.NumClosedIssues > 0) ||
			(!isShowClosed && repo.NumOpenIssues > 0) {
			showRepos = append(showRepos, repo)
		}
	}
	ctx.Data["Repos"] = showRepos

	issueStats := models.GetUserIssueStats(repoID, ctxUser.Id, repoIDs, filterMode, isPullList)
	issueStats.AllCount = int64(allCount)

	page := ctx.QueryInt("page")
	if page <= 1 {
		page = 1
	}

	var total int
	if !isShowClosed {
		total = int(issueStats.OpenCount)
	} else {
		total = int(issueStats.ClosedCount)
	}
	ctx.Data["Page"] = paginater.New(total, setting.IssuePagingNum, page, 5)

	// Get issues.
	issues, err := models.Issues(&models.IssuesOptions{
		UserID:     ctxUser.Id,
		AssigneeID: assigneeID,
		RepoID:     repoID,
		PosterID:   posterID,
		RepoIDs:    repoIDs,
		Page:       page,
		IsClosed:   isShowClosed,
		IsPull:     isPullList,
		SortType:   sortType,
	})
	if err != nil {
		ctx.Handle(500, "Issues: %v", err)
		return
	}

	// Get posters and repository.
	for i := range issues {
		issues[i].Repo, err = models.GetRepositoryByID(issues[i].RepoID)
		if err != nil {
			ctx.Handle(500, "GetRepositoryByID", fmt.Errorf("[#%d]%v", issues[i].ID, err))
			return
		}

		if err = issues[i].Repo.GetOwner(); err != nil {
			ctx.Handle(500, "GetOwner", fmt.Errorf("[#%d]%v", issues[i].ID, err))
			return
		}

		if err = issues[i].GetPoster(); err != nil {
			ctx.Handle(500, "GetPoster", fmt.Errorf("[#%d]%v", issues[i].ID, err))
			return
		}
	}
	ctx.Data["Issues"] = issues

	ctx.Data["IssueStats"] = issueStats
	ctx.Data["ViewType"] = viewType
	ctx.Data["SortType"] = sortType
	ctx.Data["RepoID"] = repoID
	ctx.Data["IsShowClosed"] = isShowClosed
	if isShowClosed {
		ctx.Data["State"] = "closed"
	} else {
		ctx.Data["State"] = "open"
	}

	ctx.HTML(200, ISSUES)
}

func ShowSSHKeys(ctx *middleware.Context, uid int64) {
	keys, err := models.ListPublicKeys(uid)
	if err != nil {
		ctx.Handle(500, "ListPublicKeys", err)
		return
	}

	var buf bytes.Buffer
	for i := range keys {
		buf.WriteString(keys[i].OmitEmail())
		buf.WriteString("\n")
	}
	ctx.PlainText(200, buf.Bytes())
}

func showOrgProfile(ctx *middleware.Context) {
	ctx.SetParams(":org", ctx.Params(":username"))
	middleware.HandleOrgAssignment(ctx)
	if ctx.Written() {
		return
	}

	org := ctx.Org.Organization
	ctx.Data["Title"] = org.FullName

	if ctx.IsSigned {
		if err := org.GetUserRepositories(ctx.User.Id); err != nil {
			ctx.Handle(500, "GetUserRepositories", err)
			return
		}
		ctx.Data["Repos"] = org.Repos
	} else {
		repos, err := models.GetRepositories(org.Id, false)
		if err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
		ctx.Data["Repos"] = repos
	}

	if err := org.GetMembers(); err != nil {
		ctx.Handle(500, "GetMembers", err)
		return
	}
	ctx.Data["Members"] = org.Members

	ctx.Data["Teams"] = org.Teams

	ctx.HTML(200, ORG_HOME)
}

func Email2User(ctx *middleware.Context) {
	u, err := models.GetUserByEmail(ctx.Query("email"))
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.Handle(404, "GetUserByEmail", err)
		} else {
			ctx.Handle(500, "GetUserByEmail", err)
		}
		return
	}
	ctx.Redirect(setting.AppSubUrl + "/user/" + u.Name)
}
<commit_msg>Remove dashboard keyword from title<commit_after>// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package user

import (
	"bytes"
	"fmt"

	"github.com/Unknwon/com"
	"github.com/Unknwon/paginater"

	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/modules/base"
	"github.com/gogits/gogs/modules/middleware"
	"github.com/gogits/gogs/modules/setting"
)

const (
	DASHBOARD base.TplName = "user/dashboard/dashboard"
	ISSUES    base.TplName = "user/dashboard/issues"
	PROFILE   base.TplName = "user/profile"
	ORG_HOME  base.TplName = "org/home"
)

func getDashboardContextUser(ctx *middleware.Context) *models.User {
	ctxUser := ctx.User
	orgName := ctx.Params(":org")
	if len(orgName) > 0 {
		// Organization.
		org, err := models.GetUserByName(orgName)
		if err != nil {
			if models.IsErrUserNotExist(err) {
				ctx.Handle(404, "GetUserByName", err)
			} else {
				ctx.Handle(500, "GetUserByName", err)
			}
			return nil
		}
		ctxUser = org
	}
	ctx.Data["ContextUser"] = ctxUser

	if err := ctx.User.GetOrganizations(true); err != nil {
		ctx.Handle(500, "GetOrganizations", err)
		return nil
	}
	ctx.Data["Orgs"] = ctx.User.Orgs

	return ctxUser
}

func retrieveFeeds(ctx *middleware.Context, ctxUserID, userID, offset int64, isProfile bool) {
	actions, err := models.GetFeeds(ctxUserID, userID, offset, isProfile)
	if err != nil {
		ctx.Handle(500, "GetFeeds", err)
		return
	}

	// Check access of private repositories.
	feeds := make([]*models.Action, 0, len(actions))
	unameAvatars := make(map[string]string)
	for _, act := range actions {
		// Cache results to reduce queries.
		_, ok := unameAvatars[act.ActUserName]
		if !ok {
			u, err := models.GetUserByName(act.ActUserName)
			if err != nil {
				if models.IsErrUserNotExist(err) {
					continue
				}
				ctx.Handle(500, "GetUserByName", err)
				return
			}
			unameAvatars[act.ActUserName] = u.AvatarLink()
		}

		act.ActAvatar = unameAvatars[act.ActUserName]
		feeds = append(feeds, act)
	}
	ctx.Data["Feeds"] = feeds
}

func Dashboard(ctx *middleware.Context) {
  ctxUser := getDashboardContextUser(ctx)
	ctx.Data["Title"] = ctxUser.DisplayName()
	ctx.Data["PageIsDashboard"] = true
	ctx.Data["PageIsNews"] = true

	if ctx.Written() {
		return
	}

	if !ctxUser.IsOrganization() {
		collaborateRepos, err := ctx.User.GetAccessibleRepositories()
		if err != nil {
			ctx.Handle(500, "GetAccessibleRepositories", err)
			return
		}

		for i := range collaborateRepos {
			if err = collaborateRepos[i].GetOwner(); err != nil {
				ctx.Handle(500, "GetOwner: "+collaborateRepos[i].Name, err)
				return
			}
		}
		ctx.Data["CollaborateCount"] = len(collaborateRepos)
		ctx.Data["CollaborativeRepos"] = collaborateRepos
	}

	var repos []*models.Repository
	if ctxUser.IsOrganization() {
		if err := ctxUser.GetUserRepositories(ctx.User.Id); err != nil {
			ctx.Handle(500, "GetUserRepositories", err)
			return
		}
		repos = ctxUser.Repos
	} else {
		var err error
		repos, err = models.GetRepositories(ctxUser.Id, true)
		if err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	}
	ctx.Data["Repos"] = repos

	// Get mirror repositories.
	mirrors := make([]*models.Repository, 0, 5)
	for _, repo := range repos {
		if repo.IsMirror {
			if err := repo.GetMirror(); err != nil {
				ctx.Handle(500, "GetMirror: "+repo.Name, err)
				return
			}
			mirrors = append(mirrors, repo)
		}
	}
	ctx.Data["MirrorCount"] = len(mirrors)
	ctx.Data["Mirrors"] = mirrors

	retrieveFeeds(ctx, ctxUser.Id, ctx.User.Id, 0, false)
	if ctx.Written() {
		return
	}
	ctx.HTML(200, DASHBOARD)
}

func Issues(ctx *middleware.Context) {
	isPullList := ctx.Params(":type") == "pulls"
	if isPullList {
		ctx.Data["Title"] = ctx.Tr("pull_requests")
		ctx.Data["PageIsPulls"] = true
	} else {
		ctx.Data["Title"] = ctx.Tr("issues")
		ctx.Data["PageIsIssues"] = true
	}

	ctxUser := getDashboardContextUser(ctx)
	if ctx.Written() {
		return
	}

	// Organization does not have view type and filter mode.
	var (
		viewType   string
		sortType   = ctx.Query("sort")
		filterMode = models.FM_ALL
		assigneeID int64
		posterID   int64
	)
	if ctxUser.IsOrganization() {
		viewType = "all"
	} else {
		viewType = ctx.Query("type")
		types := []string{"assigned", "created_by"}
		if !com.IsSliceContainsStr(types, viewType) {
			viewType = "all"
		}

		switch viewType {
		case "assigned":
			filterMode = models.FM_ASSIGN
			assigneeID = ctxUser.Id
		case "created_by":
			filterMode = models.FM_CREATE
			posterID = ctxUser.Id
		}
	}

	repoID := ctx.QueryInt64("repo")
	isShowClosed := ctx.Query("state") == "closed"

	// Get repositories.
	if ctxUser.IsOrganization() {
		if err := ctxUser.GetUserRepositories(ctx.User.Id); err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	} else {
		if err := ctxUser.GetRepositories(); err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
	}
	repos := ctxUser.Repos

	allCount := 0
	repoIDs := make([]int64, 0, len(repos))
	showRepos := make([]*models.Repository, 0, len(repos))
	for _, repo := range repos {
		if (isPullList && repo.NumPulls == 0) ||
			(!isPullList && repo.NumIssues == 0) {
			continue
		}

		repoIDs = append(repoIDs, repo.ID)

		if isPullList {
			allCount += repo.NumOpenPulls
			repo.NumOpenIssues = repo.NumOpenPulls
			repo.NumClosedIssues = repo.NumClosedPulls
		} else {
			allCount += repo.NumOpenIssues
		}

		if filterMode != models.FM_ALL {
			// Calculate repository issue count with filter mode.
			numOpen, numClosed := repo.IssueStats(ctxUser.Id, filterMode, isPullList)
			repo.NumOpenIssues, repo.NumClosedIssues = int(numOpen), int(numClosed)
		}

		if repo.ID == repoID ||
			(isShowClosed && repo.NumClosedIssues > 0) ||
			(!isShowClosed && repo.NumOpenIssues > 0) {
			showRepos = append(showRepos, repo)
		}
	}
	ctx.Data["Repos"] = showRepos

	issueStats := models.GetUserIssueStats(repoID, ctxUser.Id, repoIDs, filterMode, isPullList)
	issueStats.AllCount = int64(allCount)

	page := ctx.QueryInt("page")
	if page <= 1 {
		page = 1
	}

	var total int
	if !isShowClosed {
		total = int(issueStats.OpenCount)
	} else {
		total = int(issueStats.ClosedCount)
	}
	ctx.Data["Page"] = paginater.New(total, setting.IssuePagingNum, page, 5)

	// Get issues.
	issues, err := models.Issues(&models.IssuesOptions{
		UserID:     ctxUser.Id,
		AssigneeID: assigneeID,
		RepoID:     repoID,
		PosterID:   posterID,
		RepoIDs:    repoIDs,
		Page:       page,
		IsClosed:   isShowClosed,
		IsPull:     isPullList,
		SortType:   sortType,
	})
	if err != nil {
		ctx.Handle(500, "Issues: %v", err)
		return
	}

	// Get posters and repository.
	for i := range issues {
		issues[i].Repo, err = models.GetRepositoryByID(issues[i].RepoID)
		if err != nil {
			ctx.Handle(500, "GetRepositoryByID", fmt.Errorf("[#%d]%v", issues[i].ID, err))
			return
		}

		if err = issues[i].Repo.GetOwner(); err != nil {
			ctx.Handle(500, "GetOwner", fmt.Errorf("[#%d]%v", issues[i].ID, err))
			return
		}

		if err = issues[i].GetPoster(); err != nil {
			ctx.Handle(500, "GetPoster", fmt.Errorf("[#%d]%v", issues[i].ID, err))
			return
		}
	}
	ctx.Data["Issues"] = issues

	ctx.Data["IssueStats"] = issueStats
	ctx.Data["ViewType"] = viewType
	ctx.Data["SortType"] = sortType
	ctx.Data["RepoID"] = repoID
	ctx.Data["IsShowClosed"] = isShowClosed
	if isShowClosed {
		ctx.Data["State"] = "closed"
	} else {
		ctx.Data["State"] = "open"
	}

	ctx.HTML(200, ISSUES)
}

func ShowSSHKeys(ctx *middleware.Context, uid int64) {
	keys, err := models.ListPublicKeys(uid)
	if err != nil {
		ctx.Handle(500, "ListPublicKeys", err)
		return
	}

	var buf bytes.Buffer
	for i := range keys {
		buf.WriteString(keys[i].OmitEmail())
		buf.WriteString("\n")
	}
	ctx.PlainText(200, buf.Bytes())
}

func showOrgProfile(ctx *middleware.Context) {
	ctx.SetParams(":org", ctx.Params(":username"))
	middleware.HandleOrgAssignment(ctx)
	if ctx.Written() {
		return
	}

	org := ctx.Org.Organization
	ctx.Data["Title"] = org.FullName

	if ctx.IsSigned {
		if err := org.GetUserRepositories(ctx.User.Id); err != nil {
			ctx.Handle(500, "GetUserRepositories", err)
			return
		}
		ctx.Data["Repos"] = org.Repos
	} else {
		repos, err := models.GetRepositories(org.Id, false)
		if err != nil {
			ctx.Handle(500, "GetRepositories", err)
			return
		}
		ctx.Data["Repos"] = repos
	}

	if err := org.GetMembers(); err != nil {
		ctx.Handle(500, "GetMembers", err)
		return
	}
	ctx.Data["Members"] = org.Members

	ctx.Data["Teams"] = org.Teams

	ctx.HTML(200, ORG_HOME)
}

func Email2User(ctx *middleware.Context) {
	u, err := models.GetUserByEmail(ctx.Query("email"))
	if err != nil {
		if models.IsErrUserNotExist(err) {
			ctx.Handle(404, "GetUserByEmail", err)
		} else {
			ctx.Handle(500, "GetUserByEmail", err)
		}
		return
	}
	ctx.Redirect(setting.AppSubUrl + "/user/" + u.Name)
}
<|endoftext|>


<commit_before>// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.

// +build !windows

// Keybase file system

package main

import (
	"flag"
	"fmt"
	"os"

	"bazil.org/fuse"

	"github.com/keybase/client/go/kbfs/env"
	"github.com/keybase/client/go/kbfs/libfs"
	"github.com/keybase/client/go/kbfs/libfuse"
	"github.com/keybase/client/go/kbfs/libkbfs"
	"github.com/keybase/client/go/logger"
)

var runtimeDir = flag.String("runtime-dir", os.Getenv("KEYBASE_RUNTIME_DIR"), "runtime directory")
var label = flag.String("label", os.Getenv("KEYBASE_LABEL"), "label to help identify if running as a service")
var mountType = flag.String("mount-type", defaultMountType, "mount type: default, force, none")
var version = flag.Bool("version", false, "Print version")

const usageFormatStr = `Usage:
  kbfsfuse -version

To run against remote KBFS servers:
  kbfsfuse
    [-runtime-dir=path/to/dir] [-label=label] [-mount-type=default|force|required|none]
%s
    %s[/path/to/mountpoint]

To run in a local testing environment:
  kbfsfuse
    [-runtime-dir=path/to/dir] [-label=label] [-mount-type=default|force|required|none]
%s
    %s[/path/to/mountpoint]

Defaults:
%s `

func getUsageString(ctx libkbfs.Context) string {
	remoteUsageStr := libkbfs.GetRemoteUsageString()
	localUsageStr := libkbfs.GetLocalUsageString()
	platformUsageStr := libfuse.GetPlatformUsageString()
	defaultUsageStr := libkbfs.GetDefaultsUsageString(ctx)
	return fmt.Sprintf(usageFormatStr,
		remoteUsageStr, platformUsageStr,
		localUsageStr, platformUsageStr, defaultUsageStr)
}

func start() *libfs.Error {
	ctx := env.NewContext()

	kbfsParams := libkbfs.AddFlags(flag.CommandLine, ctx)
	platformParams := libfuse.AddPlatformFlags(flag.CommandLine)

	flag.Parse()

	if *version {
		fmt.Printf("%s\n", libkbfs.VersionString())
		return nil
	}

	mountDir := ""
	if len(flag.Args()) < 1 {
		var err error
		mountDir, err = ctx.GetMountDir()
		if err != nil {
			return libfs.InitError(err.Error())
		}
		if len(mountDir) == 0 {
			fmt.Print(getUsageString(ctx))
			return libfs.InitError("no mount specified")
		}
	} else {
		mountDir = flag.Arg(0)
	}
	err := os.MkdirAll(mountDir, os.ModePerm)
	if err != nil {
		fmt.Println(err)
	}

	if len(flag.Args()) > 1 {
		fmt.Print(getUsageString(ctx))
		return libfs.InitError("extra arguments specified (flags go before the first argument)")
	}

	if kbfsParams.Debug {
		fuseLog := logger.NewWithCallDepth("FUSE", 1)
		fuseLog.Configure("", true, "")
		fuse.Debug = libfuse.MakeFuseDebugFn(
			fuseLog, false /* superVerbose */)
	}

	options := libfuse.StartOptions{
		KbfsParams:        *kbfsParams,
		PlatformParams:    *platformParams,
		RuntimeDir:        *runtimeDir,
		Label:             *label,
		ForceMount:        *mountType == "force" || *mountType == "required",
		MountErrorIsFatal: *mountType == "required",
		SkipMount:         *mountType == "none",
		MountPoint:        mountDir,
	}

	return libfuse.Start(options, ctx)
}

func main() {
	err := start()
	if err != nil {
		fmt.Fprintf(os.Stderr, "kbfsfuse error: (%d) %s\n", err.Code, err.Message)

		os.Exit(err.Code)
	}
	os.Exit(0)
}
<commit_msg>kbfsfuse: Add error logging if this fails.<commit_after>// Copyright 2016 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.

// +build !windows

// Keybase file system

package main

import (
	"flag"
	"fmt"
	"os"
	"runtime"

	"bazil.org/fuse"

	"github.com/keybase/client/go/kbfs/env"
	"github.com/keybase/client/go/kbfs/libfs"
	"github.com/keybase/client/go/kbfs/libfuse"
	"github.com/keybase/client/go/kbfs/libkbfs"
	"github.com/keybase/client/go/logger"
)

var runtimeDir = flag.String("runtime-dir", os.Getenv("KEYBASE_RUNTIME_DIR"), "runtime directory")
var label = flag.String("label", os.Getenv("KEYBASE_LABEL"), "label to help identify if running as a service")
var mountType = flag.String("mount-type", defaultMountType, "mount type: default, force, none")
var version = flag.Bool("version", false, "Print version")

const usageFormatStr = `Usage:
  kbfsfuse -version

To run against remote KBFS servers:
  kbfsfuse
    [-runtime-dir=path/to/dir] [-label=label] [-mount-type=default|force|required|none]
%s
    %s[/path/to/mountpoint]

To run in a local testing environment:
  kbfsfuse
    [-runtime-dir=path/to/dir] [-label=label] [-mount-type=default|force|required|none]
%s
    %s[/path/to/mountpoint]

Defaults:
%s `

func getUsageString(ctx libkbfs.Context) string {
	remoteUsageStr := libkbfs.GetRemoteUsageString()
	localUsageStr := libkbfs.GetLocalUsageString()
	platformUsageStr := libfuse.GetPlatformUsageString()
	defaultUsageStr := libkbfs.GetDefaultsUsageString(ctx)
	return fmt.Sprintf(usageFormatStr,
		remoteUsageStr, platformUsageStr,
		localUsageStr, platformUsageStr, defaultUsageStr)
}

func start() *libfs.Error {
	ctx := env.NewContext()

	kbfsParams := libkbfs.AddFlags(flag.CommandLine, ctx)
	platformParams := libfuse.AddPlatformFlags(flag.CommandLine)

	flag.Parse()

	if *version {
		fmt.Printf("%s\n", libkbfs.VersionString())
		return nil
	}

	mountDir := ""
	if len(flag.Args()) < 1 {
		var err error
		mountDir, err = ctx.GetMountDir()
		if err != nil {
			return libfs.InitError(err.Error())
		}
		if len(mountDir) == 0 {
			fmt.Print(getUsageString(ctx))
			return libfs.InitError("no mount specified")
		}
	} else {
		mountDir = flag.Arg(0)
	}
	err := os.MkdirAll(mountDir, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		switch os := runtime.GOOS; os {
		case "linux":
			fmt.Println("failed to create mount directory")
		case "darwin":
			// If the user did not override the defaults this isn't expected to work.
			// The default is in a directory only writable by root.
			fmt.Println("mount directory does not exist and should have been created by system service")
		case "windows":
			fmt.Println("I honestly have no idea what to say here, maybe someone can tell me what is supposed to create this on Windows")
		}
	}

	if len(flag.Args()) > 1 {
		fmt.Print(getUsageString(ctx))
		return libfs.InitError("extra arguments specified (flags go before the first argument)")
	}

	if kbfsParams.Debug {
		fuseLog := logger.NewWithCallDepth("FUSE", 1)
		fuseLog.Configure("", true, "")
		fuse.Debug = libfuse.MakeFuseDebugFn(
			fuseLog, false /* superVerbose */)
	}

	options := libfuse.StartOptions{
		KbfsParams:        *kbfsParams,
		PlatformParams:    *platformParams,
		RuntimeDir:        *runtimeDir,
		Label:             *label,
		ForceMount:        *mountType == "force" || *mountType == "required",
		MountErrorIsFatal: *mountType == "required",
		SkipMount:         *mountType == "none",
		MountPoint:        mountDir,
	}

	return libfuse.Start(options, ctx)
}

func main() {
	err := start()
	if err != nil {
		fmt.Fprintf(os.Stderr, "kbfsfuse error: (%d) %s\n", err.Code, err.Message)

		os.Exit(err.Code)
	}
	os.Exit(0)
}
<|endoftext|>


<commit_before>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package logger

import (
	"fmt"
	"runtime"
	"strings"
	"sync/atomic"
	"time"

	logging "github.com/keybase/go-logging"

	"golang.org/x/net/context"
)

// TestLogBackend is an interface for logging to a test object (i.e.,
// a *testing.T).  We define this in order to avoid pulling in the
// "testing" package in exported code.
type TestLogBackend interface {
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Log(args ...interface{})
	Logf(format string, args ...interface{})
	Failed() bool
	Name() string
}

// TestLogger is a Logger that writes to a TestLogBackend.  All
// messages except Fatal are printed using Logf, to avoid failing a
// test that is trying to test an error condition.  No context tags
// are logged.
type TestLogger struct {
	log          TestLogBackend
	extraDepth   int
	failReported int32 // 1 is true
}

func NewTestLogger(log TestLogBackend) *TestLogger {
	return &TestLogger{log: log}
}

// Verify TestLogger fully implements the Logger interface.
var _ Logger = (*TestLogger)(nil)

// ctx can be `nil`
func (log *TestLogger) common(ctx context.Context, lvl logging.Level, useFatal bool, fmts string, arg ...interface{}) {
	if log.log.Failed() {
		failReported := atomic.SwapInt32(&(log.failReported), 1)
		if failReported == 0 {
			log.log.Logf("TEST FAILED: %s", log.log.Name())
		}
	}

	if ctx != nil {
		if useFatal {
			log.log.Fatalf(prepareString(ctx,
				log.prefixCaller(log.extraDepth, lvl, fmts)), arg...)
		} else {
			log.log.Logf(prepareString(ctx,
				log.prefixCaller(log.extraDepth, lvl, fmts)), arg...)
		}
	} else {
		if useFatal {
			log.log.Fatalf(log.prefixCaller(log.extraDepth, lvl, fmts), arg...)
		} else {
			log.log.Logf(log.prefixCaller(log.extraDepth, lvl, fmts), arg...)
		}
	}
}

func (log *TestLogger) prefixCaller(extraDepth int, lvl logging.Level, fmts string) string {
	// The testing library doesn't let us control the stack depth,
	// and it always prints out its own prefix, so use \r to clear
	// it out (at least on a terminal) and do our own formatting.
	_, file, line, _ := runtime.Caller(3 + extraDepth)
	elements := strings.Split(file, "/")
	failed := ""
	if log.log.Failed() {
		failed = "[X] "
	}

	return fmt.Sprintf("\r%s %s%s:%d: [%.1s] %s", time.Now().Format("2006-01-02 15:04:05.00000"),
		failed, elements[len(elements)-1], line, lvl, fmts)
}

func (log *TestLogger) Debug(fmts string, arg ...interface{}) {
	log.common(nil, logging.INFO, false, fmts, arg...)
}

func (log *TestLogger) CDebugf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.DEBUG, false, fmts, arg...)
}

func (log *TestLogger) Info(fmts string, arg ...interface{}) {
	log.common(nil, logging.INFO, false, fmts, arg...)
}

func (log *TestLogger) CInfof(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.INFO, false, fmts, arg...)
}

func (log *TestLogger) Notice(fmts string, arg ...interface{}) {
	log.common(nil, logging.NOTICE, false, fmts, arg...)
}

func (log *TestLogger) CNoticef(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.NOTICE, false, fmts, arg...)
}

func (log *TestLogger) Warning(fmts string, arg ...interface{}) {
	log.common(nil, logging.WARNING, false, fmts, arg...)
}

func (log *TestLogger) CWarningf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.WARNING, false, fmts, arg...)
}

func (log *TestLogger) Error(fmts string, arg ...interface{}) {
	log.common(nil, logging.ERROR, false, fmts, arg...)
}

func (log *TestLogger) Errorf(fmts string, arg ...interface{}) {
	log.common(nil, logging.ERROR, false, fmts, arg...)
}

func (log *TestLogger) CErrorf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.ERROR, false, fmts, arg...)
}

func (log *TestLogger) Critical(fmts string, arg ...interface{}) {
	log.common(nil, logging.CRITICAL, false, fmts, arg...)
}

func (log *TestLogger) CCriticalf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.CRITICAL, false, fmts, arg...)
}

func (log *TestLogger) Fatalf(fmts string, arg ...interface{}) {
	log.common(nil, logging.CRITICAL, true, fmts, arg...)
}

func (log *TestLogger) CFatalf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.CRITICAL, true, fmts, arg...)
}

func (log *TestLogger) Profile(fmts string, arg ...interface{}) {
	log.common(nil, logging.CRITICAL, false, fmts, arg...)
}

func (log *TestLogger) Configure(style string, debug bool, filename string) {
	// no-op
}

func (log *TestLogger) RotateLogFile() error {
	// no-op
	return nil
}

func (log *TestLogger) CloneWithAddedDepth(depth int) Logger {
	clone := *log
	clone.extraDepth += depth
	return &clone
}

// no-op stubs to fulfill the Logger interface
func (log *TestLogger) SetExternalHandler(_ ExternalHandler) {}
<commit_msg>Fix data race in TestLogger<commit_after>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package logger

import (
	"fmt"
	"runtime"
	"strings"
	"sync"
	"time"

	logging "github.com/keybase/go-logging"

	"golang.org/x/net/context"
)

// TestLogBackend is an interface for logging to a test object (i.e.,
// a *testing.T).  We define this in order to avoid pulling in the
// "testing" package in exported code.
type TestLogBackend interface {
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Log(args ...interface{})
	Logf(format string, args ...interface{})
	Failed() bool
	Name() string
}

// TestLogger is a Logger that writes to a TestLogBackend.  All
// messages except Fatal are printed using Logf, to avoid failing a
// test that is trying to test an error condition.  No context tags
// are logged.
type TestLogger struct {
	log          TestLogBackend
	extraDepth   int
	failReported bool
	sync.Mutex
}

func NewTestLogger(log TestLogBackend) *TestLogger {
	return &TestLogger{log: log}
}

// Verify TestLogger fully implements the Logger interface.
var _ Logger = (*TestLogger)(nil)

// ctx can be `nil`
func (log *TestLogger) common(ctx context.Context, lvl logging.Level, useFatal bool, fmts string, arg ...interface{}) {
	if log.log.Failed() {
		log.Lock()
		if !log.failReported {
			log.log.Logf("TEST FAILED: %s", log.log.Name())
		}
		log.failReported = true
		log.Unlock()
	}

	if ctx != nil {
		if useFatal {
			log.log.Fatalf(prepareString(ctx,
				log.prefixCaller(log.extraDepth, lvl, fmts)), arg...)
		} else {
			log.log.Logf(prepareString(ctx,
				log.prefixCaller(log.extraDepth, lvl, fmts)), arg...)
		}
	} else {
		if useFatal {
			log.log.Fatalf(log.prefixCaller(log.extraDepth, lvl, fmts), arg...)
		} else {
			log.log.Logf(log.prefixCaller(log.extraDepth, lvl, fmts), arg...)
		}
	}
}

func (log *TestLogger) prefixCaller(extraDepth int, lvl logging.Level, fmts string) string {
	// The testing library doesn't let us control the stack depth,
	// and it always prints out its own prefix, so use \r to clear
	// it out (at least on a terminal) and do our own formatting.
	_, file, line, _ := runtime.Caller(3 + extraDepth)
	elements := strings.Split(file, "/")
	failed := ""
	if log.log.Failed() {
		failed = "[X] "
	}

	return fmt.Sprintf("\r%s %s%s:%d: [%.1s] %s", time.Now().Format("2006-01-02 15:04:05.00000"),
		failed, elements[len(elements)-1], line, lvl, fmts)
}

func (log *TestLogger) Debug(fmts string, arg ...interface{}) {
	log.common(nil, logging.INFO, false, fmts, arg...)
}

func (log *TestLogger) CDebugf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.DEBUG, false, fmts, arg...)
}

func (log *TestLogger) Info(fmts string, arg ...interface{}) {
	log.common(nil, logging.INFO, false, fmts, arg...)
}

func (log *TestLogger) CInfof(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.INFO, false, fmts, arg...)
}

func (log *TestLogger) Notice(fmts string, arg ...interface{}) {
	log.common(nil, logging.NOTICE, false, fmts, arg...)
}

func (log *TestLogger) CNoticef(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.NOTICE, false, fmts, arg...)
}

func (log *TestLogger) Warning(fmts string, arg ...interface{}) {
	log.common(nil, logging.WARNING, false, fmts, arg...)
}

func (log *TestLogger) CWarningf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.WARNING, false, fmts, arg...)
}

func (log *TestLogger) Error(fmts string, arg ...interface{}) {
	log.common(nil, logging.ERROR, false, fmts, arg...)
}

func (log *TestLogger) Errorf(fmts string, arg ...interface{}) {
	log.common(nil, logging.ERROR, false, fmts, arg...)
}

func (log *TestLogger) CErrorf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.ERROR, false, fmts, arg...)
}

func (log *TestLogger) Critical(fmts string, arg ...interface{}) {
	log.common(nil, logging.CRITICAL, false, fmts, arg...)
}

func (log *TestLogger) CCriticalf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.CRITICAL, false, fmts, arg...)
}

func (log *TestLogger) Fatalf(fmts string, arg ...interface{}) {
	log.common(nil, logging.CRITICAL, true, fmts, arg...)
}

func (log *TestLogger) CFatalf(ctx context.Context, fmts string,
	arg ...interface{}) {
	log.common(ctx, logging.CRITICAL, true, fmts, arg...)
}

func (log *TestLogger) Profile(fmts string, arg ...interface{}) {
	log.common(nil, logging.CRITICAL, false, fmts, arg...)
}

func (log *TestLogger) Configure(style string, debug bool, filename string) {
	// no-op
}

func (log *TestLogger) RotateLogFile() error {
	// no-op
	return nil
}

func (log *TestLogger) CloneWithAddedDepth(depth int) Logger {
	log.Lock()
	defer log.Unlock()
	var clone TestLogger
	clone.log = log.log
	clone.extraDepth = log.extraDepth + depth
	clone.failReported = log.failReported
	return &clone
}

// no-op stubs to fulfill the Logger interface
func (log *TestLogger) SetExternalHandler(_ ExternalHandler) {}
<|endoftext|>