<commit_before>/**
 * Copyright 2015 Comcast Cable Communications Management, LLC
 *
 * 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 eellib

import (
	"encoding/json"
	"errors"
	"sync"

	. "github.com/Comcast/eel/eel/jtl"
	. "github.com/Comcast/eel/eel/util"
)

// EELInit initalize environment for EEL API use
func EELInit(ctx Context) {
	Gctx = ctx
	eelSettings := new(EelSettings)
	eelSettings.MaxAttempts = 3
	eelSettings.InitialDelay = 125
	eelSettings.InitialBackoff = 1000
	eelSettings.BackoffMethod = "Exponential"
	eelSettings.HttpTimeout = 1000
	eelSettings.ResponseHeaderTimeout = 1000
	eelSettings.MaxMessageSize = 512000
	eelSettings.HttpTransactionHeader = "X-B3-TraceId"
	eelSettings.HttpTenantHeader = "X-TenantId"
	eelSettings.AppName = "eel"
	eelSettings.Name = "eel"
	eelSettings.Version = "1.0"
	ctx.AddConfigValue(EelConfig, eelSettings)
	eelServiceStats := new(ServiceStats)
	ctx.AddValue(EelTotalStats, eelServiceStats)
	InitHttpTransport(ctx)
}

// EELGetSettings get current settings for read / write
func EELGetSettings(ctx Context) (*EelSettings, error) {
	if Gctx == nil {
		return nil, errors.New("must call EELInit first")
	}
	if ctx == nil {
		return nil, errors.New("ctx cannot be nil")
	}
	if ctx.ConfigValue(EelConfig) == nil {
		return nil, errors.New("no settings")
	}
	return ctx.ConfigValue(EelConfig).(*EelSettings), nil
}

// EELGetSettings get current settings for read / write
func EELUpdateSettings(ctx Context, eelSettings *EelSettings) error {
	if Gctx == nil {
		return errors.New("must call EELInit first")
	}
	if ctx == nil {
		return errors.New("ctx cannot be nil")
	}
	if eelSettings == nil {
		return errors.New("no settings")
	}
	ctx.AddValue(EelConfig, eelSettings)
	InitHttpTransport(ctx)
	return nil
}

// EELNewHandlerFactory creates handler factory for given folder with handler files.
func EELNewHandlerFactory(ctx Context, configFolder string) (*HandlerFactory, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	eelHandlerFactory, warnings := NewHandlerFactory(ctx, []string{configFolder})
	return eelHandlerFactory, warnings
}

// EELGetHandlersForEvent gets all handlers for a given event.
func EELGetHandlersForEvent(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]*HandlerConfiguration, error) {
	if Gctx == nil {
		return nil, errors.New("must call EELInit first")
	}
	if ctx == nil {
		return nil, errors.New("ctx cannot be nil")
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromInterface(event)
	if err != nil {
		return nil, err
	}
	eelMatchingHandlers := eelHandlerFactory.GetHandlersForEvent(ctx, doc)
	return eelMatchingHandlers, nil
}

// EELGetPublishers is similar to EELTransformEvent but return slice of publishers instead of slice of events.
func EELGetPublishers(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]EventPublisher, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromInterface(event)
	if err != nil {
		return nil, []error{err}
	}
	publishers := make([]EventPublisher, 0)
	eelMatchingHandlers := eelHandlerFactory.GetHandlersForEvent(ctx, doc)
	for _, h := range eelMatchingHandlers {
		p, err := h.ProcessEvent(ctx, doc)
		if err != nil {
			return nil, []error{err}
		}
		publishers = append(publishers, p...)
	}
	return publishers, GetErrors(ctx)
}

// EELGetPublishersConcurrent is the concurrent version of EELGetPublishers. Useful when processing multiple
// expensive transformations at the same time (e.g. making heavy use of curl() function calls).
func EELGetPublishersConcurrent(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]EventPublisher, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromInterface(event)
	if err != nil {
		return nil, []error{err}
	}
	eelMatchingHandlers := eelHandlerFactory.GetHandlersForEvent(ctx, doc)
	var mtx sync.Mutex
	var wg sync.WaitGroup
	publishers := make([]EventPublisher, 0)
	errs := make([]error, 0)
	for _, h := range eelMatchingHandlers {
		wg.Add(1)
		go func(h *HandlerConfiguration) {
			sctx := ctx.SubContext()
			d, _ := NewJDocFromInterface(event)
			pp, err := h.ProcessEvent(sctx, d)
			if err != nil {
				mtx.Lock()
				errs = append(errs, err)
				mtx.Unlock()
				wg.Done()
				return
			}
			ee := GetErrors(sctx)
			if ee != nil && len(ee) > 0 {
				mtx.Lock()
				errs = append(errs, ee...)
				mtx.Unlock()
			}
			if pp != nil && len(pp) > 0 {
				mtx.Lock()
				publishers = append(publishers, pp...)
				mtx.Unlock()
			}
			wg.Done()
		}(h)
	}
	wg.Wait()
	if len(errs) > 0 {
		return publishers, errs
	} else {
		return publishers, nil
	}
}

// EELTransformEvent transforms single event based on set of configuration handlers. Can yield multiple results.
func EELTransformEvent(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]interface{}, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	publishers, errs := EELGetPublishers(ctx, event, eelHandlerFactory)
	if errs != nil {
		return nil, errs
	}
	events := make([]interface{}, 0)
	for _, p := range publishers {
		events = append(events, p.GetPayloadParsed().GetOriginalObject())
	}
	return events, GetErrors(ctx)
}

// EELTransformEventConcurrent is the concurrent version of EELTransformEvent. Useful when processing multiple
// expensive transformations at the same time (e.g. making heavy use of curl() function calls).
func EELTransformEventConcurrent(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]interface{}, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	publishers, errs := EELGetPublishersConcurrent(ctx, event, eelHandlerFactory)
	if errs != nil {
		return nil, errs
	}
	events := make([]interface{}, 0)
	for _, p := range publishers {
		events = append(events, p.GetPayloadParsed().GetOriginalObject())
	}
	return events, GetErrors(ctx)
}

// EELSingleTransform can work with raw JSON transformation or a transformation wrapped in a config handler.
// Transformation must yield single result or no result (if filtered).
func EELSimpleTransform(ctx Context, event string, transformation string, isTransformationByExample bool) (string, []error) {
	if Gctx == nil {
		return "", []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return "", []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromString(event)
	if err != nil {
		return "", []error{err}
	}
	tf, err := NewJDocFromString(transformation)
	if err != nil {
		return "", []error{err}
	}
	h := new(HandlerConfiguration)
	err = json.Unmarshal([]byte(transformation), h)
	if err != nil || h.Transformation == nil {
		h.Transformation = tf.GetOriginalObject()
		h.IsTransformationByExample = isTransformationByExample
	}
	if h.Protocol == "" {
		h.Protocol = "http"
	}
	if h.Endpoint == nil {
		h.Endpoint = "http://localhost"
	}
	hf, _ := NewHandlerFactory(ctx, nil)
	h, _ = hf.GetHandlerConfigurationFromJson(ctx, "", *h)
	p, err := h.ProcessEvent(ctx, doc)
	if err != nil {
		return "", []error{err}
	}
	if len(p) > 1 {
		return "", []error{errors.New("transformation must yield single result")}
	} else if len(p) == 0 {
		return "", nil
	} else {
		return p[0].GetPayload(), GetErrors(ctx)
	}
}

// EELSingleTransform can work with raw JSON transformation or a transformation wrapped in a config handler.
// Transformation must yield single result or no result (if filtered).
func EELSimpleEvalExpression(ctx Context, event string, expr string) (string, []error) {
	if Gctx == nil {
		return "", []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return "", []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromString(event)
	if err != nil {
		return "", []error{err}
	}
	result := doc.ParseExpression(ctx, expr)
	if result == nil {
		return "", GetErrors(ctx)
	}
	rdoc, err := NewJDocFromInterface(result)
	if err != nil {
		return "", []error{err}
	}
	return rdoc.StringPretty(), GetErrors(ctx)
}
<commit_msg>adjusted http defaults<commit_after>/**
 * Copyright 2015 Comcast Cable Communications Management, LLC
 *
 * 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 eellib

import (
	"encoding/json"
	"errors"
	"sync"

	. "github.com/Comcast/eel/eel/jtl"
	. "github.com/Comcast/eel/eel/util"
)

// EELInit initalize environment for EEL API use
func EELInit(ctx Context) {
	Gctx = ctx
	eelSettings := new(EelSettings)
	eelSettings.MaxAttempts = 2
	eelSettings.InitialDelay = 125
	eelSettings.InitialBackoff = 3000
	eelSettings.BackoffMethod = "Exponential"
	eelSettings.HttpTimeout = 3000
	eelSettings.ResponseHeaderTimeout = 3000
	eelSettings.MaxMessageSize = 512000
	eelSettings.HttpTransactionHeader = "X-B3-TraceId"
	eelSettings.HttpTenantHeader = "X-TenantId"
	eelSettings.AppName = "eel"
	eelSettings.Name = "eel"
	eelSettings.Version = "1.0"
	ctx.AddConfigValue(EelConfig, eelSettings)
	eelServiceStats := new(ServiceStats)
	ctx.AddValue(EelTotalStats, eelServiceStats)
	InitHttpTransport(ctx)
}

// EELGetSettings get current settings for read / write
func EELGetSettings(ctx Context) (*EelSettings, error) {
	if Gctx == nil {
		return nil, errors.New("must call EELInit first")
	}
	if ctx == nil {
		return nil, errors.New("ctx cannot be nil")
	}
	if ctx.ConfigValue(EelConfig) == nil {
		return nil, errors.New("no settings")
	}
	return ctx.ConfigValue(EelConfig).(*EelSettings), nil
}

// EELGetSettings get current settings for read / write
func EELUpdateSettings(ctx Context, eelSettings *EelSettings) error {
	if Gctx == nil {
		return errors.New("must call EELInit first")
	}
	if ctx == nil {
		return errors.New("ctx cannot be nil")
	}
	if eelSettings == nil {
		return errors.New("no settings")
	}
	ctx.AddValue(EelConfig, eelSettings)
	InitHttpTransport(ctx)
	return nil
}

// EELNewHandlerFactory creates handler factory for given folder with handler files.
func EELNewHandlerFactory(ctx Context, configFolder string) (*HandlerFactory, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	eelHandlerFactory, warnings := NewHandlerFactory(ctx, []string{configFolder})
	return eelHandlerFactory, warnings
}

// EELGetHandlersForEvent gets all handlers for a given event.
func EELGetHandlersForEvent(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]*HandlerConfiguration, error) {
	if Gctx == nil {
		return nil, errors.New("must call EELInit first")
	}
	if ctx == nil {
		return nil, errors.New("ctx cannot be nil")
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromInterface(event)
	if err != nil {
		return nil, err
	}
	eelMatchingHandlers := eelHandlerFactory.GetHandlersForEvent(ctx, doc)
	return eelMatchingHandlers, nil
}

// EELGetPublishers is similar to EELTransformEvent but return slice of publishers instead of slice of events.
func EELGetPublishers(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]EventPublisher, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromInterface(event)
	if err != nil {
		return nil, []error{err}
	}
	publishers := make([]EventPublisher, 0)
	eelMatchingHandlers := eelHandlerFactory.GetHandlersForEvent(ctx, doc)
	for _, h := range eelMatchingHandlers {
		p, err := h.ProcessEvent(ctx, doc)
		if err != nil {
			return nil, []error{err}
		}
		publishers = append(publishers, p...)
	}
	return publishers, GetErrors(ctx)
}

// EELGetPublishersConcurrent is the concurrent version of EELGetPublishers. Useful when processing multiple
// expensive transformations at the same time (e.g. making heavy use of curl() function calls).
func EELGetPublishersConcurrent(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]EventPublisher, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromInterface(event)
	if err != nil {
		return nil, []error{err}
	}
	eelMatchingHandlers := eelHandlerFactory.GetHandlersForEvent(ctx, doc)
	var mtx sync.Mutex
	var wg sync.WaitGroup
	publishers := make([]EventPublisher, 0)
	errs := make([]error, 0)
	for _, h := range eelMatchingHandlers {
		wg.Add(1)
		go func(h *HandlerConfiguration) {
			sctx := ctx.SubContext()
			d, _ := NewJDocFromInterface(event)
			pp, err := h.ProcessEvent(sctx, d)
			if err != nil {
				mtx.Lock()
				errs = append(errs, err)
				mtx.Unlock()
				wg.Done()
				return
			}
			ee := GetErrors(sctx)
			if ee != nil && len(ee) > 0 {
				mtx.Lock()
				errs = append(errs, ee...)
				mtx.Unlock()
			}
			if pp != nil && len(pp) > 0 {
				mtx.Lock()
				publishers = append(publishers, pp...)
				mtx.Unlock()
			}
			wg.Done()
		}(h)
	}
	wg.Wait()
	if len(errs) > 0 {
		return publishers, errs
	} else {
		return publishers, nil
	}
}

// EELTransformEvent transforms single event based on set of configuration handlers. Can yield multiple results.
func EELTransformEvent(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]interface{}, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	publishers, errs := EELGetPublishers(ctx, event, eelHandlerFactory)
	if errs != nil {
		return nil, errs
	}
	events := make([]interface{}, 0)
	for _, p := range publishers {
		events = append(events, p.GetPayloadParsed().GetOriginalObject())
	}
	return events, GetErrors(ctx)
}

// EELTransformEventConcurrent is the concurrent version of EELTransformEvent. Useful when processing multiple
// expensive transformations at the same time (e.g. making heavy use of curl() function calls).
func EELTransformEventConcurrent(ctx Context, event interface{}, eelHandlerFactory *HandlerFactory) ([]interface{}, []error) {
	if Gctx == nil {
		return nil, []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return nil, []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	publishers, errs := EELGetPublishersConcurrent(ctx, event, eelHandlerFactory)
	if errs != nil {
		return nil, errs
	}
	events := make([]interface{}, 0)
	for _, p := range publishers {
		events = append(events, p.GetPayloadParsed().GetOriginalObject())
	}
	return events, GetErrors(ctx)
}

// EELSingleTransform can work with raw JSON transformation or a transformation wrapped in a config handler.
// Transformation must yield single result or no result (if filtered).
func EELSimpleTransform(ctx Context, event string, transformation string, isTransformationByExample bool) (string, []error) {
	if Gctx == nil {
		return "", []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return "", []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromString(event)
	if err != nil {
		return "", []error{err}
	}
	tf, err := NewJDocFromString(transformation)
	if err != nil {
		return "", []error{err}
	}
	h := new(HandlerConfiguration)
	err = json.Unmarshal([]byte(transformation), h)
	if err != nil || h.Transformation == nil {
		h.Transformation = tf.GetOriginalObject()
		h.IsTransformationByExample = isTransformationByExample
	}
	if h.Protocol == "" {
		h.Protocol = "http"
	}
	if h.Endpoint == nil {
		h.Endpoint = "http://localhost"
	}
	hf, _ := NewHandlerFactory(ctx, nil)
	h, _ = hf.GetHandlerConfigurationFromJson(ctx, "", *h)
	p, err := h.ProcessEvent(ctx, doc)
	if err != nil {
		return "", []error{err}
	}
	if len(p) > 1 {
		return "", []error{errors.New("transformation must yield single result")}
	} else if len(p) == 0 {
		return "", nil
	} else {
		return p[0].GetPayload(), GetErrors(ctx)
	}
}

// EELSingleTransform can work with raw JSON transformation or a transformation wrapped in a config handler.
// Transformation must yield single result or no result (if filtered).
func EELSimpleEvalExpression(ctx Context, event string, expr string) (string, []error) {
	if Gctx == nil {
		return "", []error{errors.New("must call EELInit first")}
	}
	if ctx == nil {
		return "", []error{errors.New("ctx cannot be nil")}
	}
	ctx = ctx.SubContext()
	ClearErrors(ctx)
	doc, err := NewJDocFromString(event)
	if err != nil {
		return "", []error{err}
	}
	result := doc.ParseExpression(ctx, expr)
	if result == nil {
		return "", GetErrors(ctx)
	}
	rdoc, err := NewJDocFromInterface(result)
	if err != nil {
		return "", []error{err}
	}
	return rdoc.StringPretty(), GetErrors(ctx)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Print("hello and byee!\n")
	os.Exit(-1)
}
<commit_msg>init cli app<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/urfave/cli"
)

func main() {

	app := cli.NewApp()
	app.Name = "zippy"
	app.Author = "Tugberk Ugurlu"
	app.Usage = "General purpose package distribution tool for your stuff (yes, all your stuff™)"

	app.Action = func(c *cli.Context) error {
		fmt.Print("hello and byee!\n")
		return cli.NewExitError("no pun intended", -1)
	}

	app.Run(os.Args)
}
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package newtutil

import (
	"fmt"
	"io/ioutil"
	"os/user"
	"sort"
	"strconv"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/spf13/cast"

	"mynewt.apache.org/newt/newt/interfaces"
	"mynewt.apache.org/newt/util"
	"mynewt.apache.org/newt/viper"
)

var NewtVersion Version = Version{1, 2, 0}
var NewtVersionStr string = "Apache Newt version: 1.2.0-dev"
var NewtBlinkyTag string = "master"
var NewtNumJobs int
var NewtForce bool

const NEWTRC_DIR string = ".newt"
const REPOS_FILENAME string = "repos.yml"

const CORE_REPO_NAME string = "apache-mynewt-core"
const ARDUINO_ZERO_REPO_NAME string = "mynewt_arduino_zero"

type Version struct {
	Major    int64
	Minor    int64
	Revision int64
}

func ParseVersion(s string) (Version, error) {
	v := Version{}
	parseErr := util.FmtNewtError("Invalid version string: %s", s)

	parts := strings.Split(s, ".")
	if len(parts) != 3 {
		return v, parseErr
	}

	var err error

	v.Major, err = strconv.ParseInt(parts[0], 10, 64)
	if err != nil {
		return v, parseErr
	}

	v.Minor, err = strconv.ParseInt(parts[1], 10, 64)
	if err != nil {
		return v, parseErr
	}

	v.Revision, err = strconv.ParseInt(parts[2], 10, 64)
	if err != nil {
		return v, parseErr
	}

	return v, nil
}

func (v *Version) String() string {
	return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Revision)
}

func VerCmp(v1 Version, v2 Version) int64 {
	if r := v1.Major - v2.Major; r != 0 {
		return r
	}

	if r := v1.Minor - v2.Minor; r != 0 {
		return r
	}

	if r := v1.Revision - v2.Revision; r != 0 {
		return r
	}

	return 0
}

// Contains general newt settings read from $HOME/.newt
var newtrc *viper.Viper

func readNewtrc() *viper.Viper {
	usr, err := user.Current()
	if err != nil {
		return viper.New()
	}

	dir := usr.HomeDir + "/" + NEWTRC_DIR
	v, err := util.ReadConfig(dir, strings.TrimSuffix(REPOS_FILENAME, ".yml"))
	if err != nil {
		log.Debugf("Failed to read %s/%s file", dir, REPOS_FILENAME)
		return viper.New()
	}

	return v
}

func Newtrc() *viper.Viper {
	if newtrc != nil {
		return newtrc
	}

	newtrc = readNewtrc()
	return newtrc
}

func GetSliceFeatures(v *viper.Viper, features map[string]bool,
	key string) []interface{} {

	val := v.Get(key)
	vals := []interface{}{val}

	// Process the features in alphabetical order to ensure consistent
	// results across repeated runs.
	featureKeys := make([]string, 0, len(features))
	for feature, _ := range features {
		featureKeys = append(featureKeys, feature)
	}
	sort.Strings(featureKeys)

	for _, feature := range featureKeys {
		overwriteVal := v.Get(key + "." + feature + ".OVERWRITE")
		if overwriteVal != nil {
			return []interface{}{overwriteVal}
		}

		appendVal := v.Get(key + "." + feature)
		if appendVal != nil {
			vals = append(vals, appendVal)
		}
	}

	return vals
}

func GetStringMapFeatures(v *viper.Viper, features map[string]bool,
	key string) map[string]interface{} {

	result := map[string]interface{}{}

	slice := GetSliceFeatures(v, features, key)
	for _, itf := range slice {
		sub := cast.ToStringMap(itf)
		for k, v := range sub {
			result[k] = v
		}
	}

	return result
}

func GetStringFeatures(v *viper.Viper, features map[string]bool,
	key string) string {
	val := v.GetString(key)

	// Process the features in alphabetical order to ensure consistent
	// results across repeated runs.
	var featureKeys []string
	for feature, _ := range features {
		featureKeys = append(featureKeys, feature)
	}
	sort.Strings(featureKeys)

	for _, feature := range featureKeys {
		overwriteVal := v.GetString(key + "." + feature + ".OVERWRITE")
		if overwriteVal != "" {
			val = strings.Trim(overwriteVal, "\n")
			break
		}

		appendVal := v.GetString(key + "." + feature)
		if appendVal != "" {
			val += " " + strings.Trim(appendVal, "\n")
		}
	}
	return strings.TrimSpace(val)
}

func GetBoolFeaturesDflt(v *viper.Viper, features map[string]bool,
	key string, dflt bool) (bool, error) {

	s := GetStringFeatures(v, features, key)
	if s == "" {
		return dflt, nil
	}

	b, err := strconv.ParseBool(s)
	if err != nil {
		return dflt, util.FmtNewtError("invalid bool value for %s: %s",
			key, s)
	}

	return b, nil
}

func GetBoolFeatures(v *viper.Viper, features map[string]bool,
	key string) (bool, error) {

	return GetBoolFeaturesDflt(v, features, key, false)
}

func GetStringSliceFeatures(v *viper.Viper, features map[string]bool,
	key string) []string {

	vals := GetSliceFeatures(v, features, key)

	strVals := []string{}
	for _, v := range vals {
		subVals := cast.ToStringSlice(v)
		strVals = append(strVals, subVals...)
	}

	return strVals
}

// Parses a string of the following form:
//     [@repo]<path/to/package>
//
// @return string               repo name ("" if no repo)
//         string               package name
//         error                if invalid package string
func ParsePackageString(pkgStr string) (string, string, error) {
	// remove possible trailing '/'
	pkgStr = strings.TrimSuffix(pkgStr, "/")

	if strings.HasPrefix(pkgStr, "@") {
		nameParts := strings.SplitN(pkgStr[1:], "/", 2)
		if len(nameParts) == 1 {
			return "", "", util.NewNewtError(fmt.Sprintf("Invalid package "+
				"string; contains repo but no package name: %s", pkgStr))
		} else {
			return nameParts[0], nameParts[1], nil
		}
	} else {
		return "", pkgStr, nil
	}
}

func FindRepoDesignator(s string) (int, int) {
	start := strings.Index(s, "@")
	if start == -1 {
		return -1, -1
	}

	len := strings.Index(s[start:], "/")
	if len == -1 {
		return -1, -1
	}

	return start, len
}

func ReplaceRepoDesignators(s string) (string, bool) {
	start, len := FindRepoDesignator(s)
	if start == -1 {
		return s, false
	}
	repoName := s[start+1 : start+len]

	proj := interfaces.GetProject()
	repoPath := proj.FindRepoPath(repoName)
	if repoPath == "" {
		return s, false
	}

	// Trim common project base from repo path.
	relRepoPath := strings.TrimPrefix(repoPath, proj.Path()+"/")

	return s[:start] + relRepoPath + s[start+len:], true
}

func BuildPackageString(repoName string, pkgName string) string {
	if repoName != "" {
		return "@" + repoName + "/" + pkgName
	} else {
		return pkgName
	}
}

func GeneratedPreamble() string {
	return fmt.Sprintf("/**\n * This file was generated by %s\n */\n\n",
		NewtVersionStr)
}

