<commit_before>package toolbox

import (
	"reflect"
	"strings"
	"fmt"
)

const (
	fieldNameKey  = "fieldName"
	anonymousKey  = "anonymous"
	fieldIndexKey = "fieldIndex"
	defaultKey    = "default"
)

var columnMapping = []string{"column", "dateLayout", "dateFormat", "autoincrement", "primaryKey", "sequence", "valueMap", defaultKey, anonymousKey}

//ProcessStruct reads passed in struct fields and values to pass it to provided handler
func ProcessStruct(aStruct interface{}, handler func(fieldType reflect.StructField, field reflect.Value) error) error {
	structValue := DiscoverValueByKind(reflect.ValueOf(aStruct), reflect.Struct)
	structType := structValue.Type()
	var isPrivate = func(candidate string) bool {
		if candidate == "" {
			return true
		}
		return strings.ToLower(candidate[0:1]) == candidate[0:1]
	}

	type fieldStruct struct {
		Value reflect.Value
		Type  reflect.StructField
	}
	var fields = make(map[string]*fieldStruct)

	for i := 0; i < structType.NumField(); i++ {
		fieldType := structType.Field(i)
		if ! fieldType.Anonymous {
			continue
		}
		field := structValue.Field(i)
		if ! IsStruct(field) {
			continue
		}
		var aStruct  interface{}
		if fieldType.Type.Kind() == reflect.Ptr {
			if field.IsNil() {
				superType := reflect.New(fieldType.Type.Elem())
				field.Set(superType)
			}
			aStruct = field.Interface()
		} else {
			aStruct = field.Addr().Interface()
		}

		if err := ProcessStruct(aStruct, func(fieldType reflect.StructField, field reflect.Value) error {
			fields[fieldType.Name] = &fieldStruct{Type: fieldType, Value: field}
			return nil
		}); err != nil {
			return err
		}
	}

	for i := 0; i < structType.NumField(); i++ {
		fieldType := structType.Field(i)
		fieldName := fieldType.Name
		if isPrivate(fieldName) || fieldType.Anonymous {
			continue
		}
		field := structValue.Field(i)
		fields[fieldType.Name] = &fieldStruct{Type: fieldType, Value: field}
	}

	for _, field := range fields {
		if err := handler(field.Type, field.Value); err != nil {
			return err
		}
	}
	return nil
}

//BuildTagMapping builds map keyed by mappedKeyTag tag value, and value is another map of keys where tag name is presents in the tags parameter.
func BuildTagMapping(structTemplatePointer interface{}, mappedKeyTag string, resultExclusionTag string, inheritKeyFromField bool, convertKeyToLowerCase bool, tags []string) map[string](map[string]string) {
	reflectStructType := DiscoverTypeByKind(structTemplatePointer, reflect.Struct)
	var result = make(map[string]map[string]string)
	var anonymousMappings = make(map[string]map[string]string)

	for i := 0; i < reflectStructType.NumField(); i++ {
		var field reflect.StructField
		field = reflectStructType.Field(i)
		if field.Anonymous {
			var anonymousType = DereferenceType(field.Type)

			if anonymousType.Kind() == reflect.Struct {
				anonymousMapping := BuildTagMapping(reflect.New(anonymousType).Interface(), mappedKeyTag, resultExclusionTag, inheritKeyFromField, convertKeyToLowerCase, tags)
				for k, v := range anonymousMapping {
					anonymousMappings[k] = v
					anonymousMappings[k][anonymousKey] = "true"
					anonymousMappings[k][fieldIndexKey] = AsString(i)
				}
			}
			continue
		}
		isTransient := strings.EqualFold(field.Tag.Get(resultExclusionTag), "true")
		if isTransient {
			continue
		}

		key := field.Tag.Get(mappedKeyTag)
		if mappedKeyTag == fieldNameKey {
			key = field.Name
		}
		if len(key) == 0 {
			if !inheritKeyFromField {
				continue
			}
			key = field.Name
		}

		if convertKeyToLowerCase {
			key = strings.ToLower(key)
		}

		result[key] = make(map[string]string)
		for _, tag := range tags {
			tagValue := field.Tag.Get(tag)
			if len(tagValue) > 0 {
				result[key][tag] = tagValue
			}
		}
		result[key][fieldNameKey] = field.Name
	}

	for k, v := range anonymousMappings {
		if _, has := result[k]; !has {
			result[k] = v
		}
	}
	return result
}

//NewFieldSettingByKey reads field's tags and returns them indexed by passed in key, fieldName is always part of the resulting map unless filed has "transient" tag.
func NewFieldSettingByKey(aStruct interface{}, key string) map[string](map[string]string) {
	return BuildTagMapping(aStruct, key, "transient", true, true, columnMapping)
}

func setEmptyMap(source reflect.Value) {
	if ! source.CanSet() {
		return
	}
	mapType := source.Type()

	mapPointer := reflect.New(mapType)

	mapValueType := mapType.Elem()
	mapKeyType := mapType.Key()

	newMap := mapPointer.Elem()

	newMap.Set(reflect.MakeMap(mapType))
	targetMapKeyPointer := reflect.New(mapKeyType)

	targetMapValuePointer := reflect.New(mapValueType)

	var elementKey = targetMapKeyPointer.Elem()
	var elementValue = targetMapValuePointer.Elem()

	if elementValue.Kind() == reflect.Ptr && elementValue.IsNil() {
		component := reflect.New(elementValue.Type().Elem())
		elementValue.Set(component)
	}
	if elementKey.Type() != mapKeyType {
		if elementKey.Type().AssignableTo(mapKeyType) {
			elementKey = elementKey.Convert(mapKeyType)
		}
	}

	if DereferenceType(elementValue.Type()).Kind() == reflect.Struct {
		InitStruct(elementValue.Interface())
	}

	newMap.SetMapIndex(elementKey, elementValue)
	var elem = mapPointer.Elem()
	source.Set(elem)
}

func createEmptySlice(source reflect.Value) {
	sliceType := DiscoverTypeByKind(source.Type(), reflect.Slice)
	if ! source.CanSet() {
		return
	}
	slicePointer := reflect.New(sliceType)
	slice := slicePointer.Elem()
	componentType := DiscoverComponentType(sliceType)
	var targetComponentPointer = reflect.New(componentType)
	var targetComponent = targetComponentPointer.Elem()
	if DereferenceType(componentType).Kind() == reflect.Struct {
		structElement := reflect.New(targetComponent.Type().Elem())
		InitStruct(structElement.Interface())
		targetComponentPointer.Elem().Set(structElement)
		InitStruct(targetComponentPointer.Elem().Interface())
	}
	slice.Set(reflect.Append(slice, targetComponentPointer.Elem()))
	source.Set(slicePointer.Elem())

}

//InitStruct initialise any struct pointer to empty struct
func InitStruct(source interface{}) {
	if source == nil {
		return
	}
	if ! IsStruct(source) {
		return
	}

	sourceValue, ok := source.(reflect.Value)
	if ! ok {
		sourceValue = reflect.ValueOf(source)
	}

	if sourceValue.Type().Kind() == reflect.Ptr && ! sourceValue.Elem().IsValid() {
		return
	}

	ProcessStruct(source, func(fieldType reflect.StructField, fieldValue reflect.Value) error {
		if ! fieldValue.CanInterface() {
			return nil
		}

		if fieldType.Type.Kind() == reflect.Map {
			setEmptyMap(fieldValue)
			return nil
		}
		if fieldType.Type.Kind() == reflect.Slice {
			createEmptySlice(fieldValue)
			return nil
		}
		if fieldType.Type.Kind() != reflect.Ptr {
			return nil
		}
		if DereferenceType(fieldType).Kind() == reflect.Struct {

			if !fieldValue.CanSet() {
				return nil
			}
			if fieldValue.Type().Kind() == reflect.Ptr {
				fieldStruct := reflect.New(fieldValue.Type().Elem())

				if reflect.TypeOf(source) != fieldStruct.Type() {
					InitStruct(fieldStruct.Interface())
				}
				fieldValue.Set(fieldStruct)
			}

		}
		return nil
	})
}

//StructFieldMeta represents struct field meta
type StructFieldMeta struct {
	Name        string `json:"name,omitempty"`
	Type        string `json:"type,omitempty"`
	Required    bool   `json:"required,"`
	Description string `json:"description,omitempty"`
}

//StructMeta represents struct meta details
type StructMeta struct {
	Type         string
	Fields       []*StructFieldMeta `json:"fields,omitempty"`
	Dependencies []*StructMeta      `json:"dependencies,omitempty"`
}

func GetStructMeta(source interface{}) *StructMeta {
	var result = &StructMeta{}
	var trackedTypes = make(map[string]bool)
	getStructMeta(source, result, trackedTypes)
	return result
}

//InitStruct initialise any struct pointer to empty struct
func getStructMeta(source interface{}, meta *StructMeta, trackedTypes map[string]bool) bool {
	if source == nil {
		return false
	}
	var structType = fmt.Sprintf("%T", source)
	if _, has := trackedTypes[structType]; has {
		return false
	}
	meta.Type = structType
	trackedTypes[structType] = true
	meta.Fields = make([]*StructFieldMeta, 0)
	meta.Dependencies = make([]*StructMeta, 0)
	ProcessStruct(source, func(fieldType reflect.StructField, field reflect.Value) error {
		fieldMeta := &StructFieldMeta{
		}
		if strings.Contains(string(fieldType.Tag), "-") {
			return nil
		}

		meta.Fields = append(meta.Fields, fieldMeta)
		fieldMeta.Name = fieldType.Name
		if value, ok := fieldType.Tag.Lookup("required"); ok {
			fieldMeta.Required = AsBoolean(value)
		}
		if value, ok := fieldType.Tag.Lookup("description"); ok {
			fieldMeta.Description = value
		}
		var value = field.Interface()
		fieldMeta.Type = fmt.Sprintf("%T", value)

		if IsStruct(value) {
			var fieldStruct = &StructMeta{
			}
			if (getStructMeta(field.Elem().Interface(), fieldStruct, trackedTypes)) {
				meta.Dependencies = append(meta.Dependencies, fieldStruct)
			}
			return nil
		}
		if IsMap(value) {
			var aMap = AsMap(field.Interface())
			var mapValue interface{}
			for _, mapValue = range aMap {
				break
			}
			if mapValue != nil && IsStruct(mapValue) {
				var fieldStruct = &StructMeta{}
				if (getStructMeta(mapValue, fieldStruct, trackedTypes)) {
					meta.Dependencies = append(meta.Dependencies, fieldStruct)

				}
			}
			return nil
		}
		if IsSlice(value) {
			var aSlice = AsSlice(field.Interface())
			if len(aSlice) > 0 {
				if aSlice[0] != nil && IsStruct(aSlice[0]) {
					var fieldStruct = &StructMeta{}
					if (getStructMeta(aSlice[0], fieldStruct, trackedTypes)) {
						meta.Dependencies = append(meta.Dependencies, fieldStruct)
					}
				}
			}
			return nil
		}
		return nil
	})
	return true
}
<commit_msg>patched nil pointer<commit_after>package toolbox

import (
	"reflect"
	"strings"
	"fmt"
)

const (
	fieldNameKey  = "fieldName"
	anonymousKey  = "anonymous"
	fieldIndexKey = "fieldIndex"
	defaultKey    = "default"
)

var columnMapping = []string{"column", "dateLayout", "dateFormat", "autoincrement", "primaryKey", "sequence", "valueMap", defaultKey, anonymousKey}

//ProcessStruct reads passed in struct fields and values to pass it to provided handler
func ProcessStruct(aStruct interface{}, handler func(fieldType reflect.StructField, field reflect.Value) error) error {
	structValue := DiscoverValueByKind(reflect.ValueOf(aStruct), reflect.Struct)
	structType := structValue.Type()
	var isPrivate = func(candidate string) bool {
		if candidate == "" {
			return true
		}
		return strings.ToLower(candidate[0:1]) == candidate[0:1]
	}

	type fieldStruct struct {
		Value reflect.Value
		Type  reflect.StructField
	}
	var fields = make(map[string]*fieldStruct)

	for i := 0; i < structType.NumField(); i++ {
		fieldType := structType.Field(i)
		if ! fieldType.Anonymous {
			continue
		}
		field := structValue.Field(i)
		if ! IsStruct(field) {
			continue
		}
		var aStruct  interface{}
		if fieldType.Type.Kind() == reflect.Ptr {
			if field.IsNil() {
				superType := reflect.New(fieldType.Type.Elem())
				field.Set(superType)
			}
			aStruct = field.Interface()
		} else {
			aStruct = field.Addr().Interface()
		}

		if err := ProcessStruct(aStruct, func(fieldType reflect.StructField, field reflect.Value) error {
			fields[fieldType.Name] = &fieldStruct{Type: fieldType, Value: field}
			return nil
		}); err != nil {
			return err
		}
	}

	for i := 0; i < structType.NumField(); i++ {
		fieldType := structType.Field(i)
		fieldName := fieldType.Name
		if isPrivate(fieldName) || fieldType.Anonymous {
			continue
		}
		field := structValue.Field(i)
		fields[fieldType.Name] = &fieldStruct{Type: fieldType, Value: field}
	}

	for _, field := range fields {
		if err := handler(field.Type, field.Value); err != nil {
			return err
		}
	}
	return nil
}

