<commit_before>// Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This LevelDB Go implementation is based on LevelDB C++ implementation.
// Which contains the following header:
//   Copyright (c) 2011 The LevelDB Authors. All rights reserved.
//   Use of this source code is governed by a BSD-style license that can be
//   found in the LEVELDBCPP_LICENSE file. See the LEVELDBCPP_AUTHORS file
//   for names of contributors.

// Package leveldb provides implementation of LevelDB key/value database.
//
// Create or open a database:
//
//	mydesc, err := descriptor.OpenFile("path/to/db")
//	...
//	mydb, err := db.Open(mydesc, &opt.Options{Flag: opt.OFCreateIfMissing})
//	...
//
// Read or modify the database content:
//
//	ro := &opt.ReadOptions{}
//	wo := &opt.WriteOptions{}
//	data, err := mydb.Get([]byte("key"), ro)
//	...
//	err = mydb.Put([]byte("key"), []byte("value"), wo)
//	...
//	err = mydb.Delete([]byte("key"), wo)
//	...
//
// Iterate over database content:
//
//	myiter := mydb.NewIterator(ro)
//	for myiter.Next() {
//		key := myiter.Key()
//		value := myiter.Value()
//		...
//	}
//	err = myiter.Error()
//	...
//
// Batch writes:
//
//	batch := new(db.Batch)
//	batch.Put([]byte("foo"), []byte("value"))
//	batch.Put([]byte("bar"), []byte("another value"))
//	batch.Delete([]byte("baz"))
//	err = mydb.Write(batch, wo)
//	...
//
// Use bloom filter:
//
//	o := &opt.Options{
//		Flag:   opt.OFCreateIfMissing,
//		Filter: filter.NewBloomFilter(10),
//	}
//	mydb, err := db.Open(mydesc, o)
//	...
package leveldb
<commit_msg>leveldb: fix doc<commit_after>// Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This LevelDB Go implementation is based on LevelDB C++ implementation.
// Which contains the following header:
//   Copyright (c) 2011 The LevelDB Authors. All rights reserved.
//   Use of this source code is governed by a BSD-style license that can be
//   found in the LEVELDBCPP_LICENSE file. See the LEVELDBCPP_AUTHORS file
//   for names of contributors.

// Package leveldb provides implementation of LevelDB key/value database.
//
// Create or open a database:
//
//	desc, err := descriptor.OpenFile("path/to/db")
//	...
//	db, err := leveldb.Open(desc, &opt.Options{Flag: opt.OFCreateIfMissing})
//	...
//
// Read or modify the database content:
//
//	ro := &opt.ReadOptions{}
//	wo := &opt.WriteOptions{}
//	data, err := db.Get([]byte("key"), ro)
//	...
//	err = db.Put([]byte("key"), []byte("value"), wo)
//	...
//	err = db.Delete([]byte("key"), wo)
//	...
//
// Iterate over database content:
//
//	iter := db.NewIterator(ro)
//	for iter.Next() {
//		key := iter.Key()
//		value := iter.Value()
//		...
//	}
//	err = iter.Error()
//	...
//
// Batch writes:
//
//	batch := new(leveldb.Batch)
//	batch.Put([]byte("foo"), []byte("value"))
//	batch.Put([]byte("bar"), []byte("another value"))
//	batch.Delete([]byte("baz"))
//	err = db.Write(batch, wo)
//	...
//
// Use bloom filter:
//
//	o := &opt.Options{
//		Flag:   opt.OFCreateIfMissing,
//		Filter: filter.NewBloomFilter(10),
//	}
//	db, err := leveldb.Open(desc, o)
//	...
package leveldb
<|endoftext|>


<commit_before>package lexer

import (
  "strings"
  "unicode/utf8"
)

type TokenType int

type Token struct {
  Type  TokenType
  Value string
}

const EOF = -1

type stateFn func(*Lexer) stateFn

type Lexer struct {
  name   string
  input  string
  state  stateFn
  start  int
  pos    int
  width  int
  tokens chan Token
}

func NewLexer(name, input string) *Lexer {
  l := &Lexer{
    name:   name,
    input:  input,
    tokens: make(chan Token),
  }
  go l.run()
  return l
}

func (l *Lexer) NextToken() Token {
  return <-l.tokens
}

func (l *Lexer) run() {
  for l.state = lexWhiteSpace; l.state != nil; {
    l.state = l.state(l)
  }
  close(l.tokens)
}

func (l *Lexer) emit(typ TokenType) {
  l.tokens <- Token{typ, l.input[l.start:l.pos]}
  l.start = l.pos
}

func (l *Lexer) next() rune {
  if len(l.input) <= l.pos {
    l.width = 0
    return EOF
  }

  r, size := utf8.DecodeRuneInString(l.input[l.pos:])
  l.width = size
  l.pos += l.width

  return r
}

func (l *Lexer) backup() {
  l.pos -= l.width
}

func (l *Lexer) ignore() {
  l.start = l.pos
}

func (l *Lexer) accept(valid string) bool {
  if strings.IndexRune(valid, l.next()) >= 0 {
    return true
  }

  l.backup()
  return false
}

func (l *Lexer) acceptRun(valid string) {
  for strings.IndexRune(valid, l.next()) >= 0 {
  }
  l.backup()
}

func lexWhiteSpace(l *Lexer) stateFn {
  return lexWhiteSpace
}
<commit_msg>define tokens for LispEx<commit_after>package lexer

import (
  "fmt"
  "strings"
  "unicode/utf8"
)

type TokenType int

const EOF = -1

const (
  TokenError TokenType = iota
  TokenEOF

  TokenOpenParen
  TokenCloseParen
  TokenOpenSquare
  TokenCloseSquare

  TokenStringLiteral
  TokenIntegerLiteral
  TokenFloatLiteral
  TokenBooleanLiteral
)

type Token struct {
  Type  TokenType
  Value string
}

type stateFn func(*Lexer) stateFn

type Lexer struct {
  name   string
  input  string
  state  stateFn
  start  int
  pos    int
  width  int
  tokens chan Token
}

func NewLexer(name, input string) *Lexer {
  l := &Lexer{
    name:   name,
    input:  input,
    tokens: make(chan Token),
  }
  go l.run()
  return l
}

func (l *Lexer) NextToken() Token {
  return <-l.tokens
}

func (l *Lexer) run() {
  for l.state = lexWhiteSpace; l.state != nil; {
    l.state = l.state(l)
  }
  close(l.tokens)
}

func (l *Lexer) emit(t TokenType) {
  l.tokens <- Token{t, l.input[l.start:l.pos]}
  l.start = l.pos
}

func (l *Lexer) next() rune {
  if len(l.input) <= l.pos {
    l.width = 0
    return EOF
  }

  r, size := utf8.DecodeRuneInString(l.input[l.pos:])
  l.width = size
  l.pos += l.width

  return r
}

func (l *Lexer) backup() {
  l.pos -= l.width
}

func (l *Lexer) ignore() {
  l.start = l.pos
}

func (l *Lexer) peek() rune {
  r := l.next()
  l.backup()
  return r
}

func (l *Lexer) accept(valid string) bool {
  if strings.IndexRune(valid, l.next()) >= 0 {
    return true
  }
  l.backup()
  return false
}

func (l *Lexer) acceptRun(valid string) {
  for strings.IndexRune(valid, l.next()) >= 0 {
  }
  l.backup()
}

func lexWhiteSpace(l *Lexer) stateFn {
  for r := l.next(); r == ' ' || r == '\t' || r == '\n'; l.next() {
    r = l.peek()
  }
  l.backup()
  l.ignore()

  switch r := l.next(); {
  case r == EOF:
    return lexEOF
  case r == '(':
    return lexOpenParen
  case r == ')':
    return lexCloseParen
  default:
    panic(fmt.Sprintf("Unexpected token: %q", r))
  }
}

func lexEOF(l *Lexer) stateFn {
  l.emit(TokenEOF)
  return nil
}

func lexOpenParen(l *Lexer) stateFn {
  l.emit(TokenOpenParen)
  return lexWhiteSpace
}

func lexCloseParen(l *Lexer) stateFn {
  l.emit(TokenCloseParen)
  return lexWhiteSpace
}
<|endoftext|>


<commit_before>package cwl

import (
	"fmt"
	"sort"
	"strings"

	"github.com/robertkrimen/otto"
)

// Input represents "CommandInputParameter".
// @see http://www.commonwl.org/v1.0/CommandLineTool.html#CommandInputParameter
type Input struct {
	ID             string          `json:"id"`
	Label          string          `json:"label"`
	Doc            string          `json:"doc"`
	Format         string          `json:"format"`
	Binding        *Binding        `json:"inputBinding"`
	Default        *InputDefault   `json:"default"`
	Types          []Type          `json:"type"`
	SecondaryFiles []SecondaryFile `json:"secondary_files"`
	// Input.Provided is what provided by parameters.(json|yaml)
	Provided *Provided `json:"-"`
	// Requirement ..
	RequiredType *Type
	Requirements Requirements
}

// New constructs "Input" struct from interface{}.
func (input Input) New(i interface{}) *Input {
	dest := &Input{}
	switch x := i.(type) {
	case map[string]interface{}:
		for key, v := range x {
			switch key {
			case "id":
				dest.ID = v.(string)
			case "type":
				dest.Types = Type{}.NewList(v)
			case "label":
				dest.Label = v.(string)
			case "doc":
				dest.Doc = v.(string)
			case "inputBinding":
				dest.Binding = Binding{}.New(v)
			case "default":
				dest.Default = InputDefault{}.New(v)
			case "format":
				dest.Format = v.(string)
			case "secondaryFiles":
				dest.SecondaryFiles = SecondaryFile{}.NewList(v)
			}
		}
		if dest.Default != nil {
			dest.Default.ID = dest.ID
		}
	case string:
		dest.Types = Type{}.NewList(x)
	case []interface{}:
		for _, v := range x {
			dest.Types = append(dest.Types, Type{}.New(v))
		}
	}
	return dest
}

// flatten
func (input *Input) flatten(typ Type, binding *Binding, prov interface{}) []string {
	flattened := []string{}
	switch typ.Type {
	case "int": // Array of Int
		tobejoined := []string{}
		for _, e := range input.Provided.Raw.([]interface{}) {
			tobejoined = append(tobejoined, fmt.Sprintf("%v", e))
		}
		flattened = append(flattened, strings.Join(tobejoined, input.Binding.Separator))
	case "File": // Array of Files
		switch arr := input.Provided.Raw.(type) {
		case []string:
			// TODO:
		case []interface{}:
			separated := []string{}
			for _, e := range arr {
				switch v := e.(type) {
				case map[interface{}]interface{}:
					if binding != nil && binding.Prefix != "" {
						separated = append(separated, binding.Prefix)
					}
					separated = append(separated, fmt.Sprintf("%v", v["location"]))
				default:
					// TODO:
				}
			}
			// In case it's Array of Files, unlike array of int,
			// it's NOT gonna be joined with .Binding.Separator.
			flattened = append(flattened, separated...)
		}
	case "string": // Array of string
		switch arr := prov.(type) {
		case []interface{}:
			separated := []string{}
			for _, e := range arr {
				switch v := e.(type) {
				case string:
					if binding != nil && binding.Prefix != "" {
						separated = append(separated, binding.Prefix)
					}
					separated = append(separated, fmt.Sprintf("%v", v))
				default:
					// TODO
				}
			}
			flattened = append(flattened, separated...)
		default:
			// TODO
		}
	case "array":
		switch arr := prov.(type) {
		case []interface{}:
			flattened = append(flattened, input.flatten(typ.Items[0], typ.Binding, arr[0])...)
		default:
			// TODO
		}
	default:
		if input.RequiredType != nil {
			flattened = append(flattened, input.flattenWithRequiredType()...)
		} else {
			// TODO
		}
	}
	return flattened
}