// Creates a temporary directory for downloading a repo.
func MakeTempRepoDir() (string, error) {
	tmpdir, err := ioutil.TempDir("", "newt-repo")
	if err != nil {
		return "", util.ChildNewtError(err)
	}

	return tmpdir, nil
}
<commit_msg>Update release to 1.3.0<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package newtutil

import (
	"fmt"
	"io/ioutil"
	"os/user"
	"sort"
	"strconv"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/spf13/cast"

	"mynewt.apache.org/newt/newt/interfaces"
	"mynewt.apache.org/newt/util"
	"mynewt.apache.org/newt/viper"
)

var NewtVersion Version = Version{1, 3, 0}
var NewtVersionStr string = "Apache Newt version: 1.3.0-dev"
var NewtBlinkyTag string = "mynewt_1_3_0_tag"
var NewtNumJobs int
var NewtForce bool

const NEWTRC_DIR string = ".newt"
const REPOS_FILENAME string = "repos.yml"

const CORE_REPO_NAME string = "apache-mynewt-core"
const ARDUINO_ZERO_REPO_NAME string = "mynewt_arduino_zero"

type Version struct {
	Major    int64
	Minor    int64
	Revision int64
}

func ParseVersion(s string) (Version, error) {
	v := Version{}
	parseErr := util.FmtNewtError("Invalid version string: %s", s)

	parts := strings.Split(s, ".")
	if len(parts) != 3 {
		return v, parseErr
	}

	var err error

	v.Major, err = strconv.ParseInt(parts[0], 10, 64)
	if err != nil {
		return v, parseErr
	}

	v.Minor, err = strconv.ParseInt(parts[1], 10, 64)
	if err != nil {
		return v, parseErr
	}

	v.Revision, err = strconv.ParseInt(parts[2], 10, 64)
	if err != nil {
		return v, parseErr
	}

	return v, nil
}