//BuildTagMapping builds map keyed by mappedKeyTag tag value, and value is another map of keys where tag name is presents in the tags parameter.
func BuildTagMapping(structTemplatePointer interface{}, mappedKeyTag string, resultExclusionTag string, inheritKeyFromField bool, convertKeyToLowerCase bool, tags []string) map[string](map[string]string) {
	reflectStructType := DiscoverTypeByKind(structTemplatePointer, reflect.Struct)
	var result = make(map[string]map[string]string)
	var anonymousMappings = make(map[string]map[string]string)

	for i := 0; i < reflectStructType.NumField(); i++ {
		var field reflect.StructField
		field = reflectStructType.Field(i)
		if field.Anonymous {
			var anonymousType = DereferenceType(field.Type)

			if anonymousType.Kind() == reflect.Struct {
				anonymousMapping := BuildTagMapping(reflect.New(anonymousType).Interface(), mappedKeyTag, resultExclusionTag, inheritKeyFromField, convertKeyToLowerCase, tags)
				for k, v := range anonymousMapping {
					anonymousMappings[k] = v
					anonymousMappings[k][anonymousKey] = "true"
					anonymousMappings[k][fieldIndexKey] = AsString(i)
				}
			}
			continue
		}
		isTransient := strings.EqualFold(field.Tag.Get(resultExclusionTag), "true")
		if isTransient {
			continue
		}

		key := field.Tag.Get(mappedKeyTag)
		if mappedKeyTag == fieldNameKey {
			key = field.Name
		}
		if len(key) == 0 {
			if !inheritKeyFromField {
				continue
			}
			key = field.Name
		}

		if convertKeyToLowerCase {
			key = strings.ToLower(key)
		}

		result[key] = make(map[string]string)
		for _, tag := range tags {
			tagValue := field.Tag.Get(tag)
			if len(tagValue) > 0 {
				result[key][tag] = tagValue
			}
		}
		result[key][fieldNameKey] = field.Name
	}

	for k, v := range anonymousMappings {
		if _, has := result[k]; !has {
			result[k] = v
		}
	}
	return result
}

//NewFieldSettingByKey reads field's tags and returns them indexed by passed in key, fieldName is always part of the resulting map unless filed has "transient" tag.
func NewFieldSettingByKey(aStruct interface{}, key string) map[string](map[string]string) {
	return BuildTagMapping(aStruct, key, "transient", true, true, columnMapping)
}

func setEmptyMap(source reflect.Value) {
	if ! source.CanSet() {
		return
	}
	mapType := source.Type()

	mapPointer := reflect.New(mapType)

	mapValueType := mapType.Elem()
	mapKeyType := mapType.Key()

	newMap := mapPointer.Elem()

	newMap.Set(reflect.MakeMap(mapType))
	targetMapKeyPointer := reflect.New(mapKeyType)

	targetMapValuePointer := reflect.New(mapValueType)

	var elementKey = targetMapKeyPointer.Elem()
	var elementValue = targetMapValuePointer.Elem()

	if elementValue.Kind() == reflect.Ptr && elementValue.IsNil() {
		component := reflect.New(elementValue.Type().Elem())
		elementValue.Set(component)
	}
	if elementKey.Type() != mapKeyType {
		if elementKey.Type().AssignableTo(mapKeyType) {
			elementKey = elementKey.Convert(mapKeyType)
		}
	}

	if DereferenceType(elementValue.Type()).Kind() == reflect.Struct {
		InitStruct(elementValue.Interface())
	}

	newMap.SetMapIndex(elementKey, elementValue)
	var elem = mapPointer.Elem()
	source.Set(elem)
}

func createEmptySlice(source reflect.Value) {
	sliceType := DiscoverTypeByKind(source.Type(), reflect.Slice)
	if ! source.CanSet() {
		return
	}
	slicePointer := reflect.New(sliceType)
	slice := slicePointer.Elem()
	componentType := DiscoverComponentType(sliceType)
	var targetComponentPointer = reflect.New(componentType)
	var targetComponent = targetComponentPointer.Elem()
	if DereferenceType(componentType).Kind() == reflect.Struct {
		structElement := reflect.New(targetComponent.Type().Elem())
		InitStruct(structElement.Interface())
		targetComponentPointer.Elem().Set(structElement)
		InitStruct(targetComponentPointer.Elem().Interface())
	}
	slice.Set(reflect.Append(slice, targetComponentPointer.Elem()))
	source.Set(slicePointer.Elem())

}

//InitStruct initialise any struct pointer to empty struct
func InitStruct(source interface{}) {
	if source == nil {
		return
	}
	if ! IsStruct(source) {
		return
	}

	sourceValue, ok := source.(reflect.Value)
	if ! ok {
		sourceValue = reflect.ValueOf(source)
	}

	if sourceValue.Type().Kind() == reflect.Ptr && ! sourceValue.Elem().IsValid() {
		return
	}

	ProcessStruct(source, func(fieldType reflect.StructField, fieldValue reflect.Value) error {
		if ! fieldValue.CanInterface() {
			return nil
		}

		if fieldType.Type.Kind() == reflect.Map {
			setEmptyMap(fieldValue)
			return nil
		}
		if fieldType.Type.Kind() == reflect.Slice {
			createEmptySlice(fieldValue)
			return nil
		}
		if fieldType.Type.Kind() != reflect.Ptr {
			return nil
		}
		if DereferenceType(fieldType).Kind() == reflect.Struct {

			if !fieldValue.CanSet() {
				return nil
			}
			if fieldValue.Type().Kind() == reflect.Ptr {
				fieldStruct := reflect.New(fieldValue.Type().Elem())

				if reflect.TypeOf(source) != fieldStruct.Type() {
					InitStruct(fieldStruct.Interface())
				}
				fieldValue.Set(fieldStruct)
			}

		}
		return nil
	})
}

//StructFieldMeta represents struct field meta
type StructFieldMeta struct {
	Name        string `json:"name,omitempty"`
	Type        string `json:"type,omitempty"`
	Required    bool   `json:"required,"`
	Description string `json:"description,omitempty"`
}

//StructMeta represents struct meta details
type StructMeta struct {
	Type         string
	Fields       []*StructFieldMeta `json:"fields,omitempty"`
	Dependencies []*StructMeta      `json:"dependencies,omitempty"`
}

func GetStructMeta(source interface{}) *StructMeta {
	var result = &StructMeta{}
	var trackedTypes = make(map[string]bool)
	getStructMeta(source, result, trackedTypes)
	return result
}

//InitStruct initialise any struct pointer to empty struct
func getStructMeta(source interface{}, meta *StructMeta, trackedTypes map[string]bool) bool {
	if source == nil {
		return false
	}
	var structType = fmt.Sprintf("%T", source)
	if _, has := trackedTypes[structType]; has  {
		return false
	}
	meta.Type = structType
	trackedTypes[structType] = true
	meta.Fields = make([]*StructFieldMeta, 0)
	meta.Dependencies = make([]*StructMeta, 0)
	ProcessStruct(source, func(fieldType reflect.StructField, field reflect.Value) error {
		fieldMeta := &StructFieldMeta{}
		if strings.Contains(string(fieldType.Tag), "json:\"-") {
			return nil
		}

		meta.Fields = append(meta.Fields, fieldMeta)
		fieldMeta.Name = fieldType.Name
		if value, ok := fieldType.Tag.Lookup("required"); ok {
			fieldMeta.Required = AsBoolean(value)
		}
		if value, ok := fieldType.Tag.Lookup("description"); ok {
			fieldMeta.Description = value
		}
		var value = field.Interface()
		if value== nil {
			return nil
		}

		fieldMeta.Type = fmt.Sprintf("%T", value)
		if IsStruct(value) {
			var fieldStruct = &StructMeta{}
			if field.Kind() == reflect.Ptr && ! field.IsNil() {
				if (getStructMeta(field.Elem().Interface(), fieldStruct, trackedTypes)) {
					meta.Dependencies = append(meta.Dependencies, fieldStruct)
				}
			}
			return nil
		}
		if IsMap(value) {
			var aMap = AsMap(field.Interface())
			var mapValue interface{}
			for _, mapValue = range aMap {
				break
			}
			if mapValue != nil && IsStruct(mapValue) {
				var fieldStruct = &StructMeta{}
				if (getStructMeta(mapValue, fieldStruct, trackedTypes)) {
					meta.Dependencies = append(meta.Dependencies, fieldStruct)

				}
			}
			return nil
		}
		if IsSlice(value) {
			var aSlice = AsSlice(field.Interface())
			if len(aSlice) > 0 {
				if aSlice[0] != nil && IsStruct(aSlice[0]) {
					var fieldStruct = &StructMeta{}
					if (getStructMeta(aSlice[0], fieldStruct, trackedTypes)) {
						meta.Dependencies = append(meta.Dependencies, fieldStruct)
					}
				}
			}
			return nil
		}
		return nil
	})
	return true
}
<|endoftext|>


<commit_before>package app

import (
	"fmt"
	"os"
	"reflect"
	"strings"
	"text/tabwriter"
	"text/template"
	"unicode/utf8"

	"github.com/cloudfoundry/cli/cf/configuration/plugin_config"
	. "github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/codegangsta/cli"
)

type groupedCommands struct {
	Name             string
	CommandSubGroups [][]cmdPresenter
}

func (c groupedCommands) SubTitle(name string) string {
	return terminal.HeaderColor(name + ":")
}

type cmdPresenter struct {
	Name        string
	Description string
}

func presentCmdName(cmd cli.Command) (name string) {
	name = cmd.Name
	if cmd.ShortName != "" {
		name = name + ", " + cmd.ShortName
	}
	return
}

type appPresenter struct {
	cli.App
	Commands []groupedCommands
}

func (p appPresenter) Title(name string) string {
	return terminal.HeaderColor(name)
}