func (input *Input) flattenWithRequiredType() []string {
	flattened := []string{}
	key, needed := input.Types[0].NeedRequirement()
	if !needed {
		return flattened
	}
	if input.RequiredType.Name != key {
		return flattened
	}
	switch provided := input.Provided.Raw.(type) {
	case []interface{}:
		for _, e := range provided {
			switch v := e.(type) {
			case map[interface{}]interface{}:
				for _, field := range input.RequiredType.Fields {
					val, ok := v[field.Name]
					if !ok {
						continue
					}
					if field.Binding == nil {
						// Without thinking anything, just append it!!!
						flattened = append(flattened, fmt.Sprintf("%v", val))
					} else {
						if field.Binding.Prefix != "" {
							if field.Binding.Separate {
								flattened = append(flattened, field.Binding.Prefix, fmt.Sprintf("%v", val))
							} else {
								// TODO: Join if .Separator is given
								flattened = append(flattened, fmt.Sprintf("%s%v", field.Binding.Prefix, val))
							}
						} else {
							switch v2 := val.(type) {
							case []interface{}:
								for _, val2 := range v2 {
									switch v3 := val2.(type) {
									case []interface{}:
									case map[interface{}]interface{}:
										for _, types := range input.Requirements[0].SchemaDefRequirement.Types {
											val3array := []string{}
											var val3count int = 0
											sort.Sort(types.Fields)
											for _, fields := range types.Fields {
												for key3, val3 := range v3 {
													if fields.Name == key3 {
														for _, val3type := range fields.Types {
															if val3type.Type == "" {
															} else {
																switch val3type.Type {
																case "enum":
																	for _, symbol := range val3type.Symbols {
																		if symbol == val3 {
																			val3array = append(val3array, fmt.Sprintf("%v", val3))
																			val3count = val3count + 1
																		}
																	}
																case "int":
																	if fields.Binding.Prefix != "" {
																		val3array = append(val3array, fields.Binding.Prefix, fmt.Sprintf("%v", val3))
																		val3count = val3count + 1
																	} else {
																		val3array = append(val3array, fmt.Sprintf("%v", val3))
																		val3count = val3count + 1
																	}
																}
															}
														}
													}
												}
											}
											if len(v3) == val3count {
												flattened = append(flattened, val3array...)
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	return flattened
}

// Flatten ...
func (input *Input) Flatten() []string {
	if input.Provided == nil {
		// In case "input.Default == nil" should be validated by usage layer.
		if input.Default != nil {
			return input.Default.Flatten(input.Binding)
		} else {
			return []string{}
		}
	}
	flattened := []string{}
	if repr := input.Types[0]; len(input.Types) == 1 {
		switch repr.Type {
		case "array":
			flattened = append(flattened, input.flatten(repr.Items[0], repr.Binding, input.Provided.Raw)...)
		case "int":
			flattened = append(flattened, fmt.Sprintf("%v", input.Provided.Int))
		case "File":
			flattened = append(flattened, input.Provided.Entry.Location)
		default:
			flattened = append(flattened, fmt.Sprintf("%v", input.Provided))
		}
	}
	if input.Binding != nil && input.Binding.Prefix != "" {
		flattened = append([]string{input.Binding.Prefix}, flattened...)
	}

	return flattened
}

// Inputs represents "inputs" field in CWL.
type Inputs []*Input

// New constructs new "Inputs" struct.
func (ins Inputs) New(i interface{}) Inputs {
	dest := Inputs{}
	switch x := i.(type) {
	case []interface{}:
		for _, v := range x {
			dest = append(dest, Input{}.New(v))
		}
	case map[string]interface{}:
		for key, v := range x {
			input := Input{}.New(v)
			input.ID = key
			dest = append(dest, input)
		}
	}
	return dest
}

// Len for sorting.
func (ins Inputs) Len() int {
	return len(ins)
}

// Less for sorting.
func (ins Inputs) Less(i, j int) bool {
	prev, next := ins[i].Binding, ins[j].Binding
	switch [2]bool{prev == nil, next == nil} {
	case [2]bool{true, true}:
		return true
	case [2]bool{false, true}:
		return prev.Position < 0
	case [2]bool{true, false}:
		return next.Position > 0
	default:
		return prev.Position <= next.Position
	}
}

// Swap for sorting.
func (ins Inputs) Swap(i, j int) {
	ins[i], ins[j] = ins[j], ins[i]
}

// CreateVM ...
func (ins Inputs) CreateVM(srcdir string) (*otto.Otto, error) {
	self := map[string]map[string]interface{}{}
	for _, i := range ins {
		if i.Default != nil {
			self[i.ID] = map[string]interface{}{
				"path": i.Default.Entry.Location,
			}
		}
		if i.Provided != nil {
			self[i.ID] = map[string]interface{}{
				"path": i.Provided.Entry.Location,
			}
		}
	}

	// No contents to load
	if len(self) == 0 {
		return nil, nil
	}

	vm := otto.New()
	if err := vm.Set("inputs", self); err != nil {
		return nil, err
	}
	return vm, nil
}
<commit_msg>Change method name<commit_after>package cwl

import (
	"fmt"
	"sort"
	"strings"

	"github.com/robertkrimen/otto"
)

// Input represents "CommandInputParameter".
// @see http://www.commonwl.org/v1.0/CommandLineTool.html#CommandInputParameter
type Input struct {
	ID             string          `json:"id"`
	Label          string          `json:"label"`
	Doc            string          `json:"doc"`
	Format         string          `json:"format"`
	Binding        *Binding        `json:"inputBinding"`
	Default        *InputDefault   `json:"default"`
	Types          []Type          `json:"type"`
	SecondaryFiles []SecondaryFile `json:"secondary_files"`
	// Input.Provided is what provided by parameters.(json|yaml)
	Provided *Provided `json:"-"`
	// Requirement ..
	RequiredType *Type
	Requirements Requirements
}

// New constructs "Input" struct from interface{}.
func (input Input) New(i interface{}) *Input {
	dest := &Input{}
	switch x := i.(type) {
	case map[string]interface{}:
		for key, v := range x {
			switch key {
			case "id":
				dest.ID = v.(string)
			case "type":
				dest.Types = Type{}.NewList(v)
			case "label":
				dest.Label = v.(string)
			case "doc":
				dest.Doc = v.(string)
			case "inputBinding":
				dest.Binding = Binding{}.New(v)
			case "default":
				dest.Default = InputDefault{}.New(v)
			case "format":
				dest.Format = v.(string)
			case "secondaryFiles":
				dest.SecondaryFiles = SecondaryFile{}.NewList(v)
			}
		}
		if dest.Default != nil {
			dest.Default.ID = dest.ID
		}
	case string:
		dest.Types = Type{}.NewList(x)
	case []interface{}:
		for _, v := range x {
			dest.Types = append(dest.Types, Type{}.New(v))
		}
	}
	return dest
}

// flatten
func (input *Input) flatten(typ Type, binding *Binding, prov interface{}) []string {
	flattened := []string{}
	switch typ.Type {
	case "int": // Array of Int
		tobejoined := []string{}
		for _, e := range input.Provided.Raw.([]interface{}) {
			tobejoined = append(tobejoined, fmt.Sprintf("%v", e))
		}
		flattened = append(flattened, strings.Join(tobejoined, input.Binding.Separator))
	case "File": // Array of Files
		switch arr := input.Provided.Raw.(type) {
		case []string:
			// TODO:
		case []interface{}:
			separated := []string{}
			for _, e := range arr {
				switch v := e.(type) {
				case map[interface{}]interface{}:
					if binding != nil && binding.Prefix != "" {
						separated = append(separated, binding.Prefix)
					}
					separated = append(separated, fmt.Sprintf("%v", v["location"]))
				default:
					// TODO:
				}
			}
			// In case it's Array of Files, unlike array of int,
			// it's NOT gonna be joined with .Binding.Separator.
			flattened = append(flattened, separated...)
		}
	case "string": // Array of string
		switch arr := prov.(type) {
		case []interface{}:
			separated := []string{}
			for _, e := range arr {
				switch v := e.(type) {
				case string:
					if binding != nil && binding.Prefix != "" {
						separated = append(separated, binding.Prefix)
					}
					separated = append(separated, fmt.Sprintf("%v", v))
				default:
					// TODO
				}
			}
			flattened = append(flattened, separated...)
		default:
			// TODO
		}
	case "array":
		switch arr := prov.(type) {
		case []interface{}:
			flattened = append(flattened, input.flatten(typ.Items[0], typ.Binding, arr[0])...)
		default:
			// TODO
		}
	default:
		if input.RequiredType != nil {
			flattened = append(flattened, input.flattenWithRequiredType()...)
		} else {
			// TODO
		}
	}
	return flattened
}

func (input *Input) flattenWithRequiredType() []string {
	flattened := []string{}
	key, needed := input.Types[0].NeedRequirement()
	if !needed {
		return flattened
	}
	if input.RequiredType.Name != key {
		return flattened
	}
	switch provided := input.Provided.Raw.(type) {
	case []interface{}:
		for _, e := range provided {
			switch v := e.(type) {
			case map[interface{}]interface{}:
				for _, field := range input.RequiredType.Fields {
					val, ok := v[field.Name]
					if !ok {
						continue
					}
					if field.Binding == nil {
						// Without thinking anything, just append it!!!
						flattened = append(flattened, fmt.Sprintf("%v", val))
					} else {
						if field.Binding.Prefix != "" {
							if field.Binding.Separate {
								flattened = append(flattened, field.Binding.Prefix, fmt.Sprintf("%v", val))
							} else {
								// TODO: Join if .Separator is given
								flattened = append(flattened, fmt.Sprintf("%s%v", field.Binding.Prefix, val))
							}
						} else {
							switch v2 := val.(type) {
							case []interface{}:
								for _, val2 := range v2 {
									switch v3 := val2.(type) {
									case []interface{}:
									case map[interface{}]interface{}:
										for _, types := range input.Requirements[0].SchemaDefRequirement.Types {
											val3array := []string{}
											var val3count int = 0
											sort.Sort(types.Fields)
											for _, fields := range types.Fields {
												for key3, val3 := range v3 {
													if fields.Name == key3 {
														for _, val3type := range fields.Types {
															if val3type.Type == "" {
															} else {
																switch val3type.Type {
																case "enum":
																	for _, symbol := range val3type.Symbols {
																		if symbol == val3 {
																			val3array = append(val3array, fmt.Sprintf("%v", val3))
																			val3count = val3count + 1
																		}
																	}
																case "int":
																	if fields.Binding.Prefix != "" {
																		val3array = append(val3array, fields.Binding.Prefix, fmt.Sprintf("%v", val3))
																		val3count = val3count + 1
																	} else {
																		val3array = append(val3array, fmt.Sprintf("%v", val3))
																		val3count = val3count + 1
																	}
																}
															}
														}
													}
												}
											}
											if len(v3) == val3count {
												flattened = append(flattened, val3array...)
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	return flattened
}

// Flatten ...
func (input *Input) Flatten() []string {
	if input.Provided == nil {
		// In case "input.Default == nil" should be validated by usage layer.
		if input.Default != nil {
			return input.Default.Flatten(input.Binding)
		} else {
			return []string{}
		}
	}
	flattened := []string{}
	if repr := input.Types[0]; len(input.Types) == 1 {
		switch repr.Type {
		case "array":
			flattened = append(flattened, input.flatten(repr.Items[0], repr.Binding, input.Provided.Raw)...)
		case "int":
			flattened = append(flattened, fmt.Sprintf("%v", input.Provided.Int))
		case "File":
			flattened = append(flattened, input.Provided.Entry.Location)
		default:
			flattened = append(flattened, fmt.Sprintf("%v", input.Provided))
		}
	}
	if input.Binding != nil && input.Binding.Prefix != "" {
		flattened = append([]string{input.Binding.Prefix}, flattened...)
	}

	return flattened
}

// Inputs represents "inputs" field in CWL.
type Inputs []*Input

// New constructs new "Inputs" struct.
func (ins Inputs) New(i interface{}) Inputs {
	dest := Inputs{}
	switch x := i.(type) {
	case []interface{}:
		for _, v := range x {
			dest = append(dest, Input{}.New(v))
		}
	case map[string]interface{}:
		for key, v := range x {
			input := Input{}.New(v)
			input.ID = key
			dest = append(dest, input)
		}
	}
	return dest
}

// Len for sorting.
func (ins Inputs) Len() int {
	return len(ins)
}

// Less for sorting.
func (ins Inputs) Less(i, j int) bool {
	prev, next := ins[i].Binding, ins[j].Binding
	switch [2]bool{prev == nil, next == nil} {
	case [2]bool{true, true}:
		return true
	case [2]bool{false, true}:
		return prev.Position < 0
	case [2]bool{true, false}:
		return next.Position > 0
	default:
		return prev.Position <= next.Position
	}
}

// Swap for sorting.
func (ins Inputs) Swap(i, j int) {
	ins[i], ins[j] = ins[j], ins[i]
}

// CreateVM ...
func (ins Inputs) ToJavaScriptVM(srcdir string) (*otto.Otto, error) {
	self := map[string]map[string]interface{}{}
	for _, i := range ins {
		if i.Default != nil {
			self[i.ID] = map[string]interface{}{
				"path": i.Default.Entry.Location,
			}
		}
		if i.Provided != nil {
			self[i.ID] = map[string]interface{}{
				"path": i.Provided.Entry.Location,
			}
		}
	}

	// No contents to load
	if len(self) == 0 {
		return nil, nil
	}

	vm := otto.New()
	if err := vm.Set("inputs", self); err != nil {
		return nil, err
	}
	return vm, nil
}
<|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.
 */

// qualifiedname.go
package utils

import (
	"encoding/json"
	"github.com/apache/incubator-openwhisk-client-go/whisk"
	"github.com/apache/incubator-openwhisk-wskdeploy/wski18n"
	"github.com/apache/incubator-openwhisk-wskdeploy/wskprint"
	"strings"
)

var LocalLicenseRecords = map[string][]string{
	"APACHE": {"1.0", "1.1", "2.0"},
	"LGPL":   {"2.0", "2.1", "3.0"},
	"GPL":    {"1.0", "2.0", "3.0"},
	"MPL":    {"1.0", "1.1", "2.0", "2.0-no-copyleft-exception"},
	"BSD":    {"2-Clause", "2-Clause-FreeBSD", "2-Clause-NetBSD", "3-Clause", "3-Clause-Clear", "3-Clause-No-Nuclear-License", "3-Clause-No-Nuclear-License-2014", "3-Clause-No-Nuclear-Warranty", "3-Clause-Attribution", "4-Clause", "Protection", "Source-Code", "4-Clause-UC", "3-Clause-LBNL"},
	"0BSD":   {""},
	"GFDL":   {"1.0", "1.2", "1.3"},
	"AGPL":   {"3.0"},
	"MIT":    {"", "feh", "enna", "advertising", "CMU"},
	"AFL":    {"1.1", "1.2", "2.0", "2.1", "3.0"},
	"APSL":   {"1.0", "1.1", "1.2", "2.0"},
	"EPL":    {"1.0"},
	"OSL":    {"1.0", "1.1", "2.0", "2.1", "3.0"},
	"PHP":    {"3.0", "3.01"},
}

var RemoteLicenseURL = "https://raw.githubusercontent.com/spdx/license-list-data/master/json/licenses.json"

type LicenseJSON struct {
	Description string        `json:"licenseListVersion"`
	Licenses    []LicenseItem `json:"licenses"`
	ReleaseDate string        `json:"releaseDate"`
}

type LicenseItem struct {
	Name      string `json:"name"`
	LicenseID string `json:"licenseId"`
}

var license_json = LicenseJSON{}

//Check if the license is valid
//Check local data record at first
//Then check remote json data
func CheckLicense(license string) bool {
	// TODO(#673) Strict flag should cause an error to be generatd
	if !LicenseLocalValidation(license) && !LicenseRemoteValidation(license) {
		warningString := wski18n.T(
			wski18n.ID_WARN_KEYVALUE_INVALID,
			map[string]interface{}{
				wski18n.KEY_KEY: license})
		wskprint.PrintlnOpenWhiskWarning(warningString)
		return false
	}
	return true
}

// Check if the license is in local license record
// If it is, return ture
// If it is not, return false
func LicenseLocalValidation(license string) bool {
	license_upper := strings.ToUpper(license) //change it to upper case
	parts := strings.SplitN(license_upper, "-", 2)
	license_type := parts[0]
	license_version := ""
	if len(parts) > 1 {
		license_version = parts[1]
	}

	version_list := LocalLicenseRecords[license_type]
	if version_list == nil {
		return false
	} else {
		for _, version := range LocalLicenseRecords[license_type] {
			if license_version == strings.ToUpper(version) {
				return true
			}
		}
		return false
	}
}

//Check if license is one of validate license in
//https://github.com/spdx/license-list-data/blob/master/json/licenses.json
// If it is, return ture
// If it is not, return false
func LicenseRemoteValidation(license string) bool {
	license_upper := strings.ToUpper(license) //change it to upper case

	if len(license_json.Licenses) == 0 {
		json_data, err := Read(RemoteLicenseURL)
		if err != nil {
			// TODO() i18n
			errString := wski18n.T("Failed to get the remote license json.\n")
			whisk.Debug(whisk.DbgError, errString)
			return false
		}

		//parse json
		err = json.Unmarshal(json_data, &license_json)
		if err != nil || len(license_json.Licenses) == 0 {
			// TODO() i18n
			errString := wski18n.T("Failed to parse the remote license json.\n")
			whisk.Debug(whisk.DbgError, errString)
			return false
		}
	}

	//check license
	for _, licenseobj := range license_json.Licenses {
		if strings.ToUpper(licenseobj.LicenseID) == license_upper {
			return true
		}
	}
	return false
}

//if valid or nil, true
//or else, false
func LimitsTimeoutValidation(timeout *int) bool {
	if timeout == nil {
		return true
	}
	if *timeout < 100 || *timeout > 300000 {
		wskprint.PrintlnOpenWhiskWarning(wski18n.T(wski18n.ID_WARN_LIMITS_TIMEOUT))
		return false
	}
	return true
}

//if valid or nil, true
//or else, false
func LimitsMemoryValidation(memory *int) bool {
	if memory == nil {
		return true
	}
	if *memory < 128 || *memory > 512 {
		wskprint.PrintlnOpenWhiskWarning(wski18n.T(wski18n.ID_WARN_LIMITS_MEMORY_SIZE))
		return false
	}
	return true
}

//if valid or nil, true
//or else, false
func LimitsLogsizeValidation(logsize *int) bool {
	if logsize == nil {
		return true
	}
	if *logsize < 0 || *logsize > 10 {
		wskprint.PrintlnOpenWhiskWarning(wski18n.T(wski18n.ID_WARN_LIMITS_LOG_SIZE))
		return false
	}
	return true
}

func NotSupportLimits(value *int, name string) {
	if value != nil {
		warningString := wski18n.T(
			wski18n.ID_WARN_LIMIT_UNCHANGEABLE_X_name_X,
			map[string]interface{}{wski18n.KEY_NAME: name})
		wskprint.PrintlnOpenWhiskWarning(warningString)
	}
}
<commit_msg>raise memorySize limit to 2048MB (#1034)<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.
 */

// qualifiedname.go
package utils

import (
	"encoding/json"
	"github.com/apache/incubator-openwhisk-client-go/whisk"
	"github.com/apache/incubator-openwhisk-wskdeploy/wski18n"
	"github.com/apache/incubator-openwhisk-wskdeploy/wskprint"
	"strings"
)

var LocalLicenseRecords = map[string][]string{
	"APACHE": {"1.0", "1.1", "2.0"},
	"LGPL":   {"2.0", "2.1", "3.0"},
	"GPL":    {"1.0", "2.0", "3.0"},
	"MPL":    {"1.0", "1.1", "2.0", "2.0-no-copyleft-exception"},
	"BSD":    {"2-Clause", "2-Clause-FreeBSD", "2-Clause-NetBSD", "3-Clause", "3-Clause-Clear", "3-Clause-No-Nuclear-License", "3-Clause-No-Nuclear-License-2014", "3-Clause-No-Nuclear-Warranty", "3-Clause-Attribution", "4-Clause", "Protection", "Source-Code", "4-Clause-UC", "3-Clause-LBNL"},
	"0BSD":   {""},
	"GFDL":   {"1.0", "1.2", "1.3"},
	"AGPL":   {"3.0"},
	"MIT":    {"", "feh", "enna", "advertising", "CMU"},
	"AFL":    {"1.1", "1.2", "2.0", "2.1", "3.0"},
	"APSL":   {"1.0", "1.1", "1.2", "2.0"},
	"EPL":    {"1.0"},
	"OSL":    {"1.0", "1.1", "2.0", "2.1", "3.0"},
	"PHP":    {"3.0", "3.01"},
}

var RemoteLicenseURL = "https://raw.githubusercontent.com/spdx/license-list-data/master/json/licenses.json"

type LicenseJSON struct {
	Description string        `json:"licenseListVersion"`
	Licenses    []LicenseItem `json:"licenses"`
	ReleaseDate string        `json:"releaseDate"`
}

type LicenseItem struct {
	Name      string `json:"name"`
	LicenseID string `json:"licenseId"`
}

var license_json = LicenseJSON{}

//Check if the license is valid
//Check local data record at first
//Then check remote json data
func CheckLicense(license string) bool {
	// TODO(#673) Strict flag should cause an error to be generatd
	if !LicenseLocalValidation(license) && !LicenseRemoteValidation(license) {
		warningString := wski18n.T(
			wski18n.ID_WARN_KEYVALUE_INVALID,
			map[string]interface{}{
				wski18n.KEY_KEY: license})
		wskprint.PrintlnOpenWhiskWarning(warningString)
		return false
	}
	return true
}

// Check if the license is in local license record
// If it is, return ture
// If it is not, return false
func LicenseLocalValidation(license string) bool {
	license_upper := strings.ToUpper(license) //change it to upper case
	parts := strings.SplitN(license_upper, "-", 2)
	license_type := parts[0]
	license_version := ""
	if len(parts) > 1 {
		license_version = parts[1]
	}

	version_list := LocalLicenseRecords[license_type]
	if version_list == nil {
		return false
	} else {
		for _, version := range LocalLicenseRecords[license_type] {
			if license_version == strings.ToUpper(version) {
				return true
			}
		}
		return false
	}
}

//Check if license is one of validate license in
//https://github.com/spdx/license-list-data/blob/master/json/licenses.json
// If it is, return ture
// If it is not, return false
func LicenseRemoteValidation(license string) bool {
	license_upper := strings.ToUpper(license) //change it to upper case

	if len(license_json.Licenses) == 0 {
		json_data, err := Read(RemoteLicenseURL)
		if err != nil {
			// TODO() i18n
			errString := wski18n.T("Failed to get the remote license json.\n")
			whisk.Debug(whisk.DbgError, errString)
			return false
		}

		//parse json
		err = json.Unmarshal(json_data, &license_json)
		if err != nil || len(license_json.Licenses) == 0 {
			// TODO() i18n
			errString := wski18n.T("Failed to parse the remote license json.\n")
			whisk.Debug(whisk.DbgError, errString)
			return false
		}
	}

	//check license
	for _, licenseobj := range license_json.Licenses {
		if strings.ToUpper(licenseobj.LicenseID) == license_upper {
			return true
		}
	}
	return false
}

//if valid or nil, true
//or else, false
func LimitsTimeoutValidation(timeout *int) bool {
	if timeout == nil {
		return true
	}
	if *timeout < 100 || *timeout > 300000 {
		wskprint.PrintlnOpenWhiskWarning(wski18n.T(wski18n.ID_WARN_LIMITS_TIMEOUT))
		return false
	}
	return true
}

//if valid or nil, true
//or else, false
func LimitsMemoryValidation(memory *int) bool {
	if memory == nil {
		return true
	}
	if *memory < 128 || *memory > 2048 {
		wskprint.PrintlnOpenWhiskWarning(wski18n.T(wski18n.ID_WARN_LIMITS_MEMORY_SIZE))
		return false
	}
	return true
}

//if valid or nil, true
//or else, false
func LimitsLogsizeValidation(logsize *int) bool {
	if logsize == nil {
		return true
	}
	if *logsize < 0 || *logsize > 10 {
		wskprint.PrintlnOpenWhiskWarning(wski18n.T(wski18n.ID_WARN_LIMITS_LOG_SIZE))
		return false
	}
	return true
}

func NotSupportLimits(value *int, name string) {
	if value != nil {
		warningString := wski18n.T(
			wski18n.ID_WARN_LIMIT_UNCHANGEABLE_X_name_X,
			map[string]interface{}{wski18n.KEY_NAME: name})
		wskprint.PrintlnOpenWhiskWarning(warningString)
	}
}
<|endoftext|>


<commit_before>package fire

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/kr/pretty"
	"github.com/ory-am/fosite"
	"github.com/ory-am/fosite/handler/core"
	"github.com/ory-am/fosite/handler/core/client"
	"github.com/ory-am/fosite/handler/core/implicit"
	"github.com/ory-am/fosite/handler/core/owner"
	"github.com/ory-am/fosite/handler/core/strategy"
	"github.com/ory-am/fosite/token/hmac"
	"gopkg.in/mgo.v2"
)

type AccessToken struct {
	Base         `bson:",inline" fire:"access-token:access-tokens:access_tokens"`
	Signature    string                `json:"-" valid:"-"`
	PlainRequest *fosite.Request       `json:"-" valid:"-" bson:"plain_request"`
	PlainClient  *fosite.DefaultClient `json:"-" valid:"-" bson:"plain_client"`
}

type Authenticator struct {
	storage *authenticatorStorage

	strategy     *strategy.HMACSHAStrategy
	handleHelper *core.HandleHelper
	fosite       *fosite.Fosite
}

var accessTokenModel *AccessToken

func init() {
	accessTokenModel = &AccessToken{}
	Init(accessTokenModel)
}

func NewAuthenticator(db *mgo.Database, ownerModel, clientModel Model, secret string) *Authenticator {
	// initialize models
	Init(ownerModel)
	Init(clientModel)

	// extract attributes from owner
	ownerIdentifiable := ownerModel.getBase().attributesByTag("identifiable")
	if len(ownerIdentifiable) != 1 {
		panic("expected to find exactly one 'identifiable' tag on model")
	}
	ownerVerifiable := ownerModel.getBase().attributesByTag("verifiable")
	if len(ownerVerifiable) != 1 {
		panic("expected to find exactly one 'verifiable' tag on model")
	}

	// extract attributes from client
	clientIdentifiable := clientModel.getBase().attributesByTag("identifiable")
	if len(clientIdentifiable) != 1 {
		panic("expected to find exactly one 'identifiable' tag on model")
	}
	clientVerifiable := clientModel.getBase().attributesByTag("verifiable")
	if len(clientVerifiable) != 1 {
		panic("expected to find exactly one 'verifiable' tag on model")
	}

	// create storage
	s := &authenticatorStorage{
		db:               db,
		ownerModel:       ownerModel,
		ownerIDAttr:      ownerIdentifiable[0],
		ownerSecretAttr:  ownerVerifiable[0],
		clientModel:      clientModel,
		clientIDAttr:     clientIdentifiable[0],
		clientSecretAttr: clientVerifiable[0],
	}

	// set the default token lifespan to one hour
	tokenLifespan := time.Hour

	// create a new token generation strategy
	strategy := &strategy.HMACSHAStrategy{
		Enigma: &hmac.HMACStrategy{
			GlobalSecret: []byte(secret),
		},
		AccessTokenLifespan:   tokenLifespan,
		AuthorizeCodeLifespan: tokenLifespan,
	}

	// instantiate a new fosite instance
	f := fosite.NewFosite(s)

	// set mandatory scope
	f.MandatoryScope = "fire"

	// this little helper is used by some of the handlers later
	handleHelper := &core.HandleHelper{
		AccessTokenStrategy: strategy,
		AccessTokenStorage:  s,
		AccessTokenLifespan: tokenLifespan,
	}

	// add a request validator for access tokens to fosite
	f.AuthorizedRequestValidators.Append(&core.CoreValidator{
		AccessTokenStrategy: strategy,
		AccessTokenStorage:  s,
	})

	return &Authenticator{
		storage:      s,
		fosite:       f,
		handleHelper: handleHelper,
		strategy:     strategy,
	}
}

// EnablePasswordGrant enables the usage of the OAuth 2.0 Resource Owner Password
// Credentials Grant.
func (a *Authenticator) EnablePasswordGrant() {
	// create handler
	passwordHandler := &owner.ResourceOwnerPasswordCredentialsGrantHandler{
		HandleHelper:                                 a.handleHelper,
		ResourceOwnerPasswordCredentialsGrantStorage: a.storage,
	}

	// add handler to fosite
	a.fosite.TokenEndpointHandlers.Append(passwordHandler)

	// TODO: Enable refresh token.
	// this handler is responsible for the refresh token grant
	//refreshHandler := &refresh.RefreshTokenGrantHandler{
	//	AccessTokenStrategy:      strategy,
	//	RefreshTokenStrategy:     strategy,
	//	RefreshTokenGrantStorage: s,
	//	AccessTokenLifespan:      accessTokenLifespan,
	//}

	// add handler to fosite
	//f.TokenEndpointHandlers.Append(refreshHandler)
}

// EnableCredentialsGrant enables the usage of the OAuth 2.0 Client Credentials Grant.
func (a *Authenticator) EnableCredentialsGrant() {
	// create handler
	credentialsHandler := &client.ClientCredentialsGrantHandler{
		HandleHelper: a.handleHelper,
	}

	// add handler to fosite
	a.fosite.TokenEndpointHandlers.Append(credentialsHandler)
}

// EnableImplicitGrant enables the usage of the OAuth 2.0 Implicit Grant.
func (a *Authenticator) EnableImplicitGrant() {
	// This handler is responsible for the implicit flow. The implicit flow does not return an authorize code
	// but instead returns the access token directly via an url fragment.
	implicitHandler := &implicit.AuthorizeImplicitGrantTypeHandler{
		AccessTokenStrategy: a.handleHelper.AccessTokenStrategy,
		AccessTokenStorage:  a.handleHelper.AccessTokenStorage,
		AccessTokenLifespan: a.handleHelper.AccessTokenLifespan,
	}
	a.fosite.AuthorizeEndpointHandlers.Append(implicitHandler)
}

// HashPassword returns an Authenticator compatible hash of the password.
func (a *Authenticator) HashPassword(password string) ([]byte, error) {
	return a.fosite.Hasher.Hash([]byte(password))
}

// MustHashPassword is the same as HashPassword except that it raises and error
// when the hashing failed.
func (a *Authenticator) MustHashPassword(password string) []byte {
	bytes, err := a.HashPassword(password)
	if err != nil {
		panic(err)
	}

	return bytes
}

func (a *Authenticator) Register(prefix string, router gin.IRouter) {
	router.POST(prefix+"/token", a.tokenEndpoint)
	router.GET(prefix+"/authorize", a.authEndpoint)
	router.POST(prefix+"/authorize", a.authEndpoint)
}

func (a *Authenticator) Authorizer() Callback {
	return func(ctx *Context) (error, error) {
		// prepare fosite
		f := fosite.NewContext()
		session := &strategy.HMACSession{}

		// validate request
		_, err := a.fosite.ValidateRequestAuthorization(f, ctx.GinContext.Request, session, "fire")
		if err != nil {
			return err, nil
		}

		return nil, nil
	}
}

func (a *Authenticator) tokenEndpoint(ctx *gin.Context) {
	// create new context
	f := fosite.NewContext()

	// create new session
	s := make(map[string]interface{})

	// obtain access request
	req, err := a.fosite.NewAccessRequest(f, ctx.Request, s)
	if err != nil {
		pretty.Println(err)
		a.fosite.WriteAccessError(ctx.Writer, req, err)
		return
	}

	// grant the mandatory scope
	req.GrantScope("fire")

	// obtain access response
	res, err := a.fosite.NewAccessResponse(f, ctx.Request, req)
	if err != nil {
		pretty.Println(err)
		a.fosite.WriteAccessError(ctx.Writer, req, err)
		return
	}

	// write response
	a.fosite.WriteAccessResponse(ctx.Writer, req, res)
}

func (a *Authenticator) authEndpoint(ctx *gin.Context) {
	// create new context
	f := fosite.NewContext()

	// Let's create an AuthorizeRequest object!
	// It will analyze the request and extract important information like scopes, response type and others.
	req, err := a.fosite.NewAuthorizeRequest(f, ctx.Request)
	if err != nil {
		fmt.Printf("Error occurred in NewAuthorizeRequest: %s\n", err)
		a.fosite.WriteAuthorizeError(ctx.Writer, req, err)
		return
	}
	// You have now access to authorizeRequest, Code ResponseTypes, Scopes ...

	// Normally, this would be the place where you would check if the user is logged in and gives his consent.
	// We're simplifying things and just checking if the request includes a valid username and password
	if ctx.Request.Form.Get("username") != "peter" {
		ctx.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
		ctx.Writer.Write([]byte(`<h1>Login page</h1>`))
		ctx.Writer.Write([]byte(`

Howdy! This is the log in page. For this example, it is enough to supply the username.

			<form method="post">
				<input type="text" name="username" /> try peter

				<input type="submit">
			</form>
		`))
		return
	}

	// we allow issuing of refresh tokens per default
	if req.GetScopes().Has("offline") {
		req.GrantScope("offline")
	}

	// Now that the user is authorized, we set up a session:
	session := &strategy.HMACSession{}

	// Now we need to get a response. This is the place where the AuthorizeEndpointHandlers kick in and start processing the request.
	// NewAuthorizeResponse is capable of running multiple response type handlers which in turn enables this library
	// to support open id connect.
	res, err := a.fosite.NewAuthorizeResponse(ctx, ctx.Request, req, session)

	// Catch any errors, e.g.:
	// * unknown client
	// * invalid redirect
	// * ...
	if err != nil {
		fmt.Printf("Error occurred in NewAuthorizeResponse: %s", err)
		a.fosite.WriteAuthorizeError(ctx.Writer, req, err)
		return
	}

	// Last but not least, send the response!
	a.fosite.WriteAuthorizeResponse(ctx.Writer, req, res)
}
<commit_msg>cleanup<commit_after>package fire

import (
	"time"

	"github.com/gin-gonic/gin"
	"github.com/kr/pretty"
	"github.com/ory-am/fosite"
	"github.com/ory-am/fosite/handler/core"
	"github.com/ory-am/fosite/handler/core/client"
	"github.com/ory-am/fosite/handler/core/implicit"
	"github.com/ory-am/fosite/handler/core/owner"
	"github.com/ory-am/fosite/handler/core/strategy"
	"github.com/ory-am/fosite/token/hmac"
	"gopkg.in/mgo.v2"
)

type AccessToken struct {
	Base         `bson:",inline" fire:"access-token:access-tokens:access_tokens"`
	Signature    string                `json:"-" valid:"-"`
	PlainRequest *fosite.Request       `json:"-" valid:"-" bson:"plain_request"`
	PlainClient  *fosite.DefaultClient `json:"-" valid:"-" bson:"plain_client"`
}

type Authenticator struct {
	storage *authenticatorStorage

	strategy     *strategy.HMACSHAStrategy
	handleHelper *core.HandleHelper
	fosite       *fosite.Fosite
}

var accessTokenModel *AccessToken

func init() {
	accessTokenModel = &AccessToken{}
	Init(accessTokenModel)
}

func NewAuthenticator(db *mgo.Database, ownerModel, clientModel Model, secret string) *Authenticator {
	// initialize models
	Init(ownerModel)
	Init(clientModel)

	// extract attributes from owner
	ownerIdentifiable := ownerModel.getBase().attributesByTag("identifiable")
	if len(ownerIdentifiable) != 1 {
		panic("expected to find exactly one 'identifiable' tag on model")
	}
	ownerVerifiable := ownerModel.getBase().attributesByTag("verifiable")
	if len(ownerVerifiable) != 1 {
		panic("expected to find exactly one 'verifiable' tag on model")
	}

	// extract attributes from client
	clientIdentifiable := clientModel.getBase().attributesByTag("identifiable")
	if len(clientIdentifiable) != 1 {
		panic("expected to find exactly one 'identifiable' tag on model")
	}
	clientVerifiable := clientModel.getBase().attributesByTag("verifiable")
	if len(clientVerifiable) != 1 {
		panic("expected to find exactly one 'verifiable' tag on model")
	}

	// create storage
	s := &authenticatorStorage{
		db:               db,
		ownerModel:       ownerModel,
		ownerIDAttr:      ownerIdentifiable[0],
		ownerSecretAttr:  ownerVerifiable[0],
		clientModel:      clientModel,
		clientIDAttr:     clientIdentifiable[0],
		clientSecretAttr: clientVerifiable[0],
	}

	// set the default token lifespan to one hour
	tokenLifespan := time.Hour

	// create a new token generation strategy
	strategy := &strategy.HMACSHAStrategy{
		Enigma: &hmac.HMACStrategy{
			GlobalSecret: []byte(secret),
		},
		AccessTokenLifespan:   tokenLifespan,
		AuthorizeCodeLifespan: tokenLifespan,
	}

	// instantiate a new fosite instance
	f := fosite.NewFosite(s)

	// set mandatory scope
	f.MandatoryScope = "fire"

	// this little helper is used by some of the handlers later
	handleHelper := &core.HandleHelper{
		AccessTokenStrategy: strategy,
		AccessTokenStorage:  s,
		AccessTokenLifespan: tokenLifespan,
	}

	// add a request validator for access tokens to fosite
	f.AuthorizedRequestValidators.Append(&core.CoreValidator{
		AccessTokenStrategy: strategy,
		AccessTokenStorage:  s,
	})

	return &Authenticator{
		storage:      s,
		fosite:       f,
		handleHelper: handleHelper,
		strategy:     strategy,
	}
}

// EnablePasswordGrant enables the usage of the OAuth 2.0 Resource Owner Password
// Credentials Grant.
func (a *Authenticator) EnablePasswordGrant() {
	// create handler
	passwordHandler := &owner.ResourceOwnerPasswordCredentialsGrantHandler{
		HandleHelper:                                 a.handleHelper,
		ResourceOwnerPasswordCredentialsGrantStorage: a.storage,
	}

	// add handler to fosite
	a.fosite.TokenEndpointHandlers.Append(passwordHandler)

	// TODO: Enable refresh token.
	// this handler is responsible for the refresh token grant
	//refreshHandler := &refresh.RefreshTokenGrantHandler{
	//	AccessTokenStrategy:      strategy,
	//	RefreshTokenStrategy:     strategy,
	//	RefreshTokenGrantStorage: s,
	//	AccessTokenLifespan:      accessTokenLifespan,
	//}

	// add handler to fosite
	//f.TokenEndpointHandlers.Append(refreshHandler)
}

// EnableCredentialsGrant enables the usage of the OAuth 2.0 Client Credentials Grant.
func (a *Authenticator) EnableCredentialsGrant() {
	// create handler
	credentialsHandler := &client.ClientCredentialsGrantHandler{
		HandleHelper: a.handleHelper,
	}

	// add handler to fosite
	a.fosite.TokenEndpointHandlers.Append(credentialsHandler)
}

// EnableImplicitGrant enables the usage of the OAuth 2.0 Implicit Grant.
func (a *Authenticator) EnableImplicitGrant() {
	// This handler is responsible for the implicit flow. The implicit flow does not return an authorize code
	// but instead returns the access token directly via an url fragment.
	implicitHandler := &implicit.AuthorizeImplicitGrantTypeHandler{
		AccessTokenStrategy: a.handleHelper.AccessTokenStrategy,
		AccessTokenStorage:  a.handleHelper.AccessTokenStorage,
		AccessTokenLifespan: a.handleHelper.AccessTokenLifespan,
	}
	a.fosite.AuthorizeEndpointHandlers.Append(implicitHandler)
}

// HashPassword returns an Authenticator compatible hash of the password.
func (a *Authenticator) HashPassword(password string) ([]byte, error) {
	return a.fosite.Hasher.Hash([]byte(password))
}

// MustHashPassword is the same as HashPassword except that it raises and error
// when the hashing failed.
func (a *Authenticator) MustHashPassword(password string) []byte {
	bytes, err := a.HashPassword(password)
	if err != nil {
		panic(err)
	}

	return bytes
}

func (a *Authenticator) Register(prefix string, router gin.IRouter) {
	router.POST(prefix+"/token", a.tokenEndpoint)
	router.GET(prefix+"/authorize", a.authEndpoint)
	router.POST(prefix+"/authorize", a.authEndpoint)
}

func (a *Authenticator) Authorizer() Callback {
	return func(ctx *Context) (error, error) {
		// prepare fosite
		f := fosite.NewContext()
		session := &strategy.HMACSession{}

		// validate request
		_, err := a.fosite.ValidateRequestAuthorization(f, ctx.GinContext.Request, session, "fire")
		if err != nil {
			return err, nil
		}

		return nil, nil
	}
}

func (a *Authenticator) tokenEndpoint(ctx *gin.Context) {
	// create new context
	f := fosite.NewContext()

	// create new session
	s := &strategy.HMACSession{}

	// obtain access request
	req, err := a.fosite.NewAccessRequest(f, ctx.Request, s)
	if err != nil {
		pretty.Println(err)
		a.fosite.WriteAccessError(ctx.Writer, req, err)
		return
	}

	// grant the mandatory scope
	if req.GetScopes().Has("fire") {
		req.GrantScope("fire")
	}

	// obtain access response
	res, err := a.fosite.NewAccessResponse(f, ctx.Request, req)
	if err != nil {
		pretty.Println(err)
		a.fosite.WriteAccessError(ctx.Writer, req, err)
		return
	}

	// write response
	a.fosite.WriteAccessResponse(ctx.Writer, req, res)
}

func (a *Authenticator) authEndpoint(ctx *gin.Context) {
	// create new context
	f := fosite.NewContext()

	// obtain authorize request
	req, err := a.fosite.NewAuthorizeRequest(f, ctx.Request)
	if err != nil {
		pretty.Println(err)
		a.fosite.WriteAuthorizeError(ctx.Writer, req, err)
		return
	}
	// You have now access to authorizeRequest, Code ResponseTypes, Scopes ...

	// Normally, this would be the place where you would check if the user is logged in and gives his consent.
	// We're simplifying things and just checking if the request includes a valid username and password
	if ctx.Request.Form.Get("username") != "peter" {
		ctx.Writer.Header().Set("Content-Type", "text/html; charset=utf-8")
		ctx.Writer.Write([]byte(`<h1>Login page</h1>`))
		ctx.Writer.Write([]byte(`

Howdy! This is the log in page. For this example, it is enough to supply the username.

			<form method="post">
				<input type="text" name="username" /> try peter

				<input type="submit">
			</form>
		`))
		return
	}

	// we allow issuing of refresh tokens per default
	if req.GetScopes().Has("offline") {
		req.GrantScope("offline")
	}

	// create new session
	s := &strategy.HMACSession{}

	// obtain authorize response
	res, err := a.fosite.NewAuthorizeResponse(ctx, ctx.Request, req, s)
	if err != nil {
		pretty.Println(err)
		a.fosite.WriteAuthorizeError(ctx.Writer, req, err)
		return
	}

	// write response
	a.fosite.WriteAuthorizeResponse(ctx.Writer, req, res)
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"reflect"

	"github.com/aerogo/api"
	"github.com/animenotifier/arn"
)

var routeTests = map[string][]string{
	// User
	"/user/:nick": []string{
		"/+Akyoto",
	},

	"/user/:nick/threads": []string{
		"/+Akyoto/threads",
	},

	"/user/:nick/posts": []string{
		"/+Akyoto/posts",
	},

	"/user/:nick/tracks": []string{
		"/+Akyoto/tracks",
	},

	"/user/:nick/animelist": []string{
		"/+Akyoto/animelist",
	},

	"/user/:nick/animelist/:id": []string{
		"/+Akyoto/animelist/7929",
	},

	// Pages
	"/anime/:id": []string{
		"/anime/1",
	},

	"/threads/:id": []string{
		"/threads/HJgS7c2K",
	},

	"/posts/:id": []string{
		"/posts/B1RzshnK",
	},

	"/forum/:tag": []string{
		"/forum/general",
	},

	"/search/:term": []string{
		"/search/Dragon Ball",
	},

	"/tracks/:id": []string{
		"/tracks/h0ac8sKkg",
	},

	// API
	"/api/anime/:id": []string{
		"/api/anime/1",
	},

	"/api/thread/:id": []string{
		"/api/thread/HJgS7c2K",
	},

	"/api/post/:id": []string{
		"/api/post/B1RzshnK",
	},

	"/api/animelist/:id": []string{
		"/api/animelist/4J6qpK1ve",
	},

	"/api/animelist/:id/get/:item": []string{
		"/api/animelist/4J6qpK1ve/get/7929",
	},

	"/api/animelist/:id/get/:item/:property": []string{
		"/api/animelist/4J6qpK1ve/get/7929/Episodes",
	},

	"/api/settings/:id": []string{
		"/api/settings/4J6qpK1ve",
	},

	"/api/user/:id": []string{
		"/api/user/4J6qpK1ve",
	},

	"/api/emailtouser/:id": []string{
		"/api/emailtouser/e.urbach@gmail.com",
	},

	"/api/googletouser/:id": []string{
		"/api/googletouser/106530160120373282283",
	},

	"/api/nicktouser/:id": []string{
		"/api/nicktouser/Akyoto",
	},

	"/api/searchindex/:id": []string{
		"/api/searchindex/Anime",
	},

	"/api/analytics/:id": []string{
		"/api/analytics/4J6qpK1ve",
	},

	"/api/soundtrack/:id": []string{
		"/api/soundtrack/h0ac8sKkg",
	},

	"/api/soundcloudtosoundtrack/:id": []string{
		"/api/soundcloudtosoundtrack/145918628",
	},

	"/api/youtubetosoundtrack/:id": []string{
		"/api/youtubetosoundtrack/hU2wqJuOIp4",
	},

	// Images
	"/images/avatars/large/:file": []string{
		"/images/avatars/large/4J6qpK1ve.webp",
	},

	"/images/avatars/small/:file": []string{
		"/images/avatars/small/4J6qpK1ve.webp",
	},

	"/images/brand/:file": []string{
		"/images/brand/64.webp",
	},

	"/images/login/:file": []string{
		"/images/login/google",
	},

	"/images/cover/:file": []string{
		"/images/cover/default",
	},

	"/images/elements/:file": []string{
		"/images/elements/no-avatar.svg",
	},

	// Disable these tests because they require authorization
	"/auth/google":            nil,
	"/auth/google/callback":   nil,
	"/auth/facebook":          nil,
	"/auth/facebook/callback": nil,
	"/anime/:id/edit":         nil,
	"/new/thread":             nil,
	"/new/soundtrack":         nil,
	"/user":                   nil,
	"/settings":               nil,
	"/extension/embed":        nil,
}

// API interfaces
var creatable = reflect.TypeOf((*api.Creatable)(nil)).Elem()
var updatable = reflect.TypeOf((*api.Updatable)(nil)).Elem()
var collection = reflect.TypeOf((*api.Collection)(nil)).Elem()

// Required interface implementations
var interfaceImplementations = map[string][]reflect.Type{
	"User": []reflect.Type{
		updatable,
	},
	"Thread": []reflect.Type{
		creatable,
	},
	"Post": []reflect.Type{
		creatable,
	},
	"SoundTrack": []reflect.Type{
		creatable,
	},
	"Analytics": []reflect.Type{
		creatable,
	},
	"AnimeList": []reflect.Type{
		collection,
	},
}

func init() {
	// Specify test routes
	for route, examples := range routeTests {
		app.Test(route, examples)
	}

	// Check interface implementations
	for typeName, interfaces := range interfaceImplementations {
		for _, requiredInterface := range interfaces {
			if !reflect.PtrTo(arn.DB.Type(typeName)).Implements(requiredInterface) {
				panic(errors.New(typeName + " does not implement interface " + requiredInterface.Name()))
			}
		}
	}
}
<commit_msg>Fixed tests<commit_after>package main

import (
	"errors"
	"reflect"

	"github.com/aerogo/api"
	"github.com/animenotifier/arn"
)

var routeTests = map[string][]string{
	// User
	"/user/:nick": []string{
		"/+Akyoto",
	},

	"/user/:nick/threads": []string{
		"/+Akyoto/threads",
	},

	"/user/:nick/posts": []string{
		"/+Akyoto/posts",
	},

	"/user/:nick/tracks": []string{
		"/+Akyoto/tracks",
	},

	"/user/:nick/animelist": []string{
		"/+Akyoto/animelist",
	},

	"/user/:nick/animelist/:id": []string{
		"/+Akyoto/animelist/7929",
	},

	// Pages
	"/anime/:id": []string{
		"/anime/1",
	},

	"/threads/:id": []string{
		"/threads/HJgS7c2K",
	},

	"/posts/:id": []string{
		"/posts/B1RzshnK",
	},

	"/forum/:tag": []string{
		"/forum/general",
	},

	"/search/:term": []string{
		"/search/Dragon Ball",
	},

	"/tracks/:id": []string{
		"/tracks/h0ac8sKkg",
	},

	// API
	"/api/anime/:id": []string{
		"/api/anime/1",
	},

	"/api/thread/:id": []string{
		"/api/thread/HJgS7c2K",
	},

	"/api/post/:id": []string{
		"/api/post/B1RzshnK",
	},

	"/api/animelist/:id": []string{
		"/api/animelist/4J6qpK1ve",
	},

	"/api/animelist/:id/get/:item": []string{
		"/api/animelist/4J6qpK1ve/get/7929",
	},

	"/api/animelist/:id/get/:item/:property": []string{
		"/api/animelist/4J6qpK1ve/get/7929/Episodes",
	},

	"/api/settings/:id": []string{
		"/api/settings/4J6qpK1ve",
	},

	"/api/user/:id": []string{
		"/api/user/4J6qpK1ve",
	},

	"/api/emailtouser/:id": []string{
		"/api/emailtouser/e.urbach@gmail.com",
	},

	"/api/googletouser/:id": []string{
		"/api/googletouser/106530160120373282283",
	},

	"/api/facebooktouser/:id": []string{
		"/api/facebooktouser/10207576239700188",
	},

	"/api/nicktouser/:id": []string{
		"/api/nicktouser/Akyoto",
	},

	"/api/searchindex/:id": []string{
		"/api/searchindex/Anime",
	},

	"/api/analytics/:id": []string{
		"/api/analytics/4J6qpK1ve",
	},

	"/api/soundtrack/:id": []string{
		"/api/soundtrack/h0ac8sKkg",
	},

	"/api/soundcloudtosoundtrack/:id": []string{
		"/api/soundcloudtosoundtrack/145918628",
	},

	"/api/youtubetosoundtrack/:id": []string{
		"/api/youtubetosoundtrack/hU2wqJuOIp4",
	},

	// Images
	"/images/avatars/large/:file": []string{
		"/images/avatars/large/4J6qpK1ve.webp",
	},

	"/images/avatars/small/:file": []string{
		"/images/avatars/small/4J6qpK1ve.webp",
	},

	"/images/brand/:file": []string{
		"/images/brand/64.webp",
	},

	"/images/login/:file": []string{
		"/images/login/google",
	},

	"/images/cover/:file": []string{
		"/images/cover/default",
	},

	"/images/elements/:file": []string{
		"/images/elements/no-avatar.svg",
	},

	// Disable these tests because they require authorization
	"/auth/google":              nil,
	"/auth/google/callback":     nil,
	"/auth/facebook":            nil,
	"/auth/facebook/callback":   nil,
	"/import":                   nil,
	"/import/anilist/animelist": nil,
	"/anime/:id/edit":           nil,
	"/new/thread":               nil,
	"/new/soundtrack":           nil,
	"/user":                     nil,
	"/settings":                 nil,
	"/extension/embed":          nil,
}

// API interfaces
var creatable = reflect.TypeOf((*api.Creatable)(nil)).Elem()
var updatable = reflect.TypeOf((*api.Updatable)(nil)).Elem()
var collection = reflect.TypeOf((*api.Collection)(nil)).Elem()

// Required interface implementations
var interfaceImplementations = map[string][]reflect.Type{
	"User": []reflect.Type{
		updatable,
	},
	"Thread": []reflect.Type{
		creatable,
	},
	"Post": []reflect.Type{
		creatable,
	},
	"SoundTrack": []reflect.Type{
		creatable,
	},
	"Analytics": []reflect.Type{
		creatable,
	},
	"AnimeList": []reflect.Type{
		collection,
	},
}

func init() {
	// Specify test routes
	for route, examples := range routeTests {
		app.Test(route, examples)
	}

	// Check interface implementations
	for typeName, interfaces := range interfaceImplementations {
		for _, requiredInterface := range interfaces {
			if !reflect.PtrTo(arn.DB.Type(typeName)).Implements(requiredInterface) {
				panic(errors.New(typeName + " does not implement interface " + requiredInterface.Name()))
			}
		}
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2019, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information

// +build !windows

package interp

import (
	"bufio"
	"context"
	"io"
	"os"
	"os/exec"
	"strings"
	"testing"

	"github.com/creack/pty"
)

func TestRunnerTerminalStdIO(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name  string
		files func(*testing.T) (slave io.Writer, master io.Reader)
		want  string
	}{
		{"Nil", func(t *testing.T) (io.Writer, io.Reader) {
			return nil, strings.NewReader("\n")
		}, "\n"},
		{"Pipe", func(t *testing.T) (io.Writer, io.Reader) {
			pr, pw := io.Pipe()
			return pw, pr
		}, "end\n"},
		{"Pseudo", func(t *testing.T) (io.Writer, io.Reader) {
			pty, tty, err := pty.Open()
			if err != nil {
				t.Fatal(err)
			}
			return tty, pty
		}, "012end\r\n"},
	}
	file := parse(t, nil, `
		for n in 0 1 2 3; do if [[ -t $n ]]; then echo -n $n; fi; done; echo end
	`)
	for _, test := range tests {
		test := test
		t.Run(test.name, func(t *testing.T) {
			t.Parallel()

			slave, master := test.files(t)
			// some slaves can be used as stdin too, like a tty
			slaveReader, _ := slave.(io.Reader)

			r, _ := New(StdIO(slaveReader, slave, slave))
			go func() {
				// To mimic os/exec.Cmd.Start, use a goroutine.
				if err := r.Run(context.Background(), file); err != nil {
					t.Error(err)
				}
			}()

			got, err := bufio.NewReader(master).ReadString('\n')
			if err != nil {
				t.Fatal(err)
			}
			if got != test.want {
				t.Fatalf("\nwant: %q\ngot:  %q", test.want, got)
			}
			if closer, ok := slave.(io.Closer); ok {
				closer.Close()
			}
			if closer, ok := master.(io.Closer); ok {
				closer.Close()
			}
		})
	}
}

func TestRunnerTerminalExec(t *testing.T) {
	t.Parallel()
	tests := []struct {
		name  string
		start func(*testing.T, *exec.Cmd) io.Reader
		want  string
	}{
		{"Nil", func(t *testing.T, cmd *exec.Cmd) io.Reader {
			if err := cmd.Start(); err != nil {
				t.Fatal(err)
			}
			return strings.NewReader("\n")
		}, "\n"},
		{"Pipe", func(t *testing.T, cmd *exec.Cmd) io.Reader {
			out, err := cmd.StdoutPipe()
			if err != nil {
				t.Fatal(err)
			}
			cmd.Stderr = cmd.Stdout
			if err := cmd.Start(); err != nil {
				t.Fatal(err)
			}
			return out
		}, "end\n"},
		{"Pseudo", func(t *testing.T, cmd *exec.Cmd) io.Reader {
			pty_, err := pty.Start(cmd)
			if err != nil {
				t.Fatal(err)
			}
			return pty_
		}, "012end\r\n"},
	}
	for _, test := range tests {
		test := test
		t.Run(test.name, func(t *testing.T) {
			t.Parallel()

			cmd := exec.Command(os.Getenv("GOSH_PROG"),
				"for n in 0 1 2 3; do if [[ -t $n ]]; then echo -n $n; fi; done; echo end")
			out := test.start(t, cmd)

			got, err := bufio.NewReader(out).ReadString('\n')
			if err != nil {
				t.Fatal(err)
			}
			if got != test.want {
				t.Fatalf("\nwant: %q\ngot:  %q", test.want, string(got))
			}
			if err := cmd.Wait(); err != nil {
				t.Fatal(err)
			}
		})
	}
}
<commit_msg>interp: skip TestRunnerTerminalExec/Pseudo on Mac<commit_after>// Copyright (c) 2019, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information

// +build !windows

package interp

import (
	"bufio"
	"context"
	"io"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"testing"

	"github.com/creack/pty"
)

func TestRunnerTerminalStdIO(t *testing.T) {
	t.Parallel()

	tests := []struct {
		name  string
		files func(*testing.T) (slave io.Writer, master io.Reader)
		want  string
	}{
		{"Nil", func(t *testing.T) (io.Writer, io.Reader) {
			return nil, strings.NewReader("\n")
		}, "\n"},
		{"Pipe", func(t *testing.T) (io.Writer, io.Reader) {
			pr, pw := io.Pipe()
			return pw, pr
		}, "end\n"},
		{"Pseudo", func(t *testing.T) (io.Writer, io.Reader) {
			pty, tty, err := pty.Open()
			if err != nil {
				t.Fatal(err)
			}
			return tty, pty
		}, "012end\r\n"},
	}
	file := parse(t, nil, `
		for n in 0 1 2 3; do if [[ -t $n ]]; then echo -n $n; fi; done; echo end
	`)
	for _, test := range tests {
		test := test
		t.Run(test.name, func(t *testing.T) {
			t.Parallel()

			slave, master := test.files(t)
			// some slaves can be used as stdin too, like a tty
			slaveReader, _ := slave.(io.Reader)

			r, _ := New(StdIO(slaveReader, slave, slave))
			go func() {
				// To mimic os/exec.Cmd.Start, use a goroutine.
				if err := r.Run(context.Background(), file); err != nil {
					t.Error(err)
				}
			}()

			got, err := bufio.NewReader(master).ReadString('\n')
			if err != nil {
				t.Fatal(err)
			}
			if got != test.want {
				t.Fatalf("\nwant: %q\ngot:  %q", test.want, got)
			}
			if closer, ok := slave.(io.Closer); ok {
				closer.Close()
			}
			if closer, ok := master.(io.Closer); ok {
				closer.Close()
			}
		})
	}
}

func TestRunnerTerminalExec(t *testing.T) {
	t.Parallel()
	tests := []struct {
		name  string
		start func(*testing.T, *exec.Cmd) io.Reader
		want  string
	}{
		{"Nil", func(t *testing.T, cmd *exec.Cmd) io.Reader {
			if err := cmd.Start(); err != nil {
				t.Fatal(err)
			}
			return strings.NewReader("\n")
		}, "\n"},
		{"Pipe", func(t *testing.T, cmd *exec.Cmd) io.Reader {
			out, err := cmd.StdoutPipe()
			if err != nil {
				t.Fatal(err)
			}
			cmd.Stderr = cmd.Stdout
			if err := cmd.Start(); err != nil {
				t.Fatal(err)
			}
			return out
		}, "end\n"},
		{"Pseudo", func(t *testing.T, cmd *exec.Cmd) io.Reader {
			pty_, err := pty.Start(cmd)
			if err != nil {
				t.Fatal(err)
			}
			return pty_
		}, "012end\r\n"},
	}
	for _, test := range tests {
		test := test
		t.Run(test.name, func(t *testing.T) {
			if test.name == "Pseudo" && runtime.GOOS == "darwin" {
				t.Skipf("too flaky on GitHub's Mac machines; see https://github.com/mvdan/sh/issues/513")
			}
			t.Parallel()

			cmd := exec.Command(os.Getenv("GOSH_PROG"),
				"for n in 0 1 2 3; do if [[ -t $n ]]; then echo -n $n; fi; done; echo end")
			out := test.start(t, cmd)

			got, err := bufio.NewReader(out).ReadString('\n')
			if err != nil {
				t.Fatal(err)
			}
			if got != test.want {
				t.Fatalf("\nwant: %q\ngot:  %q", test.want, string(got))
			}
			if err := cmd.Wait(); err != nil {
				t.Fatal(err)
			}
		})
	}
}
<|endoftext|>


<commit_before>// Package ipify provides a single function for retrieving your computer's
// public IP address from the ipify service: http://www.ipify.org
package pubip

import (
	"errors"
	"io/ioutil"
	"net"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/jpillora/backoff"
)

// GetIp queries the ipify service (http://www.ipify.org) to retrieve this
// machine's public IP address.  Returns your public IP address as a string, and
// any error encountered.  By default, this function will run using exponential
// backoff -- if this function fails for any reason, the request will be retried
// up to 3 times.
//
// Usage:
//
//		package main
//
//		import (
//			"fmt"
//			"github.com/rdegges/go-ipify"
//		)
//
//		func main() {
//			ip, err := ipify.GetIp()
//			if err != nil {
//				fmt.Println("Couldn't get my IP address:", err)
//			} else {
//				fmt.Println("My IP address is:", ip)
//			}
//		}
func GetIp(dest string) (string, error) {
	b := &backoff.Backoff{
		Jitter: true,
	}
	client := &http.Client{}

	req, err := http.NewRequest("GET", dest, nil)
	if err != nil {
		return "", err
	}

	//req.Header.Add("User-Agent", USER_AGENT)

	for tries := 0; tries < MaxTries; tries++ {
		resp, err := client.Do(req)
		if err != nil {
			d := b.Duration()
			time.Sleep(d)
			continue
		}

		defer resp.Body.Close()

		out, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return "", err
		}

		if resp.StatusCode != 200 {
			return "", errors.New(dest + " status code" + strconv.Itoa(resp.StatusCode) + ", body: " + string(out))
		}

		tout := strings.TrimSpace(string(out))
		ip := net.ParseIP(tout)
		if ip == nil {
			return "", errors.New("IP address not valid: " + tout)
		}
		return ip.String(), nil
	}

	return "", errors.New("Failed to reach " + dest)
}

func isValid(rs []string) bool {
	if len(rs) < 2 {
		return false
	}
	for _, s := range rs {
		if s != rs[0] {
			return false
		}
	}
	return true
}

func worker(d string, r chan<- string, e chan<- error) {
	ip, err := GetIp(d)
	if err != nil {
		e <- err
		return
	}
	r <- ip
}

func Get() (string, error) {
	var results []string
	var errs []string
	resultCh := make(chan string, len(APIURIs))
	errCh := make(chan error)

	for _, d := range APIURIs {
		go worker(d, resultCh, errCh)
	}
	for {
		select {
		case err := <-errCh:
			errs = append(errs, err.Error())
		case r := <-resultCh:
			results = append(results, r)
			if isValid(results) {
				return results[0], nil
			}
		case <-time.After(Timeout):
			return "", errors.New(strings.Join(errs, "\n"))
		}
	}
}
<commit_msg>Set the buffer size of the error channel `errCh`<commit_after>// Package ipify provides a single function for retrieving your computer's
// public IP address from the ipify service: http://www.ipify.org
package pubip

import (
	"errors"
	"io/ioutil"
	"net"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/jpillora/backoff"
)

// GetIp queries the ipify service (http://www.ipify.org) to retrieve this
// machine's public IP address.  Returns your public IP address as a string, and
// any error encountered.  By default, this function will run using exponential
// backoff -- if this function fails for any reason, the request will be retried
// up to 3 times.
//
// Usage:
//
//		package main
//
//		import (
//			"fmt"
//			"github.com/rdegges/go-ipify"
//		)
//
//		func main() {
//			ip, err := ipify.GetIp()
//			if err != nil {
//				fmt.Println("Couldn't get my IP address:", err)
//			} else {
//				fmt.Println("My IP address is:", ip)
//			}
//		}
func GetIp(dest string) (string, error) {
	b := &backoff.Backoff{
		Jitter: true,
	}
	client := &http.Client{}

	req, err := http.NewRequest("GET", dest, nil)
	if err != nil {
		return "", err
	}

	//req.Header.Add("User-Agent", USER_AGENT)

	for tries := 0; tries < MaxTries; tries++ {
		resp, err := client.Do(req)
		if err != nil {
			d := b.Duration()
			time.Sleep(d)
			continue
		}

		defer resp.Body.Close()

		out, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return "", err
		}

		if resp.StatusCode != 200 {
			return "", errors.New(dest + " status code" + strconv.Itoa(resp.StatusCode) + ", body: " + string(out))
		}

		tout := strings.TrimSpace(string(out))
		ip := net.ParseIP(tout)
		if ip == nil {
			return "", errors.New("IP address not valid: " + tout)
		}
		return ip.String(), nil
	}

	return "", errors.New("Failed to reach " + dest)
}

func isValid(rs []string) bool {
	if len(rs) < 2 {
		return false
	}
	for _, s := range rs {
		if s != rs[0] {
			return false
		}
	}
	return true
}

func worker(d string, r chan<- string, e chan<- error) {
	ip, err := GetIp(d)
	if err != nil {
		e <- err
		return
	}
	r <- ip
}

func Get() (string, error) {
	var results []string
	var errs []string
	resultCh := make(chan string, len(APIURIs))
	errCh := make(chan error, len(APIURIs))

	for _, d := range APIURIs {
		go worker(d, resultCh, errCh)
	}
	for {
		select {
		case err := <-errCh:
			errs = append(errs, err.Error())
		case r := <-resultCh:
			results = append(results, r)
			if isValid(results) {
				return results[0], nil
			}
		case <-time.After(Timeout):
			return "", errors.New(strings.Join(errs, "\n"))
		}
	}
}
<|endoftext|>


<commit_before>package acceptance_test

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"

	acceptance "github.com/cloudfoundry/bosh-bootloader/acceptance-tests"

	"github.com/cloudfoundry/bosh-bootloader/acceptance-tests/actors"
	"github.com/cloudfoundry/bosh-bootloader/testhelpers"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/pivotal-cf-experimental/bosh-test/bosh"
)

var _ = Describe("concourse deployment test", func() {
	var (
		bbl           actors.BBL
		state         acceptance.State
		lbURL         string
		configuration acceptance.Config
	)

	BeforeEach(func() {
		var err error
		configuration, err = acceptance.LoadConfig()
		Expect(err).NotTo(HaveOccurred())

		bbl = actors.NewBBL(configuration.StateFileDir, pathToBBL, configuration, "concourse-env")
		state = acceptance.NewState(configuration.StateFileDir)

		bbl.Up(configuration.IAAS, []string{"--name", bbl.PredefinedEnvID()})

		certPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT)
		Expect(err).NotTo(HaveOccurred())

		keyPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY)
		Expect(err).NotTo(HaveOccurred())

		bbl.CreateLB("concourse", certPath, keyPath, "")

		lbURL, err = actors.LBURL(configuration, bbl, state)
		Expect(err).NotTo(HaveOccurred())
	})

	It("is able to deploy concourse and teardown infrastructure", func() {
		boshClient := bosh.NewClient(bosh.Config{
			URL:              bbl.DirectorAddress(),
			Username:         bbl.DirectorUsername(),
			Password:         bbl.DirectorPassword(),
			AllowInsecureSSL: true,
		})

		By("uploading releases and stemcells", func() {
			err := uploadRelease(boshClient, configuration.ConcourseReleasePath)
			Expect(err).NotTo(HaveOccurred())

			err = uploadRelease(boshClient, configuration.GardenReleasePath)
			Expect(err).NotTo(HaveOccurred())

			err = uploadStemcell(boshClient, configuration.StemcellPath)
			Expect(err).NotTo(HaveOccurred())
		})

		By("running bosh deploy and checking all the vms are running", func() {
			os.Setenv("BOSH_CLIENT", bbl.DirectorUsername())
			os.Setenv("BOSH_CLIENT_SECRET", bbl.DirectorPassword())
			os.Setenv("BOSH_ENVIRONMENT", bbl.DirectorAddress())
			os.Setenv("BOSH_CA_CERT", bbl.DirectorCACert())
			args := []string{
				"-d", "concourse",
				"deploy",
				fmt.Sprintf("%s/concourse-deployment.yml", configuration.ConcourseDeploymentPath),
				"-o", fmt.Sprintf("%s/operations/%s.yml", configuration.ConcourseDeploymentPath, configuration.IAAS),
				"--vars-store", "concourse-vars.yml",
				"-v", fmt.Sprintf("domain=%s", lbURL),
				"-n",
			}
			cmd := exec.Command("bosh", args...)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			err := cmd.Run()
			Expect(err).NotTo(HaveOccurred())

			Eventually(func() ([]bosh.VM, error) {
				vms, err := boshClient.DeploymentVMs("concourse")
				if err != nil {
					return []bosh.VM{}, err
				}

				vmsNoID := []bosh.VM{}
				for _, vm := range vms {
					vm.ID = ""
					vm.IPs = nil
					vmsNoID = append(vmsNoID, vm)
				}
				return vmsNoID, nil
			}, "1m", "10s").Should(ConsistOf([]bosh.VM{
				{JobName: "worker", Index: 0, State: "running"},
				{JobName: "db", Index: 0, State: "running"},
				{JobName: "web", Index: 0, State: "running"},
			}))
		})

		By("testing the deployment", func() {
			tr := &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			}
			client := &http.Client{Transport: tr}

			resp, err := client.Get(lbURL)
			Expect(err).NotTo(HaveOccurred())

			Expect(resp.StatusCode).To(Equal(http.StatusOK))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).NotTo(HaveOccurred())

			Expect(string(body)).To(ContainSubstring("<title>Concourse</title>"))
		})

		By("deleting the deployment", func() {
			err := boshClient.DeleteDeployment("concourse")
			Expect(err).NotTo(HaveOccurred())
		})

		By("deleting load balancers", func() {
			bbl.DeleteLBs()
		})

		By("tearing down the infrastructure", func() {
			bbl.Destroy()
		})
	})
})

func uploadStemcell(boshClient bosh.Client, stemcellPath string) error {
	stemcell, err := openFile(stemcellPath)
	if err != nil {
		return err
	}

	_, err = boshClient.UploadStemcell(stemcell)
	return err
}

func uploadRelease(boshClient bosh.Client, releasePath string) error {
	release, err := openFile(releasePath)
	if err != nil {
		return err
	}

	_, err = boshClient.UploadRelease(release)
	return err
}

func openFile(filePath string) (bosh.SizeReader, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}

	stat, err := file.Stat()
	if err != nil {
		return nil, err
	}

	return bosh.NewSizeReader(file, stat.Size()), nil
}
<commit_msg>Accept multiple workers in concourse acceptance<commit_after>package acceptance_test

import (
	"crypto/tls"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"

	acceptance "github.com/cloudfoundry/bosh-bootloader/acceptance-tests"

	"github.com/cloudfoundry/bosh-bootloader/acceptance-tests/actors"
	"github.com/cloudfoundry/bosh-bootloader/testhelpers"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"github.com/pivotal-cf-experimental/bosh-test/bosh"
)

var _ = Describe("concourse deployment test", func() {
	var (
		bbl           actors.BBL
		state         acceptance.State
		lbURL         string
		configuration acceptance.Config
	)

	BeforeEach(func() {
		var err error
		configuration, err = acceptance.LoadConfig()
		Expect(err).NotTo(HaveOccurred())

		bbl = actors.NewBBL(configuration.StateFileDir, pathToBBL, configuration, "concourse-env")
		state = acceptance.NewState(configuration.StateFileDir)

		bbl.Up(configuration.IAAS, []string{"--name", bbl.PredefinedEnvID()})

		certPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_CERT)
		Expect(err).NotTo(HaveOccurred())

		keyPath, err := testhelpers.WriteContentsToTempFile(testhelpers.BBL_KEY)
		Expect(err).NotTo(HaveOccurred())

		bbl.CreateLB("concourse", certPath, keyPath, "")

		lbURL, err = actors.LBURL(configuration, bbl, state)
		Expect(err).NotTo(HaveOccurred())
	})

	It("is able to deploy concourse and teardown infrastructure", func() {
		boshClient := bosh.NewClient(bosh.Config{
			URL:              bbl.DirectorAddress(),
			Username:         bbl.DirectorUsername(),
			Password:         bbl.DirectorPassword(),
			AllowInsecureSSL: true,
		})

		By("uploading releases and stemcells", func() {
			err := uploadRelease(boshClient, configuration.ConcourseReleasePath)
			Expect(err).NotTo(HaveOccurred())

			err = uploadRelease(boshClient, configuration.GardenReleasePath)
			Expect(err).NotTo(HaveOccurred())

			err = uploadStemcell(boshClient, configuration.StemcellPath)
			Expect(err).NotTo(HaveOccurred())
		})

		By("running bosh deploy and checking all the vms are running", func() {
			os.Setenv("BOSH_CLIENT", bbl.DirectorUsername())
			os.Setenv("BOSH_CLIENT_SECRET", bbl.DirectorPassword())
			os.Setenv("BOSH_ENVIRONMENT", bbl.DirectorAddress())
			os.Setenv("BOSH_CA_CERT", bbl.DirectorCACert())
			args := []string{
				"-d", "concourse",
				"deploy",
				fmt.Sprintf("%s/concourse-deployment.yml", configuration.ConcourseDeploymentPath),
				"-o", fmt.Sprintf("%s/operations/%s.yml", configuration.ConcourseDeploymentPath, configuration.IAAS),
				"--vars-store", "concourse-vars.yml",
				"-v", fmt.Sprintf("domain=%s", lbURL),
				"-n",
			}
			cmd := exec.Command("bosh", args...)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			err := cmd.Run()
			Expect(err).NotTo(HaveOccurred())

			Eventually(func() ([]bosh.VM, error) {
				vms, err := boshClient.DeploymentVMs("concourse")
				if err != nil {
					return []bosh.VM{}, err
				}

				vmsNoID := []bosh.VM{}
				for _, vm := range vms {
					vm.ID = ""
					vm.IPs = nil
					vmsNoID = append(vmsNoID, vm)
				}
				return vmsNoID, nil
			}, "1m", "10s").Should(ConsistOf([]bosh.VM{
				{JobName: "worker", Index: 0, State: "running"},
				{JobName: "worker", Index: 1, State: "running"},
				{JobName: "db", Index: 0, State: "running"},
				{JobName: "web", Index: 0, State: "running"},
			}))
		})

		By("testing the deployment", func() {
			tr := &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			}
			client := &http.Client{Transport: tr}

			resp, err := client.Get(lbURL)
			Expect(err).NotTo(HaveOccurred())

			Expect(resp.StatusCode).To(Equal(http.StatusOK))

			body, err := ioutil.ReadAll(resp.Body)
			Expect(err).NotTo(HaveOccurred())

			Expect(string(body)).To(ContainSubstring("<title>Concourse</title>"))
		})

		By("deleting the deployment", func() {
			err := boshClient.DeleteDeployment("concourse")
			Expect(err).NotTo(HaveOccurred())
		})

		By("deleting load balancers", func() {
			bbl.DeleteLBs()
		})

		By("tearing down the infrastructure", func() {
			bbl.Destroy()
		})
	})
})

func uploadStemcell(boshClient bosh.Client, stemcellPath string) error {
	stemcell, err := openFile(stemcellPath)
	if err != nil {
		return err
	}

	_, err = boshClient.UploadStemcell(stemcell)
	return err
}

func uploadRelease(boshClient bosh.Client, releasePath string) error {
	release, err := openFile(releasePath)
	if err != nil {
		return err
	}

	_, err = boshClient.UploadRelease(release)
	return err
}

func openFile(filePath string) (bosh.SizeReader, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return nil, err
	}

	stat, err := file.Stat()
	if err != nil {
		return nil, err
	}

	return bosh.NewSizeReader(file, stat.Size()), nil
}
<|endoftext|>


<commit_before>package script

import (
	"encoding/json"

	"github.com/HouzuoGuo/tiedot/db"
)

type ScriptType string

const (
	Javascript ScriptType = "Javascript"
)

type Script struct {
	ID      int
	Type    ScriptType
	Title   string
	Body    string
	Enabled bool
}

type ScriptRepository struct {
	database *db.DB
}

func NewScriptRepository(database *db.DB) ScriptRepository {
	return ScriptRepository{database}
}

func hydrateScript(rawScript map[string]interface{}) Script {
	script := Script{}

	script.Title = rawScript["Title"].(string)
	script.Enabled = rawScript["Enabled"].(bool)
	script.Type = ScriptType(rawScript["Type"].(string))
	script.Body = rawScript["Body"].(string)

	return script
}

func flattenScript(script Script) map[string]interface{} {
	rawScript := make(map[string]interface{})

	rawScript["Title"] = script.Title
	rawScript["Enabled"] = script.Enabled
	rawScript["Type"] = script.Type
	rawScript["Body"] = script.Body

	return rawScript
}

func (repo *ScriptRepository) FetchAll() []Script {
	col := repo.database.Use("Scripts")
	scripts := make([]Script, 0)
	col.ForEachDoc(func(id int, doc []byte) (moveOn bool) {
		moveOn = true

		val := make(map[string]interface{}, 0)

		json.Unmarshal(doc, &val)
		script := hydrateScript(val)
		script.ID = id

		scripts = append(scripts, script)

		return
	})

	return scripts
}

func (repo *ScriptRepository) Fetch(id int) Script {
	col := repo.database.Use("Scripts")

	rawScript, err := col.Read(id)
	if err != nil {
		panic(err)
	}
	script := hydrateScript(rawScript)
	script.ID = id

	return script
}

func (repo *ScriptRepository) Save(script Script) {
	col := repo.database.Use("Scripts")
	data := flattenScript(script)

	if script.ID <= 0 {
		id, _ := col.Insert(data)
		script.ID = id

	} else {
		col.Update(script.ID, data)
	}
}

func (repo *ScriptRepository) Delete(id int) {
	col := repo.database.Use("Scripts")
	col.Delete(id)
}
<commit_msg>Scripts are now sorted lexicographically.<commit_after>package script

import (
	"encoding/json"

	"github.com/HouzuoGuo/tiedot/db"
	"sort"
)

type ScriptType string

const (
	Javascript ScriptType = "Javascript"
)

type Script struct {
	ID      int
	Type    ScriptType
	Title   string
	Body    string
	Enabled bool
}

type ScriptRepository struct {
	database *db.DB
}

func NewScriptRepository(database *db.DB) ScriptRepository {
	return ScriptRepository{database}
}

func hydrateScript(rawScript map[string]interface{}) Script {
	script := Script{}

	script.Title = rawScript["Title"].(string)
	script.Enabled = rawScript["Enabled"].(bool)
	script.Type = ScriptType(rawScript["Type"].(string))
	script.Body = rawScript["Body"].(string)

	return script
}

func flattenScript(script Script) map[string]interface{} {
	rawScript := make(map[string]interface{})

	rawScript["Title"] = script.Title
	rawScript["Enabled"] = script.Enabled
	rawScript["Type"] = script.Type
	rawScript["Body"] = script.Body

	return rawScript
}

type scriptSlice []Script

func (s scriptSlice) Len() int {
	return len(s)
}

func (s scriptSlice) Less(i, j int) bool {
	return s[i].Title < s[j].Title;
}

func (s scriptSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (repo *ScriptRepository) FetchAll() []Script {
	col := repo.database.Use("Scripts")
	scripts := make([]Script, 0)
	col.ForEachDoc(func(id int, doc []byte) (moveOn bool) {
		moveOn = true

		val := make(map[string]interface{}, 0)

		json.Unmarshal(doc, &val)
		script := hydrateScript(val)
		script.ID = id

		scripts = append(scripts, script)

		return
	})

	sort.Sort(scriptSlice(scripts))

	return scripts
}

func (repo *ScriptRepository) Fetch(id int) Script {
	col := repo.database.Use("Scripts")

	rawScript, err := col.Read(id)
	if err != nil {
		panic(err)
	}
	script := hydrateScript(rawScript)
	script.ID = id

	return script
}

func (repo *ScriptRepository) Save(script Script) {
	col := repo.database.Use("Scripts")
	data := flattenScript(script)

	if script.ID <= 0 {
		id, _ := col.Insert(data)
		script.ID = id

	} else {
		col.Update(script.ID, data)
	}
}

func (repo *ScriptRepository) Delete(id int) {
	col := repo.database.Use("Scripts")
	col.Delete(id)
}
<|endoftext|>


<commit_before>
package main

import (
    "fmt"
    "../GoLang/fibonacci"
    "../GoLang/exponenciacao"
    "../GoLang/fatorial"
    "../GoLang/hanoi"
    "../GoLang/bubblesort"
)

func main() {
    fmt.Println("Fibonacci : ", fibonacci.Fibonacci(9))
    fmt.Println("Exponenciacao : ", exponenciacao.Exponenciacao(5, 5))
    fmt.Println("Fatorial : ", fatorial.Fatorial(6))
    fmt.Println("Hanoi : ")
    hanoi.Hanoi(0, 2, 1, 3)
    slice := []int{5, 2, 1, 6, 9, 8, 7, 3, 4}
    fmt.Println("Slice : ", slice)
    fmt.Println("BubbleSort : ", bubblesort.BubbleSort(slice))
}
<commit_msg>Add test para o selection sort no main<commit_after>
package main

import (
    "fmt"
    "../GoLang/fibonacci"
    "../GoLang/exponenciacao"
    "../GoLang/fatorial"
    "../GoLang/hanoi"
    "../GoLang/bubblesort"
    "../GoLang/selectionsort"
)

func main() {
    fmt.Println("Fibonacci : ", fibonacci.Fibonacci(9))
    fmt.Println("Exponenciacao : ", exponenciacao.Exponenciacao(5, 5))
    fmt.Println("Fatorial : ", fatorial.Fatorial(6))
    fmt.Println("Hanoi : ")
    hanoi.Hanoi(0, 2, 1, 3)
    slice := []int{5, 2, 1, 6, 9, 8, 7, 3, 4}
    fmt.Println("Slice : ", slice)
    fmt.Println("BubbleSort : ", bubblesort.BubbleSort(slice))
    fmt.Println("SelectionSort : ", selectionsort.SelectionSort(slice))
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"strings"

	"github.com/docker/docker/cow"
	"github.com/docker/docker/pkg/mflag"
)

func metadata(flags *mflag.FlagSet, action string, m cow.Mall, args []string) int {
	if len(args) < 1 {
		return 1
	}
	allExist := true
	for _, what := range args {
		exists := false
		if container, err := m.GetContainer(what); err == nil {
			exists = true
			fmt.Printf("%s: %s\n", what, strings.TrimSuffix(container.Metadata, "\n"))
		} else if image, err := m.GetImage(what); err == nil {
			exists = true
			fmt.Printf("%s: %s\n", what, strings.TrimSuffix(image.Metadata, "\n"))
		}
		allExist = allExist && exists
	}
	if !allExist {
		return 1
	}
	return 0
}

func init() {
	commands = append(commands, command{
		names:       []string{"metadata"},
		optionsHelp: "[ImageOrContainerNameOrID [...]]",
		usage:       "Retrieve image or container metadata",
		minArgs:     1,
		action:      metadata,
	})
}
<commit_msg>Add a --quiet option to fetching metadata<commit_after>package main

import (
	"fmt"
	"strings"

	"github.com/docker/docker/cow"
	"github.com/docker/docker/pkg/mflag"
)

var metadataQuiet = false

func metadata(flags *mflag.FlagSet, action string, m cow.Mall, args []string) int {
	if len(args) < 1 {
		return 1
	}
	allExist := true
	for _, what := range args {
		exists := false
		if container, err := m.GetContainer(what); err == nil {
			exists = true
			if metadataQuiet {
				fmt.Printf("%s\n", strings.TrimSuffix(container.Metadata, "\n"))
			} else {
				fmt.Printf("%s: %s\n", what, strings.TrimSuffix(container.Metadata, "\n"))
			}
		} else if image, err := m.GetImage(what); err == nil {
			exists = true
			if metadataQuiet {
				fmt.Printf("%s\n", strings.TrimSuffix(image.Metadata, "\n"))
			} else {
				fmt.Printf("%s: %s\n", what, strings.TrimSuffix(image.Metadata, "\n"))
			}
		}
		allExist = allExist && exists
	}
	if !allExist {
		return 1
	}
	return 0
}

func init() {
	commands = append(commands, command{
		names:       []string{"metadata"},
		optionsHelp: "[ImageOrContainerNameOrID [...]]",
		usage:       "Retrieve image or container metadata",
		minArgs:     1,
		action:      metadata,
		addFlags: func(flags *mflag.FlagSet, cmd *command) {
			flags.BoolVar(&metadataQuiet, []string{"-quiet", "q"}, metadataQuiet, "Don't print names and IDs")
		},
	})
}
<|endoftext|>


<commit_before>// gddoexp is a command line tool crated to list eligible packages for
// archiving in GoDoc.org
package gddoexp

import (
	"fmt"

	"github.com/golang/gddo/database"
	"github.com/rafaeljusto/gddoexp"
)

func main() {
	db, err := database.New()
	if err != nil {
		fmt.Println("error creating database:", err)
		return
	}

	pkgs, err := db.AllPackages()
	if err != nil {
		fmt.Println("error retrieving all packages:", err)
		return
	}

	for _, pkg := range pkgs {
		if archive, err := gddoexp.ShouldArchivePackage(pkg.Path, db); err != nil {
			fmt.Println(err)
		} else if archive {
			fmt.Printf("package “%s” should be archived\n", pkg.Path)
		}
	}
}
<commit_msg>Fix command line package<commit_after>// gddoexp is a command line tool crated to list eligible packages for
// archiving in GoDoc.org
package main

import (
	"fmt"

	"github.com/golang/gddo/database"
	"github.com/rafaeljusto/gddoexp"
)

func main() {
	db, err := database.New()
	if err != nil {
		fmt.Println("error connecting to database:", err)
		return
	}

	pkgs, err := db.AllPackages()
	if err != nil {
		fmt.Println("error retrieving all packages:", err)
		return
	}

	for _, pkg := range pkgs {
		if archive, err := gddoexp.ShouldArchivePackage(pkg.Path, db); err != nil {
			fmt.Println(err)
		} else if archive {
			fmt.Printf("package “%s” should be archived\n", pkg.Path)
		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Knative Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"
	"time"

	"knative.dev/eventing-contrib/pkg/kncloudevents"

	"github.com/cloudevents/sdk-go/pkg/cloudevents"
	"github.com/cloudevents/sdk-go/pkg/cloudevents/types"
	"github.com/kelseyhightower/envconfig"
)

type Heartbeat struct {
	Sequence int    `json:"id"`
	Label    string `json:"label"`
}

var (
	eventSource string
	eventType   string
	sink        string
	label       string
	periodStr   string
)

func init() {
	flag.StringVar(&eventSource, "eventSource", "", "the event-source (CloudEvents)")
	flag.StringVar(&eventType, "eventType", "dev.knative.eventing.samples.heartbeat", "the event-type (CloudEvents)")
	flag.StringVar(&sink, "sink", "", "the host url to heartbeat to")
	flag.StringVar(&label, "label", "", "a special label")
	flag.StringVar(&periodStr, "period", "5", "the number of seconds between heartbeats")
}

type envConfig struct {
	// Sink URL where to send heartbeat cloudevents
	Sink string `envconfig:"SINK"`

	// Name of this pod.
	Name string `envconfig:"POD_NAME" required:"true"`

	// Namespace this pod exists in.
	Namespace string `envconfig:"POD_NAMESPACE" required:"true"`
}

func main() {
	flag.Parse()

	var env envConfig
	if err := envconfig.Process("", &env); err != nil {
		log.Printf("[ERROR] Failed to process env var: %s", err)
		os.Exit(1)
	}

	if env.Sink != "" {
		sink = env.Sink
	}

	c, err := kncloudevents.NewDefaultClient(sink)
	if err != nil {
		log.Fatalf("failed to create client: %s", err.Error())
	}

	var period time.Duration
	if p, err := strconv.Atoi(periodStr); err != nil {
		period = time.Duration(5) * time.Second
	} else {
		period = time.Duration(p) * time.Second
	}

	if eventSource == "" {
		eventSource = fmt.Sprintf("https://knative.dev/eventing-contrib/cmd/heartbeats/#%s/%s", env.Namespace, env.Name)
		log.Printf("Heartbeats Source: %s", eventSource)
	}

	if len(label) > 0 && label[0] == '"' {
		label, _ = strconv.Unquote(label)
	}
	hb := &Heartbeat{
		Sequence: 0,
		Label:    label,
	}
	ticker := time.NewTicker(period)
	for {
		hb.Sequence++

		event := cloudevents.Event{
			Context: cloudevents.EventContextV03{
				Type:   eventType,
				Source: *types.ParseURLRef(eventSource),
				Extensions: map[string]interface{}{
					"the":   42,
					"heart": "yes",
					"beats": true,
				},
			}.AsV02(),
			Data: hb,
		}

		if _, _, err := c.Send(context.Background(), event); err != nil {
			log.Printf("failed to send cloudevent: %s", err.Error())
		}
		// Wait for next tick
		<-ticker.C
	}
}
<commit_msg>Use K_SINK for where to send events. (#766)<commit_after>/*
Copyright 2018 The Knative Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"
	"time"

	"knative.dev/eventing-contrib/pkg/kncloudevents"

	"github.com/cloudevents/sdk-go/pkg/cloudevents"
	"github.com/cloudevents/sdk-go/pkg/cloudevents/types"
	"github.com/kelseyhightower/envconfig"
)

type Heartbeat struct {
	Sequence int    `json:"id"`
	Label    string `json:"label"`
}

var (
	eventSource string
	eventType   string
	sink        string
	label       string
	periodStr   string
)

func init() {
	flag.StringVar(&eventSource, "eventSource", "", "the event-source (CloudEvents)")
	flag.StringVar(&eventType, "eventType", "dev.knative.eventing.samples.heartbeat", "the event-type (CloudEvents)")
	flag.StringVar(&sink, "sink", "", "the host url to heartbeat to")
	flag.StringVar(&label, "label", "", "a special label")
	flag.StringVar(&periodStr, "period", "5", "the number of seconds between heartbeats")
}

type envConfig struct {
	// Sink URL where to send heartbeat cloudevents
	Sink string `envconfig:"K_SINK"`

	// Name of this pod.
	Name string `envconfig:"POD_NAME" required:"true"`

	// Namespace this pod exists in.
	Namespace string `envconfig:"POD_NAMESPACE" required:"true"`

	// Whether to run continuously or exit.
	OneShot bool `envconfig:"ONE_SHOT" default:"false"`
}

func main() {
	flag.Parse()

	var env envConfig
	if err := envconfig.Process("", &env); err != nil {
		log.Printf("[ERROR] Failed to process env var: %s", err)
		os.Exit(1)
	}

	if env.Sink != "" {
		sink = env.Sink
	}

	c, err := kncloudevents.NewDefaultClient(sink)
	if err != nil {
		log.Fatalf("failed to create client: %s", err.Error())
	}

	var period time.Duration
	if p, err := strconv.Atoi(periodStr); err != nil {
		period = time.Duration(5) * time.Second
	} else {
		period = time.Duration(p) * time.Second
	}

	if eventSource == "" {
		eventSource = fmt.Sprintf("https://knative.dev/eventing-contrib/cmd/heartbeats/#%s/%s", env.Namespace, env.Name)
		log.Printf("Heartbeats Source: %s", eventSource)
	}

	if len(label) > 0 && label[0] == '"' {
		label, _ = strconv.Unquote(label)
	}
	hb := &Heartbeat{
		Sequence: 0,
		Label:    label,
	}
	ticker := time.NewTicker(period)
	for {
		hb.Sequence++

		event := cloudevents.Event{
			Context: cloudevents.EventContextV03{
				Type:   eventType,
				Source: *types.ParseURLRef(eventSource),
				Extensions: map[string]interface{}{
					"the":   42,
					"heart": "yes",
					"beats": true,
				},
			}.AsV02(),
			Data: hb,
		}

		if _, _, err := c.Send(context.Background(), event); err != nil {
			log.Printf("failed to send cloudevent: %s", err.Error())
		}

		if env.OneShot {
			return
		}

		// Wait for next tick
		<-ticker.C
	}
}
<|endoftext|>