func (v *Version) String() string {
	return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Revision)
}

func VerCmp(v1 Version, v2 Version) int64 {
	if r := v1.Major - v2.Major; r != 0 {
		return r
	}

	if r := v1.Minor - v2.Minor; r != 0 {
		return r
	}

	if r := v1.Revision - v2.Revision; r != 0 {
		return r
	}

	return 0
}

// Contains general newt settings read from $HOME/.newt
var newtrc *viper.Viper

func readNewtrc() *viper.Viper {
	usr, err := user.Current()
	if err != nil {
		return viper.New()
	}

	dir := usr.HomeDir + "/" + NEWTRC_DIR
	v, err := util.ReadConfig(dir, strings.TrimSuffix(REPOS_FILENAME, ".yml"))
	if err != nil {
		log.Debugf("Failed to read %s/%s file", dir, REPOS_FILENAME)
		return viper.New()
	}

	return v
}

func Newtrc() *viper.Viper {
	if newtrc != nil {
		return newtrc
	}

	newtrc = readNewtrc()
	return newtrc
}

func GetSliceFeatures(v *viper.Viper, features map[string]bool,
	key string) []interface{} {

	val := v.Get(key)
	vals := []interface{}{val}

	// Process the features in alphabetical order to ensure consistent
	// results across repeated runs.
	featureKeys := make([]string, 0, len(features))
	for feature, _ := range features {
		featureKeys = append(featureKeys, feature)
	}
	sort.Strings(featureKeys)

	for _, feature := range featureKeys {
		overwriteVal := v.Get(key + "." + feature + ".OVERWRITE")
		if overwriteVal != nil {
			return []interface{}{overwriteVal}
		}

		appendVal := v.Get(key + "." + feature)
		if appendVal != nil {
			vals = append(vals, appendVal)
		}
	}

	return vals
}