func newAppPresenter(app *cli.App) (presenter appPresenter) {
	maxNameLen := 0
	for _, cmd := range app.Commands {
		name := presentCmdName(cmd)
		if utf8.RuneCountInString(name) > maxNameLen {
			maxNameLen = len(name)
		}
	}

	presentCommand := func(commandName string) (presenter cmdPresenter) {
		cmd := app.Command(commandName)
		presenter.Name = presentCmdName(*cmd)
		padding := strings.Repeat(" ", maxNameLen-utf8.RuneCountInString(presenter.Name))
		presenter.Name = presenter.Name + padding
		presenter.Description = cmd.Description
		return
	}

	presentPluginCommands := func() []cmdPresenter {
		pluginConfig := plugin_config.NewPluginConfig(func(err error) {
			//fail silently when running help?
		})

		plugins := pluginConfig.Plugins()
		var presenters []cmdPresenter
		var pluginPresenter cmdPresenter

		for _, pluginMetadata := range plugins {
			for _, cmd := range pluginMetadata.Commands {
				pluginPresenter.Name = cmd.Name
				padding := strings.Repeat(" ", maxNameLen-utf8.RuneCountInString(pluginPresenter.Name))
				pluginPresenter.Name = pluginPresenter.Name + padding
				pluginPresenter.Description = cmd.HelpText
				presenters = append(presenters, pluginPresenter)
			}
		}

		return presenters
	}
	presenter.Name = app.Name
	presenter.Flags = app.Flags
	presenter.Usage = app.Usage
	presenter.Version = app.Version
	presenter.Compiled = app.Compiled
	presenter.Commands = []groupedCommands{
		{
			Name: T("GETTING STARTED"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("login"),
					presentCommand("logout"),
					presentCommand("passwd"),
					presentCommand("target"),
				}, {
					presentCommand("api"),
					presentCommand("auth"),
				},
			},
		}, {
			Name: T("APPS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("apps"),
					presentCommand("app"),
				}, {
					presentCommand("push"),
					presentCommand("scale"),
					presentCommand("delete"),
					presentCommand("rename"),
				}, {
					presentCommand("start"),
					presentCommand("stop"),
					presentCommand("restart"),
					presentCommand("restage"),
				}, {
					presentCommand("events"),
					presentCommand("files"),
					presentCommand("logs"),
				}, {
					presentCommand("env"),
					presentCommand("set-env"),
					presentCommand("unset-env"),
				}, {
					presentCommand("stacks"),
				}, {
					presentCommand("copy-source"),
				},
			},
		}, {
			Name: T("SERVICES"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("marketplace"),
					presentCommand("services"),
					presentCommand("service"),
				}, {
					presentCommand("create-service"),
					presentCommand("update-service"),
					presentCommand("delete-service"),
					presentCommand("rename-service"),
				}, {
					presentCommand("bind-service"),
					presentCommand("unbind-service"),
				}, {
					presentCommand("create-user-provided-service"),
					presentCommand("update-user-provided-service"),
				},
			},
		}, {
			Name: T("ORGS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("orgs"),
					presentCommand("org"),
				}, {
					presentCommand("create-org"),
					presentCommand("delete-org"),
					presentCommand("rename-org"),
				},
			},
		}, {
			Name: T("SPACES"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("spaces"),
					presentCommand("space"),
				}, {
					presentCommand("create-space"),
					presentCommand("delete-space"),
					presentCommand("rename-space"),
				},
			},
		}, {
			Name: T("DOMAINS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("domains"),
					presentCommand("create-domain"),
					presentCommand("delete-domain"),
					presentCommand("create-shared-domain"),
					presentCommand("delete-shared-domain"),
				},
			},
		}, {
			Name: T("ROUTES"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("routes"),
					presentCommand("create-route"),
					presentCommand("check-route"),
					presentCommand("map-route"),
					presentCommand("unmap-route"),
					presentCommand("delete-route"),
					presentCommand("delete-orphaned-routes"),
				},
			},
		}, {
			Name: T("BUILDPACKS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("buildpacks"),
					presentCommand("create-buildpack"),
					presentCommand("update-buildpack"),
					presentCommand("rename-buildpack"),
					presentCommand("delete-buildpack"),
				},
			},
		}, {
			Name: T("USER ADMIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("create-user"),
					presentCommand("delete-user"),
				}, {
					presentCommand("org-users"),
					presentCommand("set-org-role"),
					presentCommand("unset-org-role"),
				}, {
					presentCommand("space-users"),
					presentCommand("set-space-role"),
					presentCommand("unset-space-role"),
				},
			},
		}, {
			Name: T("ORG ADMIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("quotas"),
					presentCommand("quota"),
					presentCommand("set-quota"),
				}, {
					presentCommand("create-quota"),
					presentCommand("delete-quota"),
					presentCommand("update-quota"),
				},
			},
		}, {
			Name: T("SPACE ADMIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("space-quota"),
					presentCommand("space-quotas"),
					presentCommand("create-space-quota"),
					presentCommand("update-space-quota"),
					presentCommand("delete-space-quota"),
					presentCommand("set-space-quota"),
					presentCommand("unset-space-quota"),
				},
			},
		}, {
			Name: T("SERVICE ADMIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("service-auth-tokens"),
					presentCommand("create-service-auth-token"),
					presentCommand("update-service-auth-token"),
					presentCommand("delete-service-auth-token"),
				}, {
					presentCommand("service-brokers"),
					presentCommand("create-service-broker"),
					presentCommand("update-service-broker"),
					presentCommand("delete-service-broker"),
					presentCommand("rename-service-broker"),
				}, {
					presentCommand("migrate-service-instances"),
					presentCommand("purge-service-offering"),
				}, {
					presentCommand("service-access"),
					presentCommand("enable-service-access"),
					presentCommand("disable-service-access"),
				},
			},
		}, {
			Name: T("SECURITY GROUP"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("security-group"),
					presentCommand("security-groups"),
					presentCommand("create-security-group"),
					presentCommand("update-security-group"),
					presentCommand("delete-security-group"),
					presentCommand("bind-security-group"),
					presentCommand("unbind-security-group"),
				}, {
					presentCommand("bind-staging-security-group"),
					presentCommand("staging-security-groups"),
					presentCommand("unbind-staging-security-group"),
				}, {
					presentCommand("bind-running-security-group"),
					presentCommand("running-security-groups"),
					presentCommand("unbind-running-security-group"),
				},
			},
		}, {
			Name: T("ENVIRONMENT VARIABLE GROUPS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("running-environment-variable-group"),
					presentCommand("staging-environment-variable-group"),
					presentCommand("set-staging-environment-variable-group"),
					presentCommand("set-running-environment-variable-group"),
				},
			},
		},
		{
			Name: T("FEATURE FLAGS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("feature-flags"),
					presentCommand("feature-flag"),
					presentCommand("enable-feature-flag"),
					presentCommand("disable-feature-flag"),
				},
			},
		}, {
			Name: T("ADVANCED"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("curl"),
					presentCommand("config"),
					presentCommand("oauth-token"),
				},
			},
		}, {
			Name: T("PLUGIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("plugins"),
					presentCommand("install-plugin"),
					presentCommand("uninstall-plugin"),
				},
			},
		}, {
			Name: T("PLUGIN COMMANDS"),
			CommandSubGroups: [][]cmdPresenter{
				presentPluginCommands(),
			},
		},
	}

	return
}

func ShowHelp(helpTemplate string, thingToPrint interface{}) {
	translatedTemplatedHelp := T(strings.Replace(helpTemplate, "{{", "[[", -1))
	translatedTemplatedHelp = strings.Replace(translatedTemplatedHelp, "[[", "{{", -1)

	switch thing := thingToPrint.(type) {
	case *cli.App:
		showAppHelp(translatedTemplatedHelp, thing)
	case cli.Command:
		showCommandHelp(translatedTemplatedHelp, thing)
	default:
		panic(fmt.Sprintf("Help printer has received something that is neither app nor command! The beast (%s) looks like this: %s", reflect.TypeOf(thing), thing))
	}
}

var CodeGangstaHelpPrinter = cli.HelpPrinter

func showCommandHelp(helpTemplate string, commandToPrint cli.Command) {
	CodeGangstaHelpPrinter(helpTemplate, commandToPrint)
}

func showAppHelp(helpTemplate string, appToPrint *cli.App) {
	presenter := newAppPresenter(appToPrint)

	w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
	t := template.Must(template.New("help").Parse(helpTemplate))
	t.Execute(w, presenter)
	w.Flush()
}
<commit_msg>correct display order in space admin help section<commit_after>package app

import (
	"fmt"
	"os"
	"reflect"
	"strings"
	"text/tabwriter"
	"text/template"
	"unicode/utf8"

	"github.com/cloudfoundry/cli/cf/configuration/plugin_config"
	. "github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/codegangsta/cli"
)

type groupedCommands struct {
	Name             string
	CommandSubGroups [][]cmdPresenter
}

func (c groupedCommands) SubTitle(name string) string {
	return terminal.HeaderColor(name + ":")
}

type cmdPresenter struct {
	Name        string
	Description string
}

func presentCmdName(cmd cli.Command) (name string) {
	name = cmd.Name
	if cmd.ShortName != "" {
		name = name + ", " + cmd.ShortName
	}
	return
}

type appPresenter struct {
	cli.App
	Commands []groupedCommands
}

func (p appPresenter) Title(name string) string {
	return terminal.HeaderColor(name)
}

func newAppPresenter(app *cli.App) (presenter appPresenter) {
	maxNameLen := 0
	for _, cmd := range app.Commands {
		name := presentCmdName(cmd)
		if utf8.RuneCountInString(name) > maxNameLen {
			maxNameLen = len(name)
		}
	}

	presentCommand := func(commandName string) (presenter cmdPresenter) {
		cmd := app.Command(commandName)
		presenter.Name = presentCmdName(*cmd)
		padding := strings.Repeat(" ", maxNameLen-utf8.RuneCountInString(presenter.Name))
		presenter.Name = presenter.Name + padding
		presenter.Description = cmd.Description
		return
	}

	presentPluginCommands := func() []cmdPresenter {
		pluginConfig := plugin_config.NewPluginConfig(func(err error) {
			//fail silently when running help?
		})

		plugins := pluginConfig.Plugins()
		var presenters []cmdPresenter
		var pluginPresenter cmdPresenter

		for _, pluginMetadata := range plugins {
			for _, cmd := range pluginMetadata.Commands {
				pluginPresenter.Name = cmd.Name
				padding := strings.Repeat(" ", maxNameLen-utf8.RuneCountInString(pluginPresenter.Name))
				pluginPresenter.Name = pluginPresenter.Name + padding
				pluginPresenter.Description = cmd.HelpText
				presenters = append(presenters, pluginPresenter)
			}
		}

		return presenters
	}
	presenter.Name = app.Name
	presenter.Flags = app.Flags
	presenter.Usage = app.Usage
	presenter.Version = app.Version
	presenter.Compiled = app.Compiled
	presenter.Commands = []groupedCommands{
		{
			Name: T("GETTING STARTED"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("login"),
					presentCommand("logout"),
					presentCommand("passwd"),
					presentCommand("target"),
				}, {
					presentCommand("api"),
					presentCommand("auth"),
				},
			},
		}, {
			Name: T("APPS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("apps"),
					presentCommand("app"),
				}, {
					presentCommand("push"),
					presentCommand("scale"),
					presentCommand("delete"),
					presentCommand("rename"),
				}, {
					presentCommand("start"),
					presentCommand("stop"),
					presentCommand("restart"),
					presentCommand("restage"),
				}, {
					presentCommand("events"),
					presentCommand("files"),
					presentCommand("logs"),
				}, {
					presentCommand("env"),
					presentCommand("set-env"),
					presentCommand("unset-env"),
				}, {
					presentCommand("stacks"),
				}, {
					presentCommand("copy-source"),
				},
			},
		}, {
			Name: T("SERVICES"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("marketplace"),
					presentCommand("services"),
					presentCommand("service"),
				}, {
					presentCommand("create-service"),
					presentCommand("update-service"),
					presentCommand("delete-service"),
					presentCommand("rename-service"),
				}, {
					presentCommand("bind-service"),
					presentCommand("unbind-service"),
				}, {
					presentCommand("create-user-provided-service"),
					presentCommand("update-user-provided-service"),
				},
			},
		}, {
			Name: T("ORGS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("orgs"),
					presentCommand("org"),
				}, {
					presentCommand("create-org"),
					presentCommand("delete-org"),
					presentCommand("rename-org"),
				},
			},
		}, {
			Name: T("SPACES"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("spaces"),
					presentCommand("space"),
				}, {
					presentCommand("create-space"),
					presentCommand("delete-space"),
					presentCommand("rename-space"),
				},
			},
		}, {
			Name: T("DOMAINS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("domains"),
					presentCommand("create-domain"),
					presentCommand("delete-domain"),
					presentCommand("create-shared-domain"),
					presentCommand("delete-shared-domain"),
				},
			},
		}, {
			Name: T("ROUTES"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("routes"),
					presentCommand("create-route"),
					presentCommand("check-route"),
					presentCommand("map-route"),
					presentCommand("unmap-route"),
					presentCommand("delete-route"),
					presentCommand("delete-orphaned-routes"),
				},
			},
		}, {
			Name: T("BUILDPACKS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("buildpacks"),
					presentCommand("create-buildpack"),
					presentCommand("update-buildpack"),
					presentCommand("rename-buildpack"),
					presentCommand("delete-buildpack"),
				},
			},
		}, {
			Name: T("USER ADMIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("create-user"),
					presentCommand("delete-user"),
				}, {
					presentCommand("org-users"),
					presentCommand("set-org-role"),
					presentCommand("unset-org-role"),
				}, {
					presentCommand("space-users"),
					presentCommand("set-space-role"),
					presentCommand("unset-space-role"),
				},
			},
		}, {
			Name: T("ORG ADMIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("quotas"),
					presentCommand("quota"),
					presentCommand("set-quota"),
				}, {
					presentCommand("create-quota"),
					presentCommand("delete-quota"),
					presentCommand("update-quota"),
				},
			},
		}, {
			Name: T("SPACE ADMIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("space-quotas"),
					presentCommand("space-quota"),
					presentCommand("create-space-quota"),
					presentCommand("update-space-quota"),
					presentCommand("delete-space-quota"),
					presentCommand("set-space-quota"),
					presentCommand("unset-space-quota"),
				},
			},
		}, {
			Name: T("SERVICE ADMIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("service-auth-tokens"),
					presentCommand("create-service-auth-token"),
					presentCommand("update-service-auth-token"),
					presentCommand("delete-service-auth-token"),
				}, {
					presentCommand("service-brokers"),
					presentCommand("create-service-broker"),
					presentCommand("update-service-broker"),
					presentCommand("delete-service-broker"),
					presentCommand("rename-service-broker"),
				}, {
					presentCommand("migrate-service-instances"),
					presentCommand("purge-service-offering"),
				}, {
					presentCommand("service-access"),
					presentCommand("enable-service-access"),
					presentCommand("disable-service-access"),
				},
			},
		}, {
			Name: T("SECURITY GROUP"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("security-group"),
					presentCommand("security-groups"),
					presentCommand("create-security-group"),
					presentCommand("update-security-group"),
					presentCommand("delete-security-group"),
					presentCommand("bind-security-group"),
					presentCommand("unbind-security-group"),
				}, {
					presentCommand("bind-staging-security-group"),
					presentCommand("staging-security-groups"),
					presentCommand("unbind-staging-security-group"),
				}, {
					presentCommand("bind-running-security-group"),
					presentCommand("running-security-groups"),
					presentCommand("unbind-running-security-group"),
				},
			},
		}, {
			Name: T("ENVIRONMENT VARIABLE GROUPS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("running-environment-variable-group"),
					presentCommand("staging-environment-variable-group"),
					presentCommand("set-staging-environment-variable-group"),
					presentCommand("set-running-environment-variable-group"),
				},
			},
		},
		{
			Name: T("FEATURE FLAGS"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("feature-flags"),
					presentCommand("feature-flag"),
					presentCommand("enable-feature-flag"),
					presentCommand("disable-feature-flag"),
				},
			},
		}, {
			Name: T("ADVANCED"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("curl"),
					presentCommand("config"),
					presentCommand("oauth-token"),
				},
			},
		}, {
			Name: T("PLUGIN"),
			CommandSubGroups: [][]cmdPresenter{
				{
					presentCommand("plugins"),
					presentCommand("install-plugin"),
					presentCommand("uninstall-plugin"),
				},
			},
		}, {
			Name: T("PLUGIN COMMANDS"),
			CommandSubGroups: [][]cmdPresenter{
				presentPluginCommands(),
			},
		},
	}

	return
}