func GetStringMapFeatures(v *viper.Viper, features map[string]bool,
	key string) map[string]interface{} {

	result := map[string]interface{}{}

	slice := GetSliceFeatures(v, features, key)
	for _, itf := range slice {
		sub := cast.ToStringMap(itf)
		for k, v := range sub {
			result[k] = v
		}
	}

	return result
}

func GetStringFeatures(v *viper.Viper, features map[string]bool,
	key string) string {
	val := v.GetString(key)

	// Process the features in alphabetical order to ensure consistent
	// results across repeated runs.
	var featureKeys []string
	for feature, _ := range features {
		featureKeys = append(featureKeys, feature)
	}
	sort.Strings(featureKeys)

	for _, feature := range featureKeys {
		overwriteVal := v.GetString(key + "." + feature + ".OVERWRITE")
		if overwriteVal != "" {
			val = strings.Trim(overwriteVal, "\n")
			break
		}

		appendVal := v.GetString(key + "." + feature)
		if appendVal != "" {
			val += " " + strings.Trim(appendVal, "\n")
		}
	}
	return strings.TrimSpace(val)
}

func GetBoolFeaturesDflt(v *viper.Viper, features map[string]bool,
	key string, dflt bool) (bool, error) {

	s := GetStringFeatures(v, features, key)
	if s == "" {
		return dflt, nil
	}

	b, err := strconv.ParseBool(s)
	if err != nil {
		return dflt, util.FmtNewtError("invalid bool value for %s: %s",
			key, s)
	}

	return b, nil
}

func GetBoolFeatures(v *viper.Viper, features map[string]bool,
	key string) (bool, error) {

	return GetBoolFeaturesDflt(v, features, key, false)
}

func GetStringSliceFeatures(v *viper.Viper, features map[string]bool,
	key string) []string {

	vals := GetSliceFeatures(v, features, key)

	strVals := []string{}
	for _, v := range vals {
		subVals := cast.ToStringSlice(v)
		strVals = append(strVals, subVals...)
	}

	return strVals
}

// Parses a string of the following form:
//     [@repo]<path/to/package>
//
// @return string               repo name ("" if no repo)
//         string               package name
//         error                if invalid package string
func ParsePackageString(pkgStr string) (string, string, error) {
	// remove possible trailing '/'
	pkgStr = strings.TrimSuffix(pkgStr, "/")

	if strings.HasPrefix(pkgStr, "@") {
		nameParts := strings.SplitN(pkgStr[1:], "/", 2)
		if len(nameParts) == 1 {
			return "", "", util.NewNewtError(fmt.Sprintf("Invalid package "+
				"string; contains repo but no package name: %s", pkgStr))
		} else {
			return nameParts[0], nameParts[1], nil
		}
	} else {
		return "", pkgStr, nil
	}
}

func FindRepoDesignator(s string) (int, int) {
	start := strings.Index(s, "@")
	if start == -1 {
		return -1, -1
	}

	len := strings.Index(s[start:], "/")
	if len == -1 {
		return -1, -1
	}

	return start, len
}

func ReplaceRepoDesignators(s string) (string, bool) {
	start, len := FindRepoDesignator(s)
	if start == -1 {
		return s, false
	}
	repoName := s[start+1 : start+len]

	proj := interfaces.GetProject()
	repoPath := proj.FindRepoPath(repoName)
	if repoPath == "" {
		return s, false
	}

	// Trim common project base from repo path.
	relRepoPath := strings.TrimPrefix(repoPath, proj.Path()+"/")

	return s[:start] + relRepoPath + s[start+len:], true
}

func BuildPackageString(repoName string, pkgName string) string {
	if repoName != "" {
		return "@" + repoName + "/" + pkgName
	} else {
		return pkgName
	}
}

func GeneratedPreamble() string {
	return fmt.Sprintf("/**\n * This file was generated by %s\n */\n\n",
		NewtVersionStr)
}

// Creates a temporary directory for downloading a repo.
func MakeTempRepoDir() (string, error) {
	tmpdir, err := ioutil.TempDir("", "newt-repo")
	if err != nil {
		return "", util.ChildNewtError(err)
	}

	return tmpdir, nil
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"path/filepath"
	"sync"
)

type conch struct {
	fig  *fileInfoGroup
	done chan struct{}
	out  chan fileOutput
	err  chan error
}

// newConch returns a pointer to a new conch with channels setup.
func newConch(fig *fileInfoGroup) *conch {
	return &conch{
		fig:  fig,
		done: make(chan struct{}),
		out:  make(chan fileOutput),
		err:  make(chan error, 1),
	}
}

// doneChan returns the conch done channel.
func (c *conch) doneChan() chan struct{} {
	return c.done
}

// feedPaths is a generator that sends paths out to digest goroutines.
func (c *conch) feedPaths(paths chan string) {
	for _, v := range c.fig.fsi {
		select {
		case paths <- filepath.Join(c.fig.dir, v.Name()):
		case <-c.done:
			c.err <- errors.New("canceled")
		}
	}

	close(paths)
}

// fanout sets-up digest goroutines according to width.
func (c *conch) fanout(paths chan string) {
	var wg sync.WaitGroup
	wg.Add(width)

	// setup digesters by width
	for i := 0; i < width; i++ {
		go func() {
			digest(c.done, paths, c.out)
			wg.Done()
		}()
	}

	wg.Wait()
	close(c.out)
}

// run wires up the paths chan, calls the path generator, calls the fanout, and
// returns the out and err channels.
func (c *conch) run() (<-chan fileOutput, <-chan error) {
	paths := make(chan string)

	go c.feedPaths(paths)
	go c.fanout(paths)

	return c.out, c.err
}
<commit_msg>Improve conch comments.<commit_after>package main

import (
	"errors"
	"path/filepath"
	"sync"
)

// conch holds a file info group, and done, out, and err channels.
type conch struct {
	fig  *fileInfoGroup
	done chan struct{}
	out  chan fileOutput
	err  chan error
}

// newConch returns a pointer to a new conch with channels setup.
func newConch(fig *fileInfoGroup) *conch {
	return &conch{
		fig:  fig,
		done: make(chan struct{}),
		out:  make(chan fileOutput),
		err:  make(chan error, 1),
	}
}

// doneChan returns the conch done channel.
func (c *conch) doneChan() chan struct{} {
	return c.done
}

// feedPaths is a generator that sends paths out for processing. If canceled,
// an error is returned.
func (c *conch) feedPaths(paths chan string) {
	for _, v := range c.fig.fsi {
		select {
		case paths <- filepath.Join(c.fig.dir, v.Name()):
		case <-c.done:
			c.err <- errors.New("canceled")
		}
	}

	close(paths)
}

// fanout sets-up digest goroutines according to width. Each digest goroutine
// waits for data from the paths channel and the entire function collapses when
// completed.
func (c *conch) fanout(paths chan string) {
	var wg sync.WaitGroup
	wg.Add(width)

	// setup digesters by width
	for i := 0; i < width; i++ {
		go func() {
			digest(c.done, paths, c.out)
			wg.Done()
		}()
	}

	wg.Wait()
	close(c.out)
}

// run wires up the paths chan, calls the path generator, calls the fanout, and
// returns the out and err channels.
func (c *conch) run() (<-chan fileOutput, <-chan error) {
	paths := make(chan string)

	go c.feedPaths(paths)
	go c.fanout(paths)

	return c.out, c.err
}
<|endoftext|>


<commit_before>package frisby

import (
	"fmt"
	"reflect"
	"strings"

	"github.com/bitly/go-simplejson"
)

// Checks the response status code
func (F *Frisby) ExpectStatus(code int) *Frisby {
	Global.NumAsserts++
	status := F.Resp.StatusCode
	if status != code {
		err_str := fmt.Sprintf("Expected Status %d, but got %d: %q", code, status, F.Resp.Status)
		F.AddError(err_str)
	}
	return F
}

// Checks for header and if values match
func (F *Frisby) ExpectHeader(key, value string) *Frisby {
	Global.NumAsserts++
	chk_val := F.Resp.Header.Get(key)
	if chk_val == "" {
		err_str := fmt.Sprintf("Expected Header %q, but it was missing", key)
		F.AddError(err_str)
	} else if chk_val != value {
		err_str := fmt.Sprintf("Expected Header %q to be %q, but got %q", key, value, chk_val)
		F.AddError(err_str)
	}
	return F
}

// Checks the response body for the given string
func (F *Frisby) ExpectContent(content string) *Frisby {
	Global.NumAsserts++
	text, err := F.Resp.Text()
	if err != nil {
		F.AddError(err.Error())
		return F
	}
	contains := strings.Contains(text, content)
	if !contains {
		err_str := fmt.Sprintf("Expected Body to contain %q, but it was missing", content)
		F.AddError(err_str)
	}
	return F
}

// ExpectJson uses the reflect.DeepEqual to compare the response
// JSON and the supplied JSON for structural and value equality
//
// path can be a dot joined field names.
// ex:  'path.to.subobject.field'
func (F *Frisby) ExpectJson(path string, value interface{}) *Frisby {
	Global.NumAsserts++
	simp_json, err := F.Resp.Json()
	if err != nil {
		F.AddError(err.Error())
		return F
	}

	if path != "" {
		path_items := strings.Split(path, ".")
		simp_json = simp_json.GetPath(path_items...)
	}
	json := simp_json.Interface()

	equal := false
	switch reflect.ValueOf(value).Kind() {
	case reflect.Int:
		val, err := simp_json.Int()
		if err != nil {
			F.AddError(err.Error())
			return F
		} else {
			equal = (val == value.(int))
		}
	case reflect.Float64:
		val, err := simp_json.Float64()
		if err != nil {
			F.AddError(err.Error())
			return F
		} else {
			equal = (val == value.(float64))
		}
	default:
		equal = reflect.DeepEqual(value, json)
	}

	if !equal {
		err_str := fmt.Sprintf("ExpectJson equality test failed for %q, got type: %v", path, reflect.TypeOf(json))
		F.AddError(err_str)
	}

	return F
}

// ExpectJsonType checks if the types of the response
// JSON and the supplied JSON match
//
// path can be a dot joined field names.
// ex:  'path.to.subobject.field'
func (F *Frisby) ExpectJsonType(path string, val_type reflect.Kind) *Frisby {
	Global.NumAsserts++
	json, err := F.Resp.Json()
	if err != nil {
		F.AddError(err.Error())
		return F
	}

	if path != "" {
		path_items := strings.Split(path, ".")
		json = json.GetPath(path_items...)
	}

	json_json := json.Interface()

	json_val := reflect.ValueOf(json_json)
	if val_type != json_val.Kind() {
		err_str := fmt.Sprintf("Expect Json %q type to be %q, but got %q", path, val_type, json_val.Type())
		F.AddError(err_str)
	}

	return F
}

// ExpectJsonLength checks if the JSON at path
// is an array and has the correct length
//
// path can be a dot joined field names.
// ex:  'path.to.subobject.field'
func (F *Frisby) ExpectJsonLength(path string, length int) *Frisby {
	Global.NumAsserts++
	json, err := F.Resp.Json()
	if err != nil {
		F.AddError(err.Error())
		return F
	}

	if path != "" {
		path_items := strings.Split(path, ".")
		json = json.GetPath(path_items...)
	}

	ary, err := json.Array()
	if err != nil {
		F.AddError(err.Error())
		return F
	}
	L := len(ary)

	if L != length {
		err_str := fmt.Sprintf("Expect length to be %d, but got %d", length, L)
		F.AddError(err_str)
	}

	return F
}

// function type used as argument to AfterContent()
type AfterContentFunc func(F *Frisby, content []byte, err error)

// AfterContent allows you to write your own functions for inspecting the body of the response.
// You are also provided with the Frisby object.
//
// The function signiture is AfterContentFunc
//  type AfterContentFunc func(F *Frisby, content []byte, err error)
//
func (F *Frisby) AfterContent(foo AfterContentFunc) *Frisby {
	content, err := F.Resp.Content()
	foo(F, content, err)
	return F
}

// function type used as argument to AfterText()
type AfterTextFunc func(F *Frisby, text string, err error)

// AfterText allows you to write your own functions for inspecting the body of the response.
// You are also provided with the Frisby object.
//
// The function signiture is AfterTextFunc
//  type AfterTextFunc func(F *Frisby, text string, err error)
//
func (F *Frisby) AfterText(foo AfterTextFunc) *Frisby {
	text, err := F.Resp.Text()
	foo(F, text, err)
	return F
}

// function type used as argument to AfterJson()
type AfterJsonFunc func(F *Frisby, json *simplejson.Json, err error)

// AfterJson allows you to write your own functions for inspecting the body of the response.
// You are also provided with the Frisby object.
//
// The function signiture is AfterJsonFunc
//  type AfterJsonFunc func(F *Frisby, json *simplejson.Json, err error)
//
// simplejson docs: https://github.com/bitly/go-simplejson
func (F *Frisby) AfterJson(foo AfterJsonFunc) *Frisby {
	json, err := F.Resp.Json()
	foo(F, json, err)
	return F
}

// Prints the body of the response
func (F *Frisby) PrintBody() *Frisby {
	str, err := F.Resp.Text()
	if err != nil {
		F.AddError(err.Error())
		return F
	}
	fmt.Println(str)
	return F
}

// Prints a report for the Frisby Object
//
// If there are any errors, they will all be printed as well
func (F *Frisby) PrintReport() *Frisby {
	if len(F.Errs) == 0 {
		fmt.Printf("Pass  [%s]\n", F.Name)
	} else {
		fmt.Printf("FAIL  [%s]\n", F.Name)
		for _, e := range F.Errs {
			fmt.Println("        - ", e)
		}
	}

	return F
}
<commit_msg>ExpectJson paths can access array items<commit_after>package frisby

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"

	"github.com/bitly/go-simplejson"
)

// Checks the response status code
func (F *Frisby) ExpectStatus(code int) *Frisby {
	Global.NumAsserts++
	status := F.Resp.StatusCode
	if status != code {
		err_str := fmt.Sprintf("Expected Status %d, but got %d: %q", code, status, F.Resp.Status)
		F.AddError(err_str)
	}
	return F
}

// Checks for header and if values match
func (F *Frisby) ExpectHeader(key, value string) *Frisby {
	Global.NumAsserts++
	chk_val := F.Resp.Header.Get(key)
	if chk_val == "" {
		err_str := fmt.Sprintf("Expected Header %q, but it was missing", key)
		F.AddError(err_str)
	} else if chk_val != value {
		err_str := fmt.Sprintf("Expected Header %q to be %q, but got %q", key, value, chk_val)
		F.AddError(err_str)
	}
	return F
}

// Checks the response body for the given string
func (F *Frisby) ExpectContent(content string) *Frisby {
	Global.NumAsserts++
	text, err := F.Resp.Text()
	if err != nil {
		F.AddError(err.Error())
		return F
	}
	contains := strings.Contains(text, content)
	if !contains {
		err_str := fmt.Sprintf("Expected Body to contain %q, but it was missing", content)
		F.AddError(err_str)
	}
	return F
}

// ExpectJson uses the reflect.DeepEqual to compare the response
// JSON and the supplied JSON for structural and value equality
//
// path can be a dot joined field names.
// ex:  'path.to.subobject.field'
func (F *Frisby) ExpectJson(path string, value interface{}) *Frisby {
	Global.NumAsserts++
	simp_json, err := F.Resp.Json()
	if err != nil {
		F.AddError(err.Error())
		return F
	}

	if path != "" {
		// Loop over each path item and progress down the json path.
		for _, segment := range strings.Split(path, ".") {
			processed := false
			// If the path segment is an integer, and we're at an array, access the index.
			index, err := strconv.Atoi(segment)
			if err == nil {
				if _, err := simp_json.Array(); err == nil {
					simp_json = simp_json.GetIndex(index)
					processed = true
				}
			}

			if !processed {
				simp_json = simp_json.Get(segment)
			}
		}
	}
	json := simp_json.Interface()

	equal := false
	switch reflect.ValueOf(value).Kind() {
	case reflect.Int:
		val, err := simp_json.Int()
		if err != nil {
			F.AddError(err.Error())
			return F
		} else {
			equal = (val == value.(int))
		}
	case reflect.Float64:
		val, err := simp_json.Float64()
		if err != nil {
			F.AddError(err.Error())
			return F
		} else {
			equal = (val == value.(float64))
		}
	default:
		equal = reflect.DeepEqual(value, json)
	}

	if !equal {
		err_str := fmt.Sprintf("ExpectJson equality test failed for %q, got type: %v", path, reflect.TypeOf(json))
		F.AddError(err_str)
	}

	return F
}

// ExpectJsonType checks if the types of the response
// JSON and the supplied JSON match
//
// path can be a dot joined field names.
// ex:  'path.to.subobject.field'
func (F *Frisby) ExpectJsonType(path string, val_type reflect.Kind) *Frisby {
	Global.NumAsserts++
	json, err := F.Resp.Json()
	if err != nil {
		F.AddError(err.Error())
		return F
	}

	if path != "" {
		path_items := strings.Split(path, ".")
		json = json.GetPath(path_items...)
	}

	json_json := json.Interface()

	json_val := reflect.ValueOf(json_json)
	if val_type != json_val.Kind() {
		err_str := fmt.Sprintf("Expect Json %q type to be %q, but got %q", path, val_type, json_val.Type())
		F.AddError(err_str)
	}

	return F
}

// ExpectJsonLength checks if the JSON at path
// is an array and has the correct length
//
// path can be a dot joined field names.
// ex:  'path.to.subobject.field'
func (F *Frisby) ExpectJsonLength(path string, length int) *Frisby {
	Global.NumAsserts++
	json, err := F.Resp.Json()
	if err != nil {
		F.AddError(err.Error())
		return F
	}

	if path != "" {
		path_items := strings.Split(path, ".")
		json = json.GetPath(path_items...)
	}

	ary, err := json.Array()
	if err != nil {
		F.AddError(err.Error())
		return F
	}
	L := len(ary)

	if L != length {
		err_str := fmt.Sprintf("Expect length to be %d, but got %d", length, L)
		F.AddError(err_str)
	}

	return F
}