func ShowHelp(helpTemplate string, thingToPrint interface{}) {
	translatedTemplatedHelp := T(strings.Replace(helpTemplate, "{{", "[[", -1))
	translatedTemplatedHelp = strings.Replace(translatedTemplatedHelp, "[[", "{{", -1)

	switch thing := thingToPrint.(type) {
	case *cli.App:
		showAppHelp(translatedTemplatedHelp, thing)
	case cli.Command:
		showCommandHelp(translatedTemplatedHelp, thing)
	default:
		panic(fmt.Sprintf("Help printer has received something that is neither app nor command! The beast (%s) looks like this: %s", reflect.TypeOf(thing), thing))
	}
}

var CodeGangstaHelpPrinter = cli.HelpPrinter

func showCommandHelp(helpTemplate string, commandToPrint cli.Command) {
	CodeGangstaHelpPrinter(helpTemplate, commandToPrint)
}

func showAppHelp(helpTemplate string, appToPrint *cli.App) {
	presenter := newAppPresenter(appToPrint)

	w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
	t := template.Must(template.New("help").Parse(helpTemplate))
	t.Execute(w, presenter)
	w.Flush()
}
<|endoftext|>


<commit_before>// Copyright 2018 The Hugo Authors. All rights reserved.
//
// 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 hugo

// CurrentVersion represents the current build version.
// This should be the only one.
var CurrentVersion = Version{
	Number:     0.86,
	PatchLevel: 0,
	Suffix:     "",
}
<commit_msg>releaser: Bump versions for release of 0.86.1<commit_after>// Copyright 2018 The Hugo Authors. All rights reserved.
//
// 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 hugo

// CurrentVersion represents the current build version.
// This should be the only one.
var CurrentVersion = Version{
	Number:     0.86,
	PatchLevel: 1,
	Suffix:     "",
}
<|endoftext|>


<commit_before>// Challenge 47 - Bleichenbacher's PKCS 1.5 Padding Oracle (Simple Case)
// http://cryptopals.com/sets/6/challenges/47

package cryptopals

import (
	"crypto/rsa"
	"math/big"
)

type challenge47 struct {
}

type oracleFunc func([]byte) bool

type interval struct {
	a *big.Int
	b *big.Int
}

func (challenge47) mulEncrypt(m, e, n, c *big.Int) []byte {
	x := new(big.Int).Exp(m, e, n)
	return x.Mul(c, x).Mod(x, n).Bytes()
}

func (challenge47) union(M []interval, m interval) []interval {
	if m.a.Cmp(m.b) > 0 {
		return M
	}

	var result []interval

	for i, mi := range M {
		if mi.b.Cmp(m.a) < 0 {
			result = append(result, mi)
		} else if m.b.Cmp(mi.a) < 0 {
			return append(append(result, m), M[i:]...)
		} else {
			m = interval{a: min(mi.a, m.a), b: max(mi.b, m.b)}
		}
	}

	return append(result, m)
}

func (x challenge47) DecryptRsaPaddingOracleSimple(pub *rsa.PublicKey, ciphertext []byte, oracle oracleFunc) []byte {
	e, c0, s := big.NewInt(int64(pub.E)), new(big.Int).SetBytes(ciphertext), new(big.Int)
	k := big.NewInt(int64(pub.N.BitLen() / 8))
	one, two, three, eight := big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(8)

	B := new(big.Int).Sub(k, two)
	B = B.Mul(eight, B).Exp(two, B, nil)

	twoB, threeB := new(big.Int).Mul(two, B), new(big.Int).Mul(three, B)
	M := []interval{interval{a: twoB, b: new(big.Int).Sub(threeB, one)}}

	// Step 2: Searching for PKCS conforming messages.
	for i := 1; ; i++ {
		if i == 1 { // Step 2a: Starting the search.
			for s = ceil(pub.N, threeB); !oracle(x.mulEncrypt(s, e, pub.N, c0)); s = s.Add(s, one) {
			}
		} else if len(M) > 1 { // Step 2.b: Searching with more than one interval left.
			for s = s.Add(s, one); !oracle(x.mulEncrypt(s, e, pub.N, c0)); s = s.Add(s, one) {
			}

		} else { // Step 2.c: Searching with one interval left.
			a, b, found := M[0].a, M[0].b, false

			r := new(big.Int).Mul(b, s)
			r = r.Sub(r, twoB).Mul(two, r).Div(r, pub.N)

			for ; !found; r = r.Add(r, one) {
				sMin := new(big.Int).Mul(r, pub.N)
				sMin = sMin.Add(twoB, sMin).Div(sMin, b)

				sMax := new(big.Int).Mul(r, pub.N)
				sMax = sMax.Add(threeB, sMax).Div(sMax, a)

				for s = sMin; s.Cmp(sMax) < 0; s = s.Add(s, one) {
					if oracle(x.mulEncrypt(s, e, pub.N, c0)) {
						found = true
						break
					}
				}
			}
		}

		var Mi []interval

		// Step 3: Narrowing the set of solutions.
		for _, m := range M {
			rMin := new(big.Int).Mul(m.a, s)
			rMin = rMin.Sub(rMin, threeB).Add(rMin, one).Div(rMin, pub.N)

			rMax := new(big.Int).Mul(m.b, s)
			rMax = rMax.Sub(rMax, twoB).Div(rMax, pub.N)

			for r := rMin; r.Cmp(rMax) <= 0; r = r.Add(r, one) {
				a := new(big.Int).Mul(r, pub.N)
				a = max(m.a, ceil(a.Add(twoB, a), s))

				b := new(big.Int).Mul(r, pub.N)
				b = min(m.b, floor(b.Add(threeB, b).Sub(b, one), s))

				mi := interval{a: a, b: b}
				Mi = x.union(Mi, mi)
			}
		}

		M = Mi

		// Step 4: Computing the solution.
		if len(M) == 1 && M[0].a.Cmp(M[0].b) == 0 {
			return M[0].a.Bytes()
		}
	}
}
<commit_msg>Fix formatting<commit_after>// Challenge 47 - Bleichenbacher's PKCS 1.5 Padding Oracle (Simple Case)
// http://cryptopals.com/sets/6/challenges/47

package cryptopals

import (
	"crypto/rsa"
	"math/big"
)

type challenge47 struct {
}

type oracleFunc func([]byte) bool

type interval struct {
	a *big.Int
	b *big.Int
}

func (challenge47) mulEncrypt(m, e, n, c *big.Int) []byte {
	x := new(big.Int).Exp(m, e, n)
	return x.Mul(c, x).Mod(x, n).Bytes()
}

func (challenge47) union(M []interval, m interval) []interval {
	if m.a.Cmp(m.b) > 0 {
		return M
	}

	var result []interval

	for i, mi := range M {
		if mi.b.Cmp(m.a) < 0 {
			result = append(result, mi)
		} else if m.b.Cmp(mi.a) < 0 {
			return append(append(result, m), M[i:]...)
		} else {
			m = interval{a: min(mi.a, m.a), b: max(mi.b, m.b)}
		}
	}

	return append(result, m)
}