// function type used as argument to AfterContent()
type AfterContentFunc func(F *Frisby, content []byte, err error)

// AfterContent allows you to write your own functions for inspecting the body of the response.
// You are also provided with the Frisby object.
//
// The function signiture is AfterContentFunc
//  type AfterContentFunc func(F *Frisby, content []byte, err error)
//
func (F *Frisby) AfterContent(foo AfterContentFunc) *Frisby {
	content, err := F.Resp.Content()
	foo(F, content, err)
	return F
}

// function type used as argument to AfterText()
type AfterTextFunc func(F *Frisby, text string, err error)

// AfterText allows you to write your own functions for inspecting the body of the response.
// You are also provided with the Frisby object.
//
// The function signiture is AfterTextFunc
//  type AfterTextFunc func(F *Frisby, text string, err error)
//
func (F *Frisby) AfterText(foo AfterTextFunc) *Frisby {
	text, err := F.Resp.Text()
	foo(F, text, err)
	return F
}

// function type used as argument to AfterJson()
type AfterJsonFunc func(F *Frisby, json *simplejson.Json, err error)

// AfterJson allows you to write your own functions for inspecting the body of the response.
// You are also provided with the Frisby object.
//
// The function signiture is AfterJsonFunc
//  type AfterJsonFunc func(F *Frisby, json *simplejson.Json, err error)
//
// simplejson docs: https://github.com/bitly/go-simplejson
func (F *Frisby) AfterJson(foo AfterJsonFunc) *Frisby {
	json, err := F.Resp.Json()
	foo(F, json, err)
	return F
}

// Prints the body of the response
func (F *Frisby) PrintBody() *Frisby {
	str, err := F.Resp.Text()
	if err != nil {
		F.AddError(err.Error())
		return F
	}
	fmt.Println(str)
	return F
}

// Prints a report for the Frisby Object
//
// If there are any errors, they will all be printed as well
func (F *Frisby) PrintReport() *Frisby {
	if len(F.Errs) == 0 {
		fmt.Printf("Pass  [%s]\n", F.Name)
	} else {
		fmt.Printf("FAIL  [%s]\n", F.Name)
		for _, e := range F.Errs {
			fmt.Println("        - ", e)
		}
	}

	return F
}
<|endoftext|>


<commit_before>package debug

import (
	proto "github.com/micro/go-micro/server/debug/proto"

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

// The debug handler represents an internal server handler
// used to determine health, status and env info about
// a service node. It's akin to Google's /statusz, /healthz,
// and /varz
type DebugHandler interface {
	Health(ctx context.Context, req *proto.HealthRequest, rsp *proto.HealthResponse) error
}

// Our own internal handler
type debug struct{}

var (
	DefaultDebugHandler = new(debug)
)

func (d *debug) Health(ctx context.Context, req *proto.HealthRequest, rsp *proto.HealthResponse) error {
	rsp.Status = "ok"
	return nil
}
<commit_msg>Debug: use the DebugHandler interface.<commit_after>package debug

import (
	proto "github.com/micro/go-micro/server/debug/proto"

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

// The debug handler represents an internal server handler
// used to determine health, status and env info about
// a service node. It's akin to Google's /statusz, /healthz,
// and /varz
type DebugHandler interface {
	Health(ctx context.Context, req *proto.HealthRequest, rsp *proto.HealthResponse) error
}

// Our own internal handler
type debug struct{}

var (
	DefaultDebugHandler DebugHandler = new(debug)
)

func (d *debug) Health(ctx context.Context, req *proto.HealthRequest, rsp *proto.HealthResponse) error {
	rsp.Status = "ok"
	return nil
}
<|endoftext|>


<commit_before>package nodefs

import (
	"io/ioutil"
	"testing"

	"github.com/hanwen/go-fuse/fuse"
)

type nodeReadNode struct {
	Node
	data []byte
}

func newNodeReadNode(d []byte) *nodeReadNode {
	return &nodeReadNode{NewDefaultNode(), d}
}

func (n *nodeReadNode) Open(flags uint32, context *fuse.Context) (file File, code fuse.Status) {
	return nil, fuse.OK
}

func (n *nodeReadNode) Read(file File, dest []byte, off int64, context *fuse.Context) (fuse.ReadResult, fuse.Status) {
	e := off + int64(len(dest))
	if int(e) > len(n.data) {
		e = int64(len(n.data))
	}
	return fuse.ReadResultData(n.data[off:int(e)]), fuse.OK
}

func (n *nodeReadNode) Lookup(out *fuse.Attr, name string, context *fuse.Context) (*Inode, fuse.Status) {
	out.Mode = fuse.S_IFREG | 0644
	out.Size = uint64(len(name))
	ch := n.Inode().NewChild(name, false, newNodeReadNode([]byte(name)))
	return ch, fuse.OK
}

func TestNodeRead(t *testing.T) {
	dir, err := ioutil.TempDir("", "nodefs")
	if err != nil {
		t.Fatalf("TempDir: %v", err)
	}

	root := newNodeReadNode([]byte("root"))
	s, _, err := MountRoot(dir, root, nil)
	if err != nil {
		t.Fatalf("MountRoot: %v", err)
	}
	s.SetDebug(true)
	go s.Serve()
	defer s.Unmount()
	content, err := ioutil.ReadFile(dir + "/file")
	if err != nil {
		t.Fatalf("MountRoot: %v", err)
	}
	want := "file"
	if string(content) != want {
		t.Fatalf("got %q, want %q", content, want)
	}
}
<commit_msg>fuse/nodefs: fix typo in fileless_test.<commit_after>package nodefs

import (
	"io/ioutil"
	"testing"

	"github.com/hanwen/go-fuse/fuse"
)

type nodeReadNode struct {
	Node
	data []byte
}

func newNodeReadNode(d []byte) *nodeReadNode {
	return &nodeReadNode{NewDefaultNode(), d}
}

func (n *nodeReadNode) Open(flags uint32, context *fuse.Context) (file File, code fuse.Status) {
	return nil, fuse.OK
}

func (n *nodeReadNode) Read(file File, dest []byte, off int64, context *fuse.Context) (fuse.ReadResult, fuse.Status) {
	e := off + int64(len(dest))
	if int(e) > len(n.data) {
		e = int64(len(n.data))
	}
	return fuse.ReadResultData(n.data[off:int(e)]), fuse.OK
}

func (n *nodeReadNode) Lookup(out *fuse.Attr, name string, context *fuse.Context) (*Inode, fuse.Status) {
	out.Mode = fuse.S_IFREG | 0644
	out.Size = uint64(len(name))
	ch := n.Inode().NewChild(name, false, newNodeReadNode([]byte(name)))
	return ch, fuse.OK
}

func TestNodeRead(t *testing.T) {
	dir, err := ioutil.TempDir("", "nodefs")
	if err != nil {
		t.Fatalf("TempDir: %v", err)
	}

	root := newNodeReadNode(nil)
	s, _, err := MountRoot(dir, root, nil)
	if err != nil {
		t.Fatalf("MountRoot: %v", err)
	}
	defer s.Unmount()
	go s.Serve()
	content, err := ioutil.ReadFile(dir + "/file")
	if err != nil {
		t.Fatalf("ReadFile: %v", err)
	}
	want := "file"
	if string(content) != want {
		t.Fatalf("got %q, want %q", content, want)
	}
}
<|endoftext|>


<commit_before>// Clock counts down to or up from a target time.
package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	target := time.Date(2018, 9, 22, 21, 54, 0, 0, time.Local)
	motto := "Just Go"
	printTargetTime(target, motto)
	exitOnEnterKey()

	var previous time.Time
	for {
		now := time.Now().Truncate(time.Second)
		if now != previous {
			previous = now
			countdown := now.Sub(target) // Negative times are before the target
			printCountdown(now, countdown)
		}
		time.Sleep(100 * time.Millisecond)
	}
}

func exitOnEnterKey() {
	go func() {
		buf := make([]byte, 1)
		_, _ = os.Stdin.Read(buf)
		os.Exit(0)
	}()
}

const (
	highlightStart = "\x1b[1;35m"
	highlightEnd   = "\x1b[0m"
	indent         = "\t"
)

func printTargetTime(target time.Time, motto string) {
	fmt.Print(indent, highlightStart, motto, highlightEnd, "\n")
	fmt.Print(indent, target.Format(time.UnixDate), "\n")
}

func printCountdown(now time.Time, countdown time.Duration) {
	var sign string
	if countdown >= 0 {
		sign = "+"
	} else {
		sign = "-"
		countdown = -countdown
	}

	days := int(countdown / (24 * time.Hour))
	countdown = countdown % (24 * time.Hour)

	fmt.Print(indent, now.Format(time.UnixDate), "  ", sign)
	if days > 0 {
		fmt.Print(days, "d")
	}
	fmt.Print(countdown, "          \r")
	os.Stdout.Sync()
}
<commit_msg>Arch Linux on Pixel<commit_after>// Clock counts down to or up from a target time.
package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	target := time.Date(2018, 9, 12, 21, 40, 37, 0, time.Local)
	motto := "Just Go"
	printTargetTime(target, motto)
	exitOnEnterKey()

	var previous time.Time
	for {
		now := time.Now().Truncate(time.Second)
		if now != previous {
			previous = now
			countdown := now.Sub(target) // Negative times are before the target
			printCountdown(now, countdown)
		}
		time.Sleep(100 * time.Millisecond)
	}
}

func exitOnEnterKey() {
	go func() {
		buf := make([]byte, 1)
		_, _ = os.Stdin.Read(buf)
		os.Exit(0)
	}()
}

const (
	highlightStart = "\x1b[1;35m"
	highlightEnd   = "\x1b[0m"
	indent         = "\t"
)

func printTargetTime(target time.Time, motto string) {
	fmt.Print(indent, highlightStart, motto, highlightEnd, "\n")
	fmt.Print(indent, target.Format(time.UnixDate), "\n")
}

func printCountdown(now time.Time, countdown time.Duration) {
	var sign string
	if countdown >= 0 {
		sign = "+"
	} else {
		sign = "-"
		countdown = -countdown
	}

	days := int(countdown / (24 * time.Hour))
	countdown = countdown % (24 * time.Hour)

	fmt.Print(indent, now.Format(time.UnixDate), "  ", sign)
	if days > 0 {
		fmt.Print(days, "d")
	}
	fmt.Print(countdown, "          \r")
	os.Stdout.Sync()
}
<|endoftext|>


<commit_before>/*
 *
 * k6 - a next-generation load testing tool
 * Copyright (C) 2016 Load Impact
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package lib

import (
	"crypto/md5"
	"encoding/hex"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"
	"gopkg.in/guregu/null.v3"
)

const groupSeparator = "::"

var ErrNameContainsGroupSeparator = errors.Errorf("group and check names may not contain '%s'", groupSeparator)

type SourceData struct {
	Data     []byte
	Filename string
}

type Stage struct {
	Duration NullDuration `json:"duration"`
	Target   null.Int     `json:"target"`
}

func (s *Stage) UnmarshalText(b []byte) error {
	var stage Stage
	parts := strings.SplitN(string(b), ":", 2)
	if len(parts) > 0 && parts[0] != "" {
		d, err := time.ParseDuration(parts[0])
		if err != nil {
			return err
		}
		stage.Duration = NullDurationFrom(d)
	}
	if len(parts) > 1 && parts[1] != "" {
		t, err := strconv.ParseInt(parts[1], 10, 64)
		if err != nil {
			return err
		}
		stage.Target = null.IntFrom(t)
	}
	*s = stage
	return nil
}

type Group struct {
	ID     string            `json:"id"`
	Path   string            `json:"path"`
	Name   string            `json:"name"`
	Parent *Group            `json:"-"`
	Groups map[string]*Group `json:"groups"`
	Checks map[string]*Check `json:"checks"`

	groupMutex sync.Mutex `json:"-"`
	checkMutex sync.Mutex `json:"-"`
}

func NewGroup(name string, parent *Group) (*Group, error) {
	if strings.Contains(name, groupSeparator) {
		return nil, ErrNameContainsGroupSeparator
	}

	path := name
	if parent != nil {
		path = parent.Path + groupSeparator + path
	}

	hash := md5.Sum([]byte(path))
	id := hex.EncodeToString(hash[:])

	return &Group{
		ID:     id,
		Path:   path,
		Name:   name,
		Parent: parent,
		Groups: make(map[string]*Group),
		Checks: make(map[string]*Check),
	}, nil
}

func (g *Group) Group(name string) (*Group, error) {
	snapshot := g.Groups
	group, ok := snapshot[name]
	if !ok {
		g.groupMutex.Lock()
		defer g.groupMutex.Unlock()

		group, ok := g.Groups[name]
		if !ok {
			group, err := NewGroup(name, g)
			if err != nil {
				return nil, err
			}
			g.Groups[name] = group
			return group, nil
		}
		return group, nil
	}
	return group, nil
}

func (g *Group) Check(name string) (*Check, error) {
	snapshot := g.Checks
	check, ok := snapshot[name]
	if !ok {
		g.checkMutex.Lock()
		defer g.checkMutex.Unlock()
		check, ok := g.Checks[name]
		if !ok {
			check, err := NewCheck(name, g)
			if err != nil {
				return nil, err
			}
			g.Checks[name] = check
			return check, nil
		}
		return check, nil
	}
	return check, nil
}

type Check struct {
	ID    string `json:"id"`
	Path  string `json:"path"`
	Group *Group `json:"-"`
	Name  string `json:"name"`

	Passes int64 `json:"passes"`
	Fails  int64 `json:"fails"`
}

func NewCheck(name string, group *Group) (*Check, error) {
	if strings.Contains(name, groupSeparator) {
		return nil, ErrNameContainsGroupSeparator
	}

	path := group.Path + groupSeparator + name
	hash := md5.Sum([]byte(path))
	id := hex.EncodeToString(hash[:])

	return &Check{
		ID:    id,
		Path:  path,
		Group: group,
		Name:  name,
	}, nil
}
<commit_msg>Fixed JSON unmarshalling of stages<commit_after>/*
 *
 * k6 - a next-generation load testing tool
 * Copyright (C) 2016 Load Impact
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package lib

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"
	"gopkg.in/guregu/null.v3"
)

const groupSeparator = "::"

var ErrNameContainsGroupSeparator = errors.Errorf("group and check names may not contain '%s'", groupSeparator)

type SourceData struct {
	Data     []byte
	Filename string
}

type StageFields struct {
	Duration NullDuration `json:"duration"`
	Target   null.Int     `json:"target"`
}

type Stage StageFields

// For some reason, implementing UnmarshalText makes encoding/json treat the type as a string.
func (s *Stage) UnmarshalJSON(b []byte) error {
	var fields StageFields
	if err := json.Unmarshal(b, &fields); err != nil {
		return err
	}
	*s = Stage(fields)
	return nil
}

func (s *Stage) UnmarshalText(b []byte) error {
	var stage Stage
	parts := strings.SplitN(string(b), ":", 2)
	if len(parts) > 0 && parts[0] != "" {
		d, err := time.ParseDuration(parts[0])
		if err != nil {
			return err
		}
		stage.Duration = NullDurationFrom(d)
	}
	if len(parts) > 1 && parts[1] != "" {
		t, err := strconv.ParseInt(parts[1], 10, 64)
		if err != nil {
			return err
		}
		stage.Target = null.IntFrom(t)
	}
	*s = stage
	return nil
}

type Group struct {
	ID     string            `json:"id"`
	Path   string            `json:"path"`
	Name   string            `json:"name"`
	Parent *Group            `json:"-"`
	Groups map[string]*Group `json:"groups"`
	Checks map[string]*Check `json:"checks"`

	groupMutex sync.Mutex `json:"-"`
	checkMutex sync.Mutex `json:"-"`
}

func NewGroup(name string, parent *Group) (*Group, error) {
	if strings.Contains(name, groupSeparator) {
		return nil, ErrNameContainsGroupSeparator
	}

	path := name
	if parent != nil {
		path = parent.Path + groupSeparator + path
	}

	hash := md5.Sum([]byte(path))
	id := hex.EncodeToString(hash[:])

	return &Group{
		ID:     id,
		Path:   path,
		Name:   name,
		Parent: parent,
		Groups: make(map[string]*Group),
		Checks: make(map[string]*Check),
	}, nil
}

func (g *Group) Group(name string) (*Group, error) {
	snapshot := g.Groups
	group, ok := snapshot[name]
	if !ok {
		g.groupMutex.Lock()
		defer g.groupMutex.Unlock()

		group, ok := g.Groups[name]
		if !ok {
			group, err := NewGroup(name, g)
			if err != nil {
				return nil, err
			}
			g.Groups[name] = group
			return group, nil
		}
		return group, nil
	}
	return group, nil
}

func (g *Group) Check(name string) (*Check, error) {
	snapshot := g.Checks
	check, ok := snapshot[name]
	if !ok {
		g.checkMutex.Lock()
		defer g.checkMutex.Unlock()
		check, ok := g.Checks[name]
		if !ok {
			check, err := NewCheck(name, g)
			if err != nil {
				return nil, err
			}
			g.Checks[name] = check
			return check, nil
		}
		return check, nil
	}
	return check, nil
}

type Check struct {
	ID    string `json:"id"`
	Path  string `json:"path"`
	Group *Group `json:"-"`
	Name  string `json:"name"`

	Passes int64 `json:"passes"`
	Fails  int64 `json:"fails"`
}

func NewCheck(name string, group *Group) (*Check, error) {
	if strings.Contains(name, groupSeparator) {
		return nil, ErrNameContainsGroupSeparator
	}

	path := group.Path + groupSeparator + name
	hash := md5.Sum([]byte(path))
	id := hex.EncodeToString(hash[:])

	return &Check{
		ID:    id,
		Path:  path,
		Group: group,
		Name:  name,
	}, nil
}
<|endoftext|>


<commit_before>package main

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gkarlik/expense-tracker/api-gateway/handlers/v1"
	"github.com/gkarlik/quark-go"
	auth "github.com/gkarlik/quark-go/auth/jwt"
	"github.com/gkarlik/quark-go/logger"
	"github.com/gkarlik/quark-go/metrics/noop"
	"github.com/gkarlik/quark-go/ratelimiter"
	"github.com/gkarlik/quark-go/service/discovery/plain"
	nt "github.com/gkarlik/quark-go/service/trace/noop"
	"github.com/gorilla/mux"
	_ "github.com/jinzhu/gorm/dialects/postgres"
)

var (
	discovery     *plain.ServiceDiscovery
	discoveryAddr string
)

type Gateway struct {
	*quark.ServiceBase
}

func CreateGateway() *Gateway {
	name := quark.GetEnvVar("GATEWAY_NAME")
	version := quark.GetEnvVar("GATEWAY_VERSION")
	gp := quark.GetEnvVar("GATEWAY_PORT")
	discoveryAddr = quark.GetEnvVar("DISCOVERY")

	port, err := strconv.Atoi(gp)
	if err != nil {
		panic("Incorrect port value!")
	}

	addr, err := quark.GetHostAddress(port)
	if err != nil {
		panic("Cannot resolve host address!")
	}

	discovery = plain.NewServiceDiscovery("http://" + discoveryAddr)

	return &Gateway{
		ServiceBase: quark.NewService(
			quark.Name(name),
			quark.Version(version),
			quark.Address(addr),
			quark.Discovery(discovery),
			quark.Metrics(noop.NewMetricsReporter()),
			quark.Tracer(nt.NewTracer())),
	}
}

var srv = CreateGateway()

func main() {
	defer srv.Dispose()

	secret := quark.GetEnvVar("GATEWAY_SECRET")
	am := auth.NewAuthenticationMiddleware(
		auth.WithSecret(secret),
		auth.WithContextKey("USER_KEY"),
		auth.WithAuthenticationFunc(func(credentials auth.Credentials) (auth.Claims, error) {
			return v1.AuthenticateUser(srv, credentials)
		}))

	rl := ratelimiter.NewHTTPRateLimiter(100 * time.Millisecond)

	r := mux.NewRouter()
	// user service - v1
	r.Handle("/api/v1/auth", rl.Handle(http.HandlerFunc(am.GenerateToken))).Methods(http.MethodPost)
	r.Handle("/api/v1/users", rl.Handle(v1.GetUserByLoginHandler(srv))).Methods(http.MethodGet)
	r.Handle("/api/v1/users/{id:[0-9]+}", rl.Handle(v1.GetUserByIDHandler(srv))).Methods(http.MethodGet)
	r.Handle("/api/v1/users", rl.Handle(v1.RegisterUserHandler(srv))).Methods(http.MethodPost)

	// expense service - v1
	r.Handle("/api/v1/expenses", rl.Handle(am.Authenticate(v1.UpdateExpenseHandler(srv)))).Methods(http.MethodPut, http.MethodPost)
	r.Handle("/api/v1/categories", rl.Handle(am.Authenticate(v1.UpdateCategoryHandler(srv)))).Methods(http.MethodPut, http.MethodPost)

	srv.Log().InfoWithFields(logger.Fields{
		"addr": srv.Info().Address.String(),
	}, "Service initialized. Listening for incomming connections")

	discovery.Serve(discoveryAddr)

	http.ListenAndServe(srv.Info().Address.String(), r)
}
<commit_msg>User service routes authentication.<commit_after>package main

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gkarlik/expense-tracker/api-gateway/handlers/v1"
	"github.com/gkarlik/quark-go"
	auth "github.com/gkarlik/quark-go/auth/jwt"
	"github.com/gkarlik/quark-go/logger"
	"github.com/gkarlik/quark-go/metrics/noop"
	"github.com/gkarlik/quark-go/ratelimiter"
	"github.com/gkarlik/quark-go/service/discovery/plain"
	nt "github.com/gkarlik/quark-go/service/trace/noop"
	"github.com/gorilla/mux"
	_ "github.com/jinzhu/gorm/dialects/postgres"
)

var (
	discovery     *plain.ServiceDiscovery
	discoveryAddr string
)

type Gateway struct {
	*quark.ServiceBase
}

func CreateGateway() *Gateway {
	name := quark.GetEnvVar("GATEWAY_NAME")
	version := quark.GetEnvVar("GATEWAY_VERSION")
	gp := quark.GetEnvVar("GATEWAY_PORT")
	discoveryAddr = quark.GetEnvVar("DISCOVERY")

	port, err := strconv.Atoi(gp)
	if err != nil {
		panic("Incorrect port value!")
	}

	addr, err := quark.GetHostAddress(port)
	if err != nil {
		panic("Cannot resolve host address!")
	}

	discovery = plain.NewServiceDiscovery("http://" + discoveryAddr)

	return &Gateway{
		ServiceBase: quark.NewService(
			quark.Name(name),
			quark.Version(version),
			quark.Address(addr),
			quark.Discovery(discovery),
			quark.Metrics(noop.NewMetricsReporter()),
			quark.Tracer(nt.NewTracer())),
	}
}

var srv = CreateGateway()

func main() {
	defer srv.Dispose()

	secret := quark.GetEnvVar("GATEWAY_SECRET")
	am := auth.NewAuthenticationMiddleware(
		auth.WithSecret(secret),
		auth.WithContextKey("USER_KEY"),
		auth.WithAuthenticationFunc(func(credentials auth.Credentials) (auth.Claims, error) {
			return v1.AuthenticateUser(srv, credentials)
		}))

	rl := ratelimiter.NewHTTPRateLimiter(100 * time.Millisecond)

	r := mux.NewRouter()
	// user service - v1
	r.Handle("/api/v1/auth", rl.Handle(http.HandlerFunc(am.GenerateToken))).Methods(http.MethodPost)
	r.Handle("/api/v1/users", rl.Handle(am.Authenticate(v1.GetUserByLoginHandler(srv)))).Methods(http.MethodGet)
	r.Handle("/api/v1/users/{id:[0-9]+}", rl.Handle(am.Authenticate(v1.GetUserByIDHandler(srv)))).Methods(http.MethodGet)
	r.Handle("/api/v1/users", rl.Handle(v1.RegisterUserHandler(srv))).Methods(http.MethodPost)

	// expense service - v1
	r.Handle("/api/v1/expenses", rl.Handle(am.Authenticate(v1.UpdateExpenseHandler(srv)))).Methods(http.MethodPut, http.MethodPost)
	r.Handle("/api/v1/categories", rl.Handle(am.Authenticate(v1.UpdateCategoryHandler(srv)))).Methods(http.MethodPut, http.MethodPost)

	srv.Log().InfoWithFields(logger.Fields{
		"addr": srv.Info().Address.String(),
	}, "Service initialized. Listening for incomming connections")

	discovery.Serve(discoveryAddr)

	http.ListenAndServe(srv.Info().Address.String(), r)
}
<|endoftext|>


<commit_before>/*
Create two slices of integers.

Then, figure out which of those integers are in both lists.
*/
package main