func (x challenge47) DecryptRsaPaddingOracleSimple(pub *rsa.PublicKey, ciphertext []byte, oracle oracleFunc) []byte {
	e, c0, s := big.NewInt(int64(pub.E)), new(big.Int).SetBytes(ciphertext), new(big.Int)
	k := big.NewInt(int64(pub.N.BitLen() / 8))
	one, two, three, eight := big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(8)

	B := new(big.Int).Sub(k, two)
	B = B.Mul(eight, B).Exp(two, B, nil)

	twoB, threeB := new(big.Int).Mul(two, B), new(big.Int).Mul(three, B)
	M := []interval{interval{a: twoB, b: new(big.Int).Sub(threeB, one)}}

	// Step 2: Searching for PKCS conforming messages.
	for i := 1; ; i++ {
		if i == 1 { // Step 2a: Starting the search.
			for s = ceil(pub.N, threeB); !oracle(x.mulEncrypt(s, e, pub.N, c0)); s = s.Add(s, one) {
			}
		} else if len(M) > 1 { // Step 2.b: Searching with more than one interval left.
			for s = s.Add(s, one); !oracle(x.mulEncrypt(s, e, pub.N, c0)); s = s.Add(s, one) {
			}
		} else { // Step 2.c: Searching with one interval left.
			a, b, found := M[0].a, M[0].b, false

			r := new(big.Int).Mul(b, s)
			r = r.Sub(r, twoB).Mul(two, r).Div(r, pub.N)

			for ; !found; r = r.Add(r, one) {
				sMin := new(big.Int).Mul(r, pub.N)
				sMin = sMin.Add(twoB, sMin).Div(sMin, b)

				sMax := new(big.Int).Mul(r, pub.N)
				sMax = sMax.Add(threeB, sMax).Div(sMax, a)

				for s = sMin; s.Cmp(sMax) < 0; s = s.Add(s, one) {
					if oracle(x.mulEncrypt(s, e, pub.N, c0)) {
						found = true
						break
					}
				}
			}
		}

		var Mi []interval

		// Step 3: Narrowing the set of solutions.
		for _, m := range M {
			rMin := new(big.Int).Mul(m.a, s)
			rMin = rMin.Sub(rMin, threeB).Add(rMin, one).Div(rMin, pub.N)

			rMax := new(big.Int).Mul(m.b, s)
			rMax = rMax.Sub(rMax, twoB).Div(rMax, pub.N)

			for r := rMin; r.Cmp(rMax) <= 0; r = r.Add(r, one) {
				a := new(big.Int).Mul(r, pub.N)
				a = max(m.a, ceil(a.Add(twoB, a), s))

				b := new(big.Int).Mul(r, pub.N)
				b = min(m.b, floor(b.Add(threeB, b).Sub(b, one), s))

				mi := interval{a: a, b: b}
				Mi = x.union(Mi, mi)
			}
		}

		M = Mi

		// Step 4: Computing the solution.
		if len(M) == 1 && M[0].a.Cmp(M[0].b) == 0 {
			return M[0].a.Bytes()
		}
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * 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 traversal

import (
	"bufio"
	"bytes"
	"io"
	"strings"
)

// Token represents a lexical token.
type Token int

const (
	// Special tokens
	ILLEGAL Token = iota
	EOF
	WS

	// Literals
	IDENT

	// Misc characters
	COMMA
	DOT
	LEFT_PARENTHESIS
	RIGHT_PARENTHESIS
	STRING
	NUMBER

	// Keywords
	G
	V
	HAS
	OUT
	IN
	OUTV
	INV
	OUTE
	INE
	DEDUP
	WITHIN
	WITHOUT
	METADATA
	SHORTESTPATHTO
	NE
	BOTH
	CONTEXT
	REGEX
	LT
	GT
	LTE
	GTE
	INSIDE
	OUTSIDE
	BETWEEN
	COUNT
	RANGE
	LIMIT
	SORT
	SINCE

	// extensions token have to start after 1000
)

type GremlinTraversalScanner struct {
	reader     *bufio.Reader
	extensions []GremlinTraversalExtension
}

func NewGremlinTraversalScanner(r io.Reader, e []GremlinTraversalExtension) *GremlinTraversalScanner {
	return &GremlinTraversalScanner{
		reader:     bufio.NewReader(r),
		extensions: e,
	}
}

func (s *GremlinTraversalScanner) Scan() (tok Token, lit string) {
	ch := s.read()

	if isWhitespace(ch) {
		return s.scanWhitespace()
	} else if isDigit(ch) {
		s.unread()
		return s.scanNumber()
	} else if isString(ch) {
		return s.scanString()
	} else if isLetter(ch) {
		s.unread()
		return s.scanIdent()
	}

	switch ch {
	case eof:
		return EOF, ""
	case '(':
		return LEFT_PARENTHESIS, string(ch)
	case ')':
		return RIGHT_PARENTHESIS, string(ch)
	case ',':
		return COMMA, string(ch)
	case '.':
		return DOT, string(ch)
	}

	return ILLEGAL, string(ch)
}

func (s *GremlinTraversalScanner) scanWhitespace() (tok Token, lit string) {
	var buf bytes.Buffer

	for {
		if ch := s.read(); ch == eof {
			break
		} else if !isWhitespace(ch) {
			s.unread()
			break
		} else {
			buf.WriteRune(ch)
		}
	}

	return WS, buf.String()
}

func (s *GremlinTraversalScanner) scanNumber() (tok Token, lit string) {
	var buf bytes.Buffer
	buf.WriteRune(s.read())

	for {
		if ch := s.read(); isLetter(ch) {
			return ILLEGAL, string(ch)
		} else if ch == eof || (!isDigit(ch) && ch != '.') {
			s.unread()
			break
		} else {
			_, _ = buf.WriteRune(ch)
		}
	}

	return NUMBER, buf.String()
}

func (s *GremlinTraversalScanner) scanString() (tok Token, lit string) {
	var buf bytes.Buffer

	for {
		if ch := s.read(); ch == '"' || ch == '\'' || ch == eof {
			break
		} else {
			_, _ = buf.WriteRune(ch)
		}
	}

	return STRING, buf.String()
}

func (s *GremlinTraversalScanner) scanIdent() (tok Token, lit string) {
	var buf bytes.Buffer
	buf.WriteRune(s.read())

	for {
		if ch := s.read(); ch == eof {
			break
		} else if !isLetter(ch) && !isDigit(ch) && ch != '_' {
			s.unread()
			break
		} else {
			_, _ = buf.WriteRune(ch)
		}
	}

	us := strings.ToUpper(buf.String())

	switch us {
	case "G":
		return G, buf.String()
	case "V":
		return V, buf.String()
	case "HAS":
		return HAS, buf.String()
	case "OUT":
		return OUT, buf.String()
	case "IN":
		return IN, buf.String()
	case "OUTV":
		return OUTV, buf.String()
	case "INV":
		return INV, buf.String()
	case "OUTE":
		return OUTE, buf.String()
	case "INE":
		return INE, buf.String()
	case "WITHIN":
		return WITHIN, buf.String()
	case "WITHOUT":
		return WITHOUT, buf.String()
	case "DEDUP":
		return DEDUP, buf.String()
	case "METADATA":
		return METADATA, buf.String()
	case "SHORTESTPATHTO":
		return SHORTESTPATHTO, buf.String()
	case "NE":
		return NE, buf.String()
	case "BOTH":
		return BOTH, buf.String()
	case "CONTEXT":
		return CONTEXT, buf.String()
	case "REGEX":
		return REGEX, buf.String()
	case "LT":
		return LT, buf.String()
	case "GT":
		return GT, buf.String()
	case "LTE":
		return LTE, buf.String()
	case "GTE":
		return GTE, buf.String()
	case "INSIDE":
		return INSIDE, buf.String()
	case "BETWEEN":
		return BETWEEN, buf.String()
	case "COUNT":
		return COUNT, buf.String()
	case "RANGE":
		return RANGE, buf.String()
	case "LIMIT":
		return LIMIT, buf.String()
	case "SORT":
		return SORT, buf.String()
	case "SINCE":
		return SINCE, buf.String()
	}

	for _, e := range s.extensions {
		if t, ok := e.ScanIdent(us); ok {
			return t, buf.String()
		}
	}

	return IDENT, buf.String()
}

func (s *GremlinTraversalScanner) read() rune {
	ch, _, err := s.reader.ReadRune()
	if err != nil {
		return eof
	}
	return ch
}

func (s *GremlinTraversalScanner) unread() {
	s.reader.UnreadRune()
}

func isString(ch rune) bool {
	return ch == '"' || ch == '\''
}

func isWhitespace(ch rune) bool {
	return ch == ' ' || ch == '\t' || ch == '\n'
}

func isLetter(ch rune) bool {
	return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
}

func isDigit(ch rune) bool {
	return (ch >= '0' && ch <= '9')
}

var eof = rune(0)
<commit_msg>gremlin: add "At" alias for "Context"<commit_after>/*
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * 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 traversal

import (
	"bufio"
	"bytes"
	"io"
	"strings"
)

// Token represents a lexical token.
type Token int

const (
	// Special tokens
	ILLEGAL Token = iota
	EOF
	WS

	// Literals
	IDENT

	// Misc characters
	COMMA
	DOT
	LEFT_PARENTHESIS
	RIGHT_PARENTHESIS
	STRING
	NUMBER

	// Keywords
	G
	V
	HAS
	OUT
	IN
	OUTV
	INV
	OUTE
	INE
	DEDUP
	WITHIN
	WITHOUT
	METADATA
	SHORTESTPATHTO
	NE
	BOTH
	CONTEXT
	REGEX
	LT
	GT
	LTE
	GTE
	INSIDE
	OUTSIDE
	BETWEEN
	COUNT
	RANGE
	LIMIT
	SORT
	SINCE

	// extensions token have to start after 1000
)

type GremlinTraversalScanner struct {
	reader     *bufio.Reader
	extensions []GremlinTraversalExtension
}

func NewGremlinTraversalScanner(r io.Reader, e []GremlinTraversalExtension) *GremlinTraversalScanner {
	return &GremlinTraversalScanner{
		reader:     bufio.NewReader(r),
		extensions: e,
	}
}

func (s *GremlinTraversalScanner) Scan() (tok Token, lit string) {
	ch := s.read()

	if isWhitespace(ch) {
		return s.scanWhitespace()
	} else if isDigit(ch) {
		s.unread()
		return s.scanNumber()
	} else if isString(ch) {
		return s.scanString()
	} else if isLetter(ch) {
		s.unread()
		return s.scanIdent()
	}

	switch ch {
	case eof:
		return EOF, ""
	case '(':
		return LEFT_PARENTHESIS, string(ch)
	case ')':
		return RIGHT_PARENTHESIS, string(ch)
	case ',':
		return COMMA, string(ch)
	case '.':
		return DOT, string(ch)
	}

	return ILLEGAL, string(ch)
}

func (s *GremlinTraversalScanner) scanWhitespace() (tok Token, lit string) {
	var buf bytes.Buffer

	for {
		if ch := s.read(); ch == eof {
			break
		} else if !isWhitespace(ch) {
			s.unread()
			break
		} else {
			buf.WriteRune(ch)
		}
	}

	return WS, buf.String()
}

func (s *GremlinTraversalScanner) scanNumber() (tok Token, lit string) {
	var buf bytes.Buffer
	buf.WriteRune(s.read())

	for {
		if ch := s.read(); isLetter(ch) {
			return ILLEGAL, string(ch)
		} else if ch == eof || (!isDigit(ch) && ch != '.') {
			s.unread()
			break
		} else {
			_, _ = buf.WriteRune(ch)
		}
	}

	return NUMBER, buf.String()
}

func (s *GremlinTraversalScanner) scanString() (tok Token, lit string) {
	var buf bytes.Buffer

	for {
		if ch := s.read(); ch == '"' || ch == '\'' || ch == eof {
			break
		} else {
			_, _ = buf.WriteRune(ch)
		}
	}

	return STRING, buf.String()
}

func (s *GremlinTraversalScanner) scanIdent() (tok Token, lit string) {
	var buf bytes.Buffer
	buf.WriteRune(s.read())

	for {
		if ch := s.read(); ch == eof {
			break
		} else if !isLetter(ch) && !isDigit(ch) && ch != '_' {
			s.unread()
			break
		} else {
			_, _ = buf.WriteRune(ch)
		}
	}

	us := strings.ToUpper(buf.String())

	switch us {
	case "G":
		return G, buf.String()
	case "V":
		return V, buf.String()
	case "HAS":
		return HAS, buf.String()
	case "OUT":
		return OUT, buf.String()
	case "IN":
		return IN, buf.String()
	case "OUTV":
		return OUTV, buf.String()
	case "INV":
		return INV, buf.String()
	case "OUTE":
		return OUTE, buf.String()
	case "INE":
		return INE, buf.String()
	case "WITHIN":
		return WITHIN, buf.String()
	case "WITHOUT":
		return WITHOUT, buf.String()
	case "DEDUP":
		return DEDUP, buf.String()
	case "METADATA":
		return METADATA, buf.String()
	case "SHORTESTPATHTO":
		return SHORTESTPATHTO, buf.String()
	case "NE":
		return NE, buf.String()
	case "BOTH":
		return BOTH, buf.String()
	case "CONTEXT", "AT":
		return CONTEXT, buf.String()
	case "REGEX":
		return REGEX, buf.String()
	case "LT":
		return LT, buf.String()
	case "GT":
		return GT, buf.String()
	case "LTE":
		return LTE, buf.String()
	case "GTE":
		return GTE, buf.String()
	case "INSIDE":
		return INSIDE, buf.String()
	case "BETWEEN":
		return BETWEEN, buf.String()
	case "COUNT":
		return COUNT, buf.String()
	case "RANGE":
		return RANGE, buf.String()
	case "LIMIT":
		return LIMIT, buf.String()
	case "SORT":
		return SORT, buf.String()
	case "SINCE":
		return SINCE, buf.String()
	}

	for _, e := range s.extensions {
		if t, ok := e.ScanIdent(us); ok {
			return t, buf.String()
		}
	}

	return IDENT, buf.String()
}

func (s *GremlinTraversalScanner) read() rune {
	ch, _, err := s.reader.ReadRune()
	if err != nil {
		return eof
	}
	return ch
}

func (s *GremlinTraversalScanner) unread() {
	s.reader.UnreadRune()
}

func isString(ch rune) bool {
	return ch == '"' || ch == '\''
}

func isWhitespace(ch rune) bool {
	return ch == ' ' || ch == '\t' || ch == '\n'
}

func isLetter(ch rune) bool {
	return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
}

func isDigit(ch rune) bool {
	return (ch >= '0' && ch <= '9')
}

var eof = rune(0)
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"encoding/hex"
	"fmt"
	"getcommandline"
	"hash"
	"io"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"tokenize"
)

/*
  REVISION HISTORY
  ----------------
   6 Apr 13 -- First modified version of module.  I will use VLI to compare all digits of the hashes.
  23 Apr 13 -- Fixed problem of a single line in the hashes file, that does not contain an EOL character, causes
                an immediate return without processing of the characters just read in.
  24 Apr 13 -- Added output of which file either matches or does not match.
  19 Sep 16 -- Finished conversion to Go, that was started 13 Sep 16.  Added the removed of '*' which is part of a std linux formated hash file.  And I forgot that
                 the routine allowed either order in the file.  If the token has a '.' I assume it is a filename, else it is a hash value.
  21 Sep 16 -- Fixed the case issue in tokenize.GetToken.  Edited code here to correspond to this fix.
  25 Nov 16 -- Need to not panic when target file is not found, only panic when hash file is not found.
                 And added a LastCompiled message and string.
  13 Oct 17 -- No changes here, but tokenize was changed so that horizontal tab char is now a delim.
  14 Oct 17 -- Tweaked output a bit.  And added executable timestamp code.
  19 Oct 17 -- Added ability to ignore the * that standard hash files for linux use.
*/

const LastCompiled = "14 Oct 2017"

//* ************************* MAIN ***************************************************************
func main() {

	const K = 1024
	const M = 1024 * 1024

	const (
		md5hash = iota
		sha1hash
		sha256hash
		sha384hash
		sha512hash
		HashType
	)

	const ReadBufferSize = M
	//  const ReadBufferSize = 80 * M;

	var HashName = [...]string{"md5", "sha1", "sha256", "sha384", "sha512"}
	var inbuf string
	var WhichHash int
	var readErr error
	var TargetFilename, HashValueReadFromFile, HashValueComputedStr string
	var hasher hash.Hash
	var FileSize int64

	if len(os.Args) <= 1 {
		fmt.Println(" Usage: comparehashes <hashFileName.ext> where .ext = [.md5|.sha1|.sha256|.sha384|.sha512]")
		os.Exit(0)
	}
	inbuf = getcommandline.GetCommandLineString()

	extension := filepath.Ext(inbuf)
	extension = strings.ToLower(extension)
	switch extension {
	case ".md5":
		WhichHash = md5hash
	case ".sha1":
		WhichHash = sha1hash
	case ".sha256":
		WhichHash = sha256hash
	case ".sha384":
		WhichHash = sha384hash
	case ".sha512":
		WhichHash = sha512hash
	default:
		fmt.Println()
		fmt.Println()
		fmt.Println(" Not a recognized hash extension.  Will assume sha1.")
		WhichHash = sha1hash
	} // switch case on extension for HashType

	fmt.Println()
	fmt.Print(" comparehashes written in Go.  GOOS =", runtime.GOOS, ".  ARCH=", runtime.GOARCH)

	fmt.Println(".  Last compiled ", LastCompiled)
	//            fmt.Println(".  HashType = md5, sha1, sha256, sha384, sha512.  WhichHash = ",HashName[WhichHash]);
	workingdir, _ := os.Getwd()
	execname, _ := os.Executable()
	ExecFI, _ := os.Stat(execname)
	LastLinkedTimeStamp := ExecFI.ModTime().Format("Mon Jan 2 2006 15:04:05 MST")
	fmt.Printf("%s has timestamp of %s.  Working directory is %s.  Full name of executable is %s.\n", ExecFI.Name(), LastLinkedTimeStamp, workingdir, execname)
	fmt.Println()

	// Read and parse the file with the hashes.

	HashesFile, err := os.Open(inbuf)
	if os.IsNotExist(err) {
		fmt.Println(inbuf, " does not exist.")
		os.Exit(1)
	} else { // we know that the file exists
		check(err, " Error opening hashes file.")
	}
	check(err, "Cannot open HashesFile.  Does it exist?  ")
	defer HashesFile.Close()

	scanner := bufio.NewScanner(HashesFile)
	scanner.Split(bufio.ScanLines) // I believe this is the default.  I may experiment to see if I need this line for my code to work, AFTER I debug it as it is.

	for { /* to read multiple lines */
		FileSize = 0
		readSuccess := scanner.Scan()
		if !readSuccess {
			break
		} // end main reading loop

		inputline := scanner.Text()
		if readErr = scanner.Err(); readErr != nil {
			if readErr == io.EOF {
				break
			} // reached EOF condition, so there are no more lines to read.
			fmt.Fprintln(os.Stderr, "Unknown error while reading from the HashesFile :", readErr)
			os.Exit(1)
		}

		if strings.HasPrefix(inputline, ";") || strings.HasPrefix(inputline, "#") || (len(inputline) <= 10) {
			continue
		} /* allow comments and essentially blank lines */

		tokenize.INITKN(inputline)
		tokenize.SetMapDelim('*')  // to ignore this character that begins the filename field.  Don't know why it's there.

		FirstToken, EOL := tokenize.GetTokenString(false)

		if EOL {
			fmt.Errorf(" Error while getting 1st token in the hashing file.  Skipping")
			continue
		}

		if strings.ContainsRune(FirstToken.Str, '.') { /* have filename first on line */
			TargetFilename = FirstToken.Str
			SecondToken, EOL := tokenize.GetTokenString(false) // Get hash string from the line in the file
			if EOL {
				fmt.Errorf(" Got EOL while getting HashValue (2nd) token in the hashing file.  Skipping \n")
				continue
			} /* if EOL */
			HashValueReadFromFile = SecondToken.Str

		} else { /* have hash first on line */
			HashValueReadFromFile = FirstToken.Str
			SecondToken, EOL := tokenize.GetTokenString(false) // Get name of file on which to compute the hash
			if EOL {
				fmt.Errorf(" Error while gatting TargetFilename token in the hashing file.  Skipping \n")
				continue
			} /* if EOL */

			if strings.ContainsRune(SecondToken.Str, '*') { // If it contains a *, it will be the first position.
				SecondToken.Str = SecondToken.Str[1:]
				if strings.ContainsRune(SecondToken.Str, '*') { // this should not happen
					fmt.Println(" Filename token still contains a * character.  Str:", SecondToken.Str, "  Skipping.")
					continue
				}
			}
			TargetFilename = (SecondToken.Str)
		} /* if have filename first or hash value first */

		/*
		   now to compute the hash, compare them, and output results
		*/
		/* Create Hash Section */
		TargetFile, err := os.Open(TargetFilename)
		//    exists := true;
		if os.IsNotExist(err) {
			fmt.Println(TargetFilename, " does not exist.")
			continue
		} else { // we know that the file exists
			check(err, " Error opening TargetFilename.")
		}

		defer TargetFile.Close()

		switch WhichHash { // Initialing case switch on WhichHash
		case md5hash:
			hasher = md5.New()
		case sha1hash:
			hasher = sha1.New()
		case sha256hash:
			hasher = sha256.New()
		case sha384hash:
			hasher = sha512.New384()
		case sha512hash:
			hasher = sha512.New()
		default:
			hasher = sha256.New()
		} /* initializing switch case on WhichHash */

		/*    This loop works, but there is a much shorter way.  I got this after asking for help on the mailing list.
		      FileReadBuffer := make([]byte,ReadBufferSize);
		      for {   // Repeat Until eof loop.
		        n,err := TargetFile.Read(FileReadBuffer);
		        if n == 0 || err == io.EOF { break }
		        check(err," Unexpected error while reading the target file on which to compute the hash,");
		        hasher.Write(FileReadBuffer[:n]);
		        FileSize += int64(n);
		      } // Repeat Until TargetFile.eof loop;
		*/

		FileSize, readErr = io.Copy(hasher, TargetFile)
		HashValueComputedStr = hex.EncodeToString(hasher.Sum(nil))

		// I got the idea to use the different base64 versions and my own hex converter code, just to see.
		// And I can also use sfprintf with the %x verb.  base64 versions are not useful as they use a larger
		// character set than hex.  I deleted all references to the base64 versions.  And the hex encoded and
		// sprintf using %x were the same, so I removed the sprintf code.
		//    HashValueComputedSprintf := fmt.Sprintf("%x",hasher.Sum(nil));

		//		fmt.Println(" Filename  = ", TargetFilename, ", FileSize = ", FileSize, ", ", HashName[WhichHash], " computed hash string -- ")
		fmt.Printf(" Filename  = %s, filesize = %d, using hash %s.\n", TargetFilename, FileSize, HashName[WhichHash])
		fmt.Println("       Read From File:", HashValueReadFromFile)
		fmt.Println(" Computed hex encoded:", HashValueComputedStr)
		//    fmt.Println(" Computed sprintf:",HashValueComputedSprintf);

		if HashValueReadFromFile == HashValueComputedStr {
			fmt.Print(" Matched.")
		} else {
			fmt.Print(" Not matched.")
		} /* if hashes */
		TargetFile.Close() // Close the handle to allow opening a target from the next line, if there is one.
		fmt.Println()
		fmt.Println()
		fmt.Println()
	} /* outer LOOP to read multiple lines */

	HashesFile.Close() // Don't really need this because of the defer statement.
	fmt.Println()
} // Main for comparehashes.go.

// ------------------------------------------------------- check -------------------------------
func check(e error, msg string) {
	if e != nil {
		fmt.Errorf("%s : ", msg)
		panic(e)
	}
}
<commit_msg>modified:   comparehashes/comparehashes.go -- Will ignore * char.<commit_after>package main

import (
	"bufio"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"encoding/hex"
	"fmt"
	"getcommandline"
	"hash"
	"io"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"tokenize"
)

/*
  REVISION HISTORY
  ----------------
   6 Apr 13 -- First modified version of module.  I will use VLI to compare all digits of the hashes.
  23 Apr 13 -- Fixed problem of a single line in the hashes file, that does not contain an EOL character, causes
                an immediate return without processing of the characters just read in.
  24 Apr 13 -- Added output of which file either matches or does not match.
  19 Sep 16 -- Finished conversion to Go, that was started 13 Sep 16.  Added the removed of '*' which is part of a std linux formated hash file.  And I forgot that
                 the routine allowed either order in the file.  If the token has a '.' I assume it is a filename, else it is a hash value.
  21 Sep 16 -- Fixed the case issue in tokenize.GetToken.  Edited code here to correspond to this fix.
  25 Nov 16 -- Need to not panic when target file is not found, only panic when hash file is not found.
                 And added a LastCompiled message and string.
  13 Oct 17 -- No changes here, but tokenize was changed so that horizontal tab char is now a delim.
  14 Oct 17 -- Tweaked output a bit.  And added executable timestamp code.
  19 Oct 17 -- Added ability to ignore the * that standard hash files for linux use.
*/

const LastCompiled = "19 Oct 2017"

//* ************************* MAIN ***************************************************************
func main() {

	const K = 1024
	const M = 1024 * 1024

	const (
		md5hash = iota
		sha1hash
		sha256hash
		sha384hash
		sha512hash
		HashType
	)

	const ReadBufferSize = M
	//  const ReadBufferSize = 80 * M;

	var HashName = [...]string{"md5", "sha1", "sha256", "sha384", "sha512"}
	var inbuf string
	var WhichHash int
	var readErr error
	var TargetFilename, HashValueReadFromFile, HashValueComputedStr string
	var hasher hash.Hash
	var FileSize int64

	if len(os.Args) <= 1 {
		fmt.Println(" Usage: comparehashes <hashFileName.ext> where .ext = [.md5|.sha1|.sha256|.sha384|.sha512]")
		os.Exit(0)
	}
	inbuf = getcommandline.GetCommandLineString()

	extension := filepath.Ext(inbuf)
	extension = strings.ToLower(extension)
	switch extension {
	case ".md5":
		WhichHash = md5hash
	case ".sha1":
		WhichHash = sha1hash
	case ".sha256":
		WhichHash = sha256hash
	case ".sha384":
		WhichHash = sha384hash
	case ".sha512":
		WhichHash = sha512hash
	default:
		fmt.Println()
		fmt.Println()
		fmt.Println(" Not a recognized hash extension.  Will assume sha1.")
		WhichHash = sha1hash
	} // switch case on extension for HashType

	fmt.Println()
	fmt.Print(" comparehashes written in Go.  GOOS =", runtime.GOOS, ".  ARCH=", runtime.GOARCH)

	fmt.Println(".  Last compiled ", LastCompiled)
	//            fmt.Println(".  HashType = md5, sha1, sha256, sha384, sha512.  WhichHash = ",HashName[WhichHash]);
	workingdir, _ := os.Getwd()
	execname, _ := os.Executable()
	ExecFI, _ := os.Stat(execname)
	LastLinkedTimeStamp := ExecFI.ModTime().Format("Mon Jan 2 2006 15:04:05 MST")
	fmt.Printf("%s has timestamp of %s.  Working directory is %s.  Full name of executable is %s.\n", ExecFI.Name(), LastLinkedTimeStamp, workingdir, execname)
	fmt.Println()

	// Read and parse the file with the hashes.

	HashesFile, err := os.Open(inbuf)
	if os.IsNotExist(err) {
		fmt.Println(inbuf, " does not exist.")
		os.Exit(1)
	} else { // we know that the file exists
		check(err, " Error opening hashes file.")
	}
	check(err, "Cannot open HashesFile.  Does it exist?  ")
	defer HashesFile.Close()

	scanner := bufio.NewScanner(HashesFile)
	scanner.Split(bufio.ScanLines) // I believe this is the default.  I may experiment to see if I need this line for my code to work, AFTER I debug it as it is.

	for { /* to read multiple lines */
		FileSize = 0
		readSuccess := scanner.Scan()
		if !readSuccess {
			break
		} // end main reading loop

		inputline := scanner.Text()
		if readErr = scanner.Err(); readErr != nil {
			if readErr == io.EOF {
				break
			} // reached EOF condition, so there are no more lines to read.
			fmt.Fprintln(os.Stderr, "Unknown error while reading from the HashesFile :", readErr)
			os.Exit(1)
		}

		if strings.HasPrefix(inputline, ";") || strings.HasPrefix(inputline, "#") || (len(inputline) <= 10) {
			continue
		} /* allow comments and essentially blank lines */

		tokenize.INITKN(inputline)
		tokenize.SetMapDelim('*') // to ignore this character that begins the filename field.  Don't know why it's there.

		FirstToken, EOL := tokenize.GetTokenString(false)

		if EOL {
			fmt.Errorf(" Error while getting 1st token in the hashing file.  Skipping")
			continue
		}

		if strings.ContainsRune(FirstToken.Str, '.') { /* have filename first on line */
			TargetFilename = FirstToken.Str
			SecondToken, EOL := tokenize.GetTokenString(false) // Get hash string from the line in the file
			if EOL {
				fmt.Errorf(" Got EOL while getting HashValue (2nd) token in the hashing file.  Skipping \n")
				continue
			} /* if EOL */
			HashValueReadFromFile = SecondToken.Str

		} else { /* have hash first on line */
			HashValueReadFromFile = FirstToken.Str
			SecondToken, EOL := tokenize.GetTokenString(false) // Get name of file on which to compute the hash
			if EOL {
				fmt.Errorf(" Error while gatting TargetFilename token in the hashing file.  Skipping \n")
				continue
			} /* if EOL */

			if strings.ContainsRune(SecondToken.Str, '*') { // If it contains a *, it will be the first position.
				SecondToken.Str = SecondToken.Str[1:]
				if strings.ContainsRune(SecondToken.Str, '*') { // this should not happen
					fmt.Println(" Filename token still contains a * character.  Str:", SecondToken.Str, "  Skipping.")
					continue
				}
			}
			TargetFilename = (SecondToken.Str)
		} /* if have filename first or hash value first */

		/*
		   now to compute the hash, compare them, and output results
		*/
		/* Create Hash Section */
		TargetFile, err := os.Open(TargetFilename)
		//    exists := true;
		if os.IsNotExist(err) {
			fmt.Println(TargetFilename, " does not exist.")
			continue
		} else { // we know that the file exists
			check(err, " Error opening TargetFilename.")
		}

		defer TargetFile.Close()

		switch WhichHash { // Initialing case switch on WhichHash
		case md5hash:
			hasher = md5.New()
		case sha1hash:
			hasher = sha1.New()
		case sha256hash:
			hasher = sha256.New()
		case sha384hash:
			hasher = sha512.New384()
		case sha512hash:
			hasher = sha512.New()
		default:
			hasher = sha256.New()
		} /* initializing switch case on WhichHash */

		/*    This loop works, but there is a much shorter way.  I got this after asking for help on the mailing list.
		      FileReadBuffer := make([]byte,ReadBufferSize);
		      for {   // Repeat Until eof loop.
		        n,err := TargetFile.Read(FileReadBuffer);
		        if n == 0 || err == io.EOF { break }
		        check(err," Unexpected error while reading the target file on which to compute the hash,");
		        hasher.Write(FileReadBuffer[:n]);
		        FileSize += int64(n);
		      } // Repeat Until TargetFile.eof loop;
		*/

		FileSize, readErr = io.Copy(hasher, TargetFile)
		HashValueComputedStr = hex.EncodeToString(hasher.Sum(nil))

		// I got the idea to use the different base64 versions and my own hex converter code, just to see.
		// And I can also use sfprintf with the %x verb.  base64 versions are not useful as they use a larger
		// character set than hex.  I deleted all references to the base64 versions.  And the hex encoded and
		// sprintf using %x were the same, so I removed the sprintf code.
		//    HashValueComputedSprintf := fmt.Sprintf("%x",hasher.Sum(nil));

		//		fmt.Println(" Filename  = ", TargetFilename, ", FileSize = ", FileSize, ", ", HashName[WhichHash], " computed hash string -- ")
		fmt.Printf(" Filename  = %s, filesize = %d, using hash %s.\n", TargetFilename, FileSize, HashName[WhichHash])
		fmt.Println("       Read From File:", HashValueReadFromFile)
		fmt.Println(" Computed hex encoded:", HashValueComputedStr)
		//    fmt.Println(" Computed sprintf:",HashValueComputedSprintf);

		if HashValueReadFromFile == HashValueComputedStr {
			fmt.Print(" Matched.")
		} else {
			fmt.Print(" Not matched.")
		} /* if hashes */
		TargetFile.Close() // Close the handle to allow opening a target from the next line, if there is one.
		fmt.Println()
		fmt.Println()
		fmt.Println()
	} /* outer LOOP to read multiple lines */

	HashesFile.Close() // Don't really need this because of the defer statement.
	fmt.Println()
} // Main for comparehashes.go.

// ------------------------------------------------------- check -------------------------------
func check(e error, msg string) {
	if e != nil {
		fmt.Errorf("%s : ", msg)
		panic(e)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"archive/zip"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

type ModList struct {
	Mods []Mod `json:"mods"`
}

type Mod struct {
	Name    string `json:"name"`
	Enabled bool   `json:"enabled,string"`
}

// List mods installed in the factorio/mods directory
func listInstalledMods(modDir string) ([]string, error) {
	result := []string{}

	files, err := ioutil.ReadDir(modDir)
	if err != nil {
		log.Printf("Error listing installed mods: %s", err)
		return result, err
	}
	for _, f := range files {
		if f.Name() == "mod-list.json" {
			continue
		}
		result = append(result, f.Name())
	}

	return result, nil
}

// Delete mod by provided filename
func rmMod(modName string) error {
	removed := false
	if modName == "" {
		return errors.New("No mod name provided.")
	}
	// Get list of installed mods
	installedMods, err := listInstalledMods(config.FactorioModsDir)
	if err != nil {
		log.Printf("Error in remove mod list: %s", err)
		return err
	}

	// Check if provided mod matches one thats installed else return err
	for _, mod := range installedMods {
		if strings.Contains(mod, modName) {
			log.Printf("Removing mod: %s", mod)
			err := os.Remove(filepath.Join(config.FactorioModsDir, mod))
			if err != nil {
				log.Printf("Error removing mod %s: %s", mod, err)
				return err
			}
			removed = true
			log.Printf("Removed mod: %s", mod)
		}
	}

	if !removed {
		log.Printf("Did not remove mod: %s", modName)
		return errors.New(fmt.Sprintf("Did not remove mod: %s", modName))
	}

	return nil
}

func rmModPack(modpack string) error {
	removed := false
	if modpack == "" {
		return errors.New("No mod pack name provided.")
	}
	// Get list of modpacks
	modpacks, err := listModPacks(filepath.Join(config.FactorioDir, "modpacks"))
	if err != nil {
		log.Printf("Error listing modpacks in rmModPack: %s", err)
		return err
	}

	for _, m := range modpacks {
		if strings.Contains(m, modpack) {
			log.Printf("Removing modpack: %s", m)
			err := os.Remove(filepath.Join(config.FactorioDir, "modpacks", m))
			if err != nil {
				log.Printf("Error trying to remove modpack: %s: %s", m, err)
				return err
			}
			removed = true
			log.Printf("Removed modpack: %s", m)
		}
	}

	if !removed {
		log.Printf("Did not remove modpack: %s", modpack)
		return errors.New(fmt.Sprintf("Did not remove modpack: %s", modpack))
	}

	return nil
}

func createModPackDir() error {
	err := os.Mkdir(filepath.Join(config.FactorioDir, "modpacks"), 0775)
	if err != nil {
		log.Printf("Could not create modpacks directory: %s", err)
		return err
	}

	return nil
}

// Create's modpack zip file from provided title, mods parameter is a string of mod filenames
func createModPack(title string, mods ...string) error {
	zipfile, err := os.Create(filepath.Join(config.FactorioDir, "modpacks", title+".zip"))
	if err != nil {
		log.Printf("Error creating zipfile: %s, error: %s", title, err)
	}
	defer zipfile.Close()
	// Create Zip writer
	z := zip.NewWriter(zipfile)
	defer z.Close()

	for _, mod := range mods {
		// Process mod file, add to zipfile
		f, err := os.Open(filepath.Join(config.FactorioDir, "mods", mod))
		if err != nil {
			log.Printf("Error creating modpack file %s for archival: ", mod, err)
			return err
		}
		// Read contents of mod to be compressed
		modfile, err := ioutil.ReadAll(f)
		if err != nil {
			log.Printf("Error reading modfile contents: %s", err)
			continue
		}
		// Add file to zip archive
		fmt.Println(mod)
		zip, err := z.Create(mod)
		if err != nil {
			log.Printf("Error adding file: %s to zip: %s", f.Name, err)
			continue
		}
		// Write file contents to zip archive
		_, err = zip.Write(modfile)
		if err != nil {
			log.Printf("Error writing to zipfile: %s", err)
			continue
		}
	}

	err = z.Close()
	if err != nil {
		log.Printf("Error trying to zip: %s, error: %s", title, err)
	}

	return nil
}

func listModPacks(modDir string) ([]string, error) {
	result := []string{}

	files, err := ioutil.ReadDir(modDir)
	if err != nil {
		log.Printf("Error listing modpacks: %s", err)
		return result, err
	}
	for _, f := range files {
		result = append(result, f.Name())
	}

	return result, nil
}

// Parses mod-list.json file in factorio/mods
// returns ModList struct
func parseModList() (ModList, error) {
	var mods ModList
	modListFile := filepath.Join(config.FactorioModsDir, "mod-list.json")

	modList, err := ioutil.ReadFile(modListFile)
	if err != nil {
		log.Printf("Error reading mod-list.json file: %s", err)
		return mods, err
	}

	err = json.Unmarshal(modList, &mods)
	if err != nil {
		log.Printf("Error parsing mod-list.json JSON: %s", err)
		return mods, err
	}

	return mods, nil
}

// Toggles Enabled boolean for mod specified in name parameter in mod-list.json file
func (m *ModList) toggleMod(name string) error {
	found := false
	status := false

	for i := range m.Mods {
		if m.Mods[i].Name == name {
			found = true
			if m.Mods[i].Enabled == true {
				m.Mods[i].Enabled = false
			} else {
				m.Mods[i].Enabled = true
				status = true
			}
		}
	}

	if found {
		err := m.save()
		if err != nil {
			log.Printf("Error saving changes to mod-list-.json file: %s", err)
			return err
		}
		log.Printf("Mod: %s was toggled to %v", name, status)
	}

	return nil
}

// Saves ModList object to mod-list.json file
// Overwrites old file
func (m ModList) save() error {
	modListFile := filepath.Join(config.FactorioModsDir, "mod-list.json")
	b, _ := json.MarshalIndent(m, "", "    ")

	err := ioutil.WriteFile(modListFile, b, 0644)
	if err != nil {
		log.Printf("Error writing to mod-list.json file: %s", err)
		return err
	}

	return nil
}

//TODO Add method to allow downloading all installed mods in zip file
<commit_msg>Fix error check conditional<commit_after>package main

import (
	"archive/zip"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

type ModList struct {
	Mods []Mod `json:"mods"`
}

type Mod struct {
	Name    string `json:"name"`
	Enabled bool   `json:"enabled,string"`
}

// List mods installed in the factorio/mods directory
func listInstalledMods(modDir string) ([]string, error) {
	result := []string{}

	files, err := ioutil.ReadDir(modDir)
	if err != nil {
		log.Printf("Error listing installed mods: %s", err)
		return result, err
	}
	for _, f := range files {
		if f.Name() == "mod-list.json" {
			continue
		}
		result = append(result, f.Name())
	}

	return result, nil
}

// Delete mod by provided filename
func rmMod(modName string) error {
	removed := false
	if modName == "" {
		return errors.New("No mod name provided.")
	}
	// Get list of installed mods
	installedMods, err := listInstalledMods(config.FactorioModsDir)
	if err != nil {
		log.Printf("Error in remove mod list: %s", err)
		return err
	}

	// Check if provided mod matches one thats installed else return err
	for _, mod := range installedMods {
		if strings.Contains(mod, modName) {
			log.Printf("Removing mod: %s", mod)
			err := os.Remove(filepath.Join(config.FactorioModsDir, mod))
			if err != nil {
				log.Printf("Error removing mod %s: %s", mod, err)
				return err
			}
			removed = true
			log.Printf("Removed mod: %s", mod)
		}
	}

	if !removed {
		log.Printf("Did not remove mod: %s", modName)
		return errors.New(fmt.Sprintf("Did not remove mod: %s", modName))
	}

	return nil
}

func rmModPack(modpack string) error {
	removed := false
	if modpack == "" {
		return errors.New("No mod pack name provided.")
	}
	// Get list of modpacks
	modpacks, err := listModPacks(filepath.Join(config.FactorioDir, "modpacks"))
	if err != nil {
		log.Printf("Error listing modpacks in rmModPack: %s", err)
		return err
	}

	for _, m := range modpacks {
		if strings.Contains(m, modpack) {
			log.Printf("Removing modpack: %s", m)
			err := os.Remove(filepath.Join(config.FactorioDir, "modpacks", m))
			if err != nil {
				log.Printf("Error trying to remove modpack: %s: %s", m, err)
				return err
			}
			removed = true
			log.Printf("Removed modpack: %s", m)
		}
	}

	if !removed {
		log.Printf("Did not remove modpack: %s", modpack)
		return errors.New(fmt.Sprintf("Did not remove modpack: %s", modpack))
	}

	return nil
}

func createModPackDir() error {
	err := os.Mkdir(filepath.Join(config.FactorioDir, "modpacks"), 0775)
	if err != nil && os.IsNotExist(err) {
		log.Printf("Could not create modpacks directory: %s", err)
		return err
	}

	return nil
}

// Create's modpack zip file from provided title, mods parameter is a string of mod filenames
func createModPack(title string, mods ...string) error {
	zipfile, err := os.Create(filepath.Join(config.FactorioDir, "modpacks", title+".zip"))
	if err != nil {
		log.Printf("Error creating zipfile: %s, error: %s", title, err)
	}
	defer zipfile.Close()
	// Create Zip writer
	z := zip.NewWriter(zipfile)
	defer z.Close()

	for _, mod := range mods {
		// Process mod file, add to zipfile
		f, err := os.Open(filepath.Join(config.FactorioDir, "mods", mod))
		if err != nil {
			log.Printf("Error creating modpack file %s for archival: ", mod, err)
			return err
		}
		// Read contents of mod to be compressed
		modfile, err := ioutil.ReadAll(f)
		if err != nil {
			log.Printf("Error reading modfile contents: %s", err)
			continue
		}
		// Add file to zip archive
		fmt.Println(mod)
		zip, err := z.Create(mod)
		if err != nil {
			log.Printf("Error adding file: %s to zip: %s", f.Name, err)
			continue
		}
		// Write file contents to zip archive
		_, err = zip.Write(modfile)
		if err != nil {
			log.Printf("Error writing to zipfile: %s", err)
			continue
		}
	}

	err = z.Close()
	if err != nil {
		log.Printf("Error trying to zip: %s, error: %s", title, err)
	}

	return nil
}

func listModPacks(modDir string) ([]string, error) {
	result := []string{}

	files, err := ioutil.ReadDir(modDir)
	if err != nil {
		log.Printf("Error listing modpacks: %s", err)
		return result, err
	}
	for _, f := range files {
		result = append(result, f.Name())
	}

	return result, nil
}

// Parses mod-list.json file in factorio/mods
// returns ModList struct
func parseModList() (ModList, error) {
	var mods ModList
	modListFile := filepath.Join(config.FactorioModsDir, "mod-list.json")

	modList, err := ioutil.ReadFile(modListFile)
	if err != nil {
		log.Printf("Error reading mod-list.json file: %s", err)
		return mods, err
	}

	err = json.Unmarshal(modList, &mods)
	if err != nil {
		log.Printf("Error parsing mod-list.json JSON: %s", err)
		return mods, err
	}

	return mods, nil
}

// Toggles Enabled boolean for mod specified in name parameter in mod-list.json file
func (m *ModList) toggleMod(name string) error {
	found := false
	status := false

	for i := range m.Mods {
		if m.Mods[i].Name == name {
			found = true
			if m.Mods[i].Enabled == true {
				m.Mods[i].Enabled = false
			} else {
				m.Mods[i].Enabled = true
				status = true
			}
		}
	}

	if found {
		err := m.save()
		if err != nil {
			log.Printf("Error saving changes to mod-list-.json file: %s", err)
			return err
		}
		log.Printf("Mod: %s was toggled to %v", name, status)
	}

	return nil
}

// Saves ModList object to mod-list.json file
// Overwrites old file
func (m ModList) save() error {
	modListFile := filepath.Join(config.FactorioModsDir, "mod-list.json")
	b, _ := json.MarshalIndent(m, "", "    ")

	err := ioutil.WriteFile(modListFile, b, 0644)
	if err != nil {
		log.Printf("Error writing to mod-list.json file: %s", err)
		return err
	}

	return nil
}

//TODO Add method to allow downloading all installed mods in zip file
<|endoftext|>


<commit_before>package rest

import (
    "bufio"
    "bytes"
    "io"
    "log"
    "github.com/johnny-morrice/godelbrot/process"
    lib "github.com/johnny-morrice/godelbrot/libgodelbrot"
)

type renderbuffers struct {
    png bytes.Buffer
    info bytes.Buffer
    nextinfo bytes.Buffer
    report bytes.Buffer
}

func (rb *renderbuffers) logReport() {
    sc := bufio.NewScanner(&rb.report)
    for sc.Scan() {
        err := sc.Err()
        if err != nil {
            log.Printf("Error while printing error (omg!): %v", err)
        }
        log.Println(sc.Text())
    }
}

func (rb *renderbuffers) input(info *lib.Info) error {
    return lib.WriteInfo(&rb.info, info)
}

// renderservice renders fractals
type renderservice struct {
    s sem
}

// makeRenderService creates a render service that allows at most `concurrent` concurrent tasks.
func makeRenderservice(concurrent uint) renderservice {
    rs := renderservice{}
    rs.s = semaphor(concurrent)
    return rs
}

// render a fractal into the renderbuffers
func (rs *renderservice) render(rbuf *renderbuffers, zoomArgs []string) error {
    rs.s.acquire(1)
    var err error
    if zoomArgs == nil || len(zoomArgs) == 0 {
        debugf("Render in progress")
        tee := io.TeeReader(&rbuf.info, &rbuf.nextinfo)
        err = process.Render(tee, &rbuf.png, &rbuf.report)
        debugf("Render done")
    } else {
        debugf("ZoomRender in progress")
        next, zerr := process.ZoomRender(&rbuf.info, &rbuf.png, &rbuf.report, zoomArgs)
        err = zerr
        if err == nil {
            _, err = io.Copy(&rbuf.nextinfo, next)
        }
        debugf("ZoomRender done")
    }
    rs.s.release(1)
    return err
}<commit_msg>Debug trace in renderservice<commit_after>package rest

import (
    "bufio"
    "bytes"
    "io"
    "log"
    "strings"
    "github.com/johnny-morrice/godelbrot/process"
    lib "github.com/johnny-morrice/godelbrot/libgodelbrot"
)

type renderbuffers struct {
    png bytes.Buffer
    info bytes.Buffer
    nextinfo bytes.Buffer
    report bytes.Buffer
}

func (rb *renderbuffers) logReport() {
    sc := bufio.NewScanner(&rb.report)
    for sc.Scan() {
        err := sc.Err()
        if err != nil {
            log.Printf("Error while printing error (omg!): %v", err)
        }
        log.Println(sc.Text())
    }
}

func (rb *renderbuffers) input(info *lib.Info) error {
    return lib.WriteInfo(&rb.info, info)
}

// renderservice renders fractals
type renderservice struct {
    s sem
}

// makeRenderService creates a render service that allows at most `concurrent` concurrent tasks.
func makeRenderservice(concurrent uint) renderservice {
    rs := renderservice{}
    rs.s = semaphor(concurrent)
    return rs
}

// render a fractal into the renderbuffers
func (rs renderservice) render(rbuf *renderbuffers, zoomArgs []string) error {
    rs.s.acquire(1)
    var err error
    if zoomArgs == nil || len(zoomArgs) == 0 {
        debugf("Render in progress")
        tee := io.TeeReader(&rbuf.info, &rbuf.nextinfo)
        err = process.Render(tee, &rbuf.png, &rbuf.report)
        debugf("Render done")
    } else {
        debugf("ZoomRender in progress: %v", strings.Join(zoomArgs, " "))
        next, zerr := process.ZoomRender(&rbuf.info, &rbuf.png, &rbuf.report, zoomArgs)
        err = zerr
        if err == nil {
            _, err = io.Copy(&rbuf.nextinfo, next)
        }
        debugf("ZoomRender done")
    }
    rs.s.release(1)
    return err
}<|endoftext|>


<commit_before>package m_etcd

import (
	"os"
	"strings"
	"testing"

	"github.com/coreos/go-etcd/etcd"
)

func TestEtcdClientIntegration(t *testing.T) {
	if os.Getenv("IntegrationTests") == "" {
		return
	}

	eclient := createEtcdClient(t)

	mclient := NewEtcdClient("test", eclient)

	if err := mclient.SubmitTask("testid1"); err != nil {
		t.Fatalf("Unable to submit task.   error:%v", err)
	}

	if err := mclient.SubmitTask("testid1"); err == nil {
		t.Fatalf("Unable to submit task.   error:%v", err)
	}
}

func createEtcdClient(t *testing.T) *etcd.Client {
	peers_from_environment := os.Getenv("ETCDCTL_PEERS") //This is the same ENV that etcdctl uses for Peers.

	if peers_from_environment == "" {
		peers_from_environment = "localhost:5001,localhost:5002,localhost:5003"
	}

	peers := strings.Split(peers_from_environment, ",")

	client := etcd.NewClient(peers)

	ok := client.SyncCluster()

	if !ok {
		t.Fatalf("Cannot sync with the cluster using peers " + strings.Join(peers, ", "))
	}

	if !isEtcdUp(client, t) {
		t.Fatalf("While testing etcd, the test couldn't connect to etcd. " + strings.Join(peers, ", "))
	}

	return client

}
<commit_msg>Update client_test.go<commit_after>package m_etcd

import (
	"os"
	"strings"
	"testing"

	"github.com/coreos/go-etcd/etcd"
)

func TestEtcdClientIntegration(t *testing.T) {
	if os.Getenv("IntegrationTests") == "" {
		return
	}

	eclient := createEtcdClient(t)

	mclient := NewEtcdClient("test", eclient)

	if err := mclient.SubmitTask("testid1"); err != nil {
		t.Fatalf("Unable to submit task.   error:%v", err)
	}

	if err := mclient.SubmitTask("testid1"); err == nil {
		t.Fatalf("We shoudln't have been allowed to submit the same task twice.   error:%v", err)
	}
}

func createEtcdClient(t *testing.T) *etcd.Client {
	peers_from_environment := os.Getenv("ETCDCTL_PEERS") //This is the same ENV that etcdctl uses for Peers.

	if peers_from_environment == "" {
		peers_from_environment = "localhost:5001,localhost:5002,localhost:5003"
	}

	peers := strings.Split(peers_from_environment, ",")

	client := etcd.NewClient(peers)

	ok := client.SyncCluster()

	if !ok {
		t.Fatalf("Cannot sync with the cluster using peers " + strings.Join(peers, ", "))
	}

	if !isEtcdUp(client, t) {
		t.Fatalf("While testing etcd, the test couldn't connect to etcd. " + strings.Join(peers, ", "))
	}

	return client

}
<|endoftext|>


<commit_before>package gitconfig

import (
	"fmt"
	. "github.com/onsi/gomega"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
)

func TestGlobal(t *testing.T) {
	RegisterTestingT(t)

	var (
		err error
	)

	username, err := Global("user.name")
	Expect(err).NotTo(HaveOccurred())
	fmt.Println("user.name: ", username)
}

func TestLocal(t *testing.T) {
	RegisterTestingT(t)

	var (
		err error
	)

	url, err := Local("remotes.origin.url")
	Expect(err).NotTo(HaveOccurred())
	fmt.Println("remotes.origin.url: ", url)
}

func TestExecGitConfig(t *testing.T) {
	RegisterTestingT(t)

	reset := withGitConfigFile(`
[user]
    name  = deeeet
    email = deeeet@example.com
`)

	defer reset()

	var (
		err error
	)

	username, err := execGitConfig("user.name")
	Expect(err).NotTo(HaveOccurred())
	Expect(username).To(Equal("deeeet"))

	email, err := execGitConfig("user.email")
	Expect(err).NotTo(HaveOccurred())
	Expect(email).To(Equal("deeeet@example.com"))
}

func withGitConfigFile(content string) func() {
	tmpdir, err := ioutil.TempDir("", "go-gitconfig-test")
	if err != nil {
		panic(err)
	}

	tmpGitConfigFile := filepath.Join(tmpdir, "gitconfig")

	ioutil.WriteFile(
		tmpGitConfigFile,
		[]byte(content),
		0777,
	)

	prevGitConfigEnv := os.Getenv("GIT_CONFIG")
	os.Setenv("GIT_CONFIG", tmpGitConfigFile)

	return func() {
		os.Setenv("GIT_CONFIG", prevGitConfigEnv)
	}
}
<commit_msg>Delete test which is not worked on Drone.io<commit_after>package gitconfig

import (
	"fmt"
	. "github.com/onsi/gomega"
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
)

func TestGlobal(t *testing.T) {
	RegisterTestingT(t)

	var (
		err error
	)

	username, err := Global("user.name")
	Expect(err).NotTo(HaveOccurred())
	fmt.Println("user.name: ", username)
}

// func TestLocal(t *testing.T) {
// 	RegisterTestingT(t)

// 	var (
// 		err error
// 	)

// 	url, err := Local("remote.origin.url")
// 	Expect(err).NotTo(HaveOccurred())
// 	fmt.Println("remotes.origin.url: ", url)
// }

func TestExecGitConfig(t *testing.T) {
	RegisterTestingT(t)

	reset := withGitConfigFile(`
[user]
    name  = deeeet
    email = deeeet@example.com
`)

	defer reset()

	var (
		err error
	)

	username, err := execGitConfig("user.name")
	Expect(err).NotTo(HaveOccurred())
	Expect(username).To(Equal("deeeet"))

	email, err := execGitConfig("user.email")
	Expect(err).NotTo(HaveOccurred())
	Expect(email).To(Equal("deeeet@example.com"))
}

func withGitConfigFile(content string) func() {
	tmpdir, err := ioutil.TempDir("", "go-gitconfig-test")
	if err != nil {
		panic(err)
	}

	tmpGitConfigFile := filepath.Join(tmpdir, "gitconfig")

	ioutil.WriteFile(
		tmpGitConfigFile,
		[]byte(content),
		0777,
	)

	prevGitConfigEnv := os.Getenv("GIT_CONFIG")
	os.Setenv("GIT_CONFIG", tmpGitConfigFile)

	return func() {
		os.Setenv("GIT_CONFIG", prevGitConfigEnv)
	}
}
<|endoftext|>