import (
    "fmt"
    "math/rand"
)

var length int = 1000
var domain int = 100000

var A []int = make([]int, length)
var B []int = make([]int, length)
var C [][]int = make([][]int, 0, length)

//Generate random values
func construct(Group []int) {
	for i := range Group {
        Group[i] = rand.Intn(domain)
    }
}

func main() {
    construct(A)
    construct(B)

    for ak, av := range A {
        for bk, bv := range B {
            if av == bv {
                C = append(C, []int{ak, bk, av})
            }
        }
    }

    fmt.Println(A)
    fmt.Println(B)
    fmt.Println(C)
}<commit_msg>nonblocking go routines still not figured out.<commit_after>/*
Create two slices of integers.

Then, figure out which of those integers are in both lists.
*/
package main

import (
    "fmt"
    "math/rand"
//    "sync"
)

var length int = 1000
var domain int = 100000

var A []int = make([]int, length)
var B []int = make([]int, length)
//var C [][]int = make([][]int, 0, length)

var ch chan []int = make(chan []int, 1)

//Generate random values
func construct(Group []int) {
	for i := range Group {
        Group[i] = rand.Intn(domain)
    }
}

func main() {
    construct(A)
    construct(B)

    //var wg sync.WaitGroup

    for ak, av := range A {
    //    wg.Add(1)

    //    go func(wg *sync.WaitGroup) {
    //        defer wg.Done()
            ak, av := ak, av

            for bk, bv := range B {
                if av == bv {
                    ch <- []int{ak, bk, av}
                }
            }
    //    }(&wg)
    }

    go func() {
        for i := range ch {
            //C = append(C, []int{ak, bk, av})
            fmt.Println(i)
        }
    }()
/*
    go func(wg *sync.WaitGroup) {
        wg.Wait()
        defer close(ch)
    }(&wg)
*/
    fmt.Println(A)
    fmt.Println(B)
    //fmt.Println(C)
}<|endoftext|>


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

import (
	"net/http"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

func initTemplates() {
}

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

import (
	"net/http"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

func initTemplates() {
}

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