<commit_before>package admin

import (
	"bytes"
	"database/sql"
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/jinzhu/gorm"
	"github.com/jinzhu/now"
	"github.com/qor/qor"
	"github.com/qor/qor/media_library"
	"github.com/qor/qor/resource"
	"github.com/qor/qor/roles"
	"github.com/qor/qor/utils"
)

type Meta struct {
	base          *Resource
	Name          string
	DBName        string
	Alias         string
	Label         string
	Type          string
	Valuer        func(interface{}, *qor.Context) interface{}
	Setter        func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context)
	Metas         []resource.Metaor
	Resource      resource.Resourcer
	Collection    interface{}
	GetCollection func(interface{}, *qor.Context) [][]string
	Permission    *roles.Permission
}

func (meta *Meta) GetName() string {
	return meta.Name
}

func (meta *Meta) GetFieldName() string {
	return meta.Alias
}

func (meta *Meta) GetMetas() []resource.Metaor {
	if len(meta.Metas) > 0 {
		return meta.Metas
	} else if meta.Resource == nil {
		return []resource.Metaor{}
	} else {
		return meta.Resource.GetMetas([]string{})
	}
}

func (meta *Meta) GetResource() resource.Resourcer {
	return meta.Resource
}

func (meta *Meta) GetValuer() func(interface{}, *qor.Context) interface{} {
	return meta.Valuer
}

func (meta *Meta) GetSetter() func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
	return meta.Setter
}

func (meta *Meta) HasPermission(mode roles.PermissionMode, context *qor.Context) bool {
	if meta.Permission == nil {
		return true
	}
	return meta.Permission.HasPermission(mode, context.Roles...)
}

func getField(fields map[string]*gorm.Field, name string) (*gorm.Field, bool) {
	for _, field := range fields {
		if field.Name == name || field.DBName == name {
			return field, true
		}
	}
	return nil, false
}

func (meta *Meta) updateMeta() {
	if meta.Name == "" {
		utils.ExitWithMsg("Meta should have name: %v", reflect.ValueOf(meta).Type())
	} else if meta.Alias == "" {
		meta.Alias = meta.Name
	}

	if meta.Label == "" {
		meta.Label = utils.HumanizeString(meta.Name)
	}

	var (
		scope       = &gorm.Scope{Value: meta.base.Value}
		nestedField = strings.Contains(meta.Alias, ".")
		field       *gorm.Field
		hasColumn   bool
	)

	if nestedField {
		subModel, name := utils.ParseNestedField(reflect.ValueOf(meta.base.Value), meta.Alias)
		subScope := &gorm.Scope{Value: subModel.Interface()}
		field, hasColumn = getField(subScope.Fields(), name)
	} else {
		if field, hasColumn = getField(scope.Fields(), meta.Alias); hasColumn {
			meta.Alias = field.Name
			meta.DBName = field.DBName
		}
	}

	var fieldType reflect.Type
	if hasColumn {
		fieldType = field.Field.Type()
		for fieldType.Kind() == reflect.Ptr {
			fieldType = fieldType.Elem()
		}
	}

	// Set Meta Type
	if meta.Type == "" && hasColumn {
		if relationship := field.Relationship; relationship != nil {
			if relationship.Kind == "has_one" {
				meta.Type = "single_edit"
			} else if relationship.Kind == "has_many" {
				meta.Type = "collection_edit"
			} else if relationship.Kind == "belongs_to" {
				meta.Type = "select_one"
			} else if relationship.Kind == "many_to_many" {
				meta.Type = "select_many"
			}
		} else {
			switch fieldType.Kind().String() {
			case "string":
				if size, ok := utils.ParseTagOption(field.Tag.Get("sql"))["SIZE"]; ok {
					if i, _ := strconv.Atoi(size); i > 255 {
						meta.Type = "text"
					} else {
						meta.Type = "string"
					}
				} else if text, ok := utils.ParseTagOption(field.Tag.Get("sql"))["TYPE"]; ok && text == "text" {
					meta.Type = "text"
				} else {
					meta.Type = "string"
				}
			case "bool":
				meta.Type = "checkbox"
			default:
				if regexp.MustCompile(`^(.*)?(u)?(int)(\d+)?`).MatchString(fieldType.Kind().String()) {
					meta.Type = "number"
				} else if regexp.MustCompile(`^(.*)?(float)(\d+)?`).MatchString(fieldType.Kind().String()) {
					meta.Type = "float"
				} else if _, ok := reflect.New(fieldType).Interface().(*time.Time); ok {
					meta.Type = "datetime"
				} else if _, ok := reflect.New(fieldType).Interface().(media_library.MediaLibrary); ok {
					meta.Type = "file"
				}
			}
		}
	}

	// Set Meta Resource
	if meta.Resource == nil {
		if hasColumn && (field.Relationship != nil) {
			var result interface{}
			if fieldType.Kind().String() == "struct" {
				result = reflect.New(field.Field.Type()).Interface()
			} else if fieldType.Kind().String() == "slice" {
				result = reflect.New(field.Field.Type().Elem()).Interface()
			}

			res := meta.base.GetAdmin().NewResource(result)
			res.compile()
			meta.Resource = res
		}
	}

	if meta.Type == "serialize_argument" {
		type SerializeArgumentInterface interface {
			GetSerializeArgumentResource() *Resource
			GetSerializeArgument() interface{}
			SetSerializeArgument(value interface{})
		}

		if meta.Valuer == nil {
			meta.Valuer = func(value interface{}, context *qor.Context) interface{} {
				if serializeArgument, ok := value.(SerializeArgumentInterface); ok {
					return struct {
						Value    interface{}
						Resource *Resource
					}{
						Value:    serializeArgument.GetSerializeArgument(),
						Resource: serializeArgument.GetSerializeArgumentResource(),
					}
				}
				return nil
			}
		}

		if meta.Setter == nil {
			meta.Setter = func(result interface{}, metaValue *resource.MetaValue, context *qor.Context) {
				if serializeArgument, ok := result.(SerializeArgumentInterface); ok {
					if res := serializeArgument.GetSerializeArgumentResource(); res != nil {
						value := res.NewStruct()

						for _, meta := range res.GetMetas([]string{}) {
							metaValue := metaValue.MetaValues.Get(meta.GetName())
							if setter := meta.GetSetter(); setter != nil {
								setter(value, metaValue, context)
							}
						}

						serializeArgument.SetSerializeArgument(value)
					}
				}
			}
		}
	}

	// Set Meta Valuer
	if meta.Valuer == nil {
		if hasColumn {
			meta.Valuer = func(value interface{}, context *qor.Context) interface{} {
				scope := context.GetDB().NewScope(value)
				alias := meta.Alias
				if nestedField {
					fields := strings.Split(alias, ".")
					alias = fields[len(fields)-1]
				}

				if f, ok := scope.FieldByName(alias); ok {
					if field.Relationship != nil {
						if f.Field.CanAddr() && !scope.PrimaryKeyZero() {
							context.GetDB().Model(value).Related(f.Field.Addr().Interface(), meta.Alias)
						}
					}
					if f.Field.CanAddr() {
						return f.Field.Addr().Interface()
					} else {
						return f.Field.Interface()
					}
				}

				return ""
			}
		} else {
			utils.ExitWithMsg("Unsupported meta name %v for resource %v", meta.Name, reflect.TypeOf(meta.base.Value))
		}
	}

	scopeField, _ := scope.FieldByName(meta.Alias)

	// Set Meta Collection
	if meta.Collection != nil {
		if maps, ok := meta.Collection.([]string); ok {
			meta.GetCollection = func(interface{}, *qor.Context) (results [][]string) {
				for _, value := range maps {
					results = append(results, []string{value, value})
				}
				return
			}
		} else if maps, ok := meta.Collection.([][]string); ok {
			meta.GetCollection = func(interface{}, *qor.Context) [][]string {
				return maps
			}
		} else if f, ok := meta.Collection.(func(interface{}, *qor.Context) [][]string); ok {
			meta.GetCollection = f
		} else {
			utils.ExitWithMsg("Unsupported Collection format for meta %v of resource %v", meta.Name, reflect.TypeOf(meta.base.Value))
		}
	} else if meta.Type == "select_one" || meta.Type == "select_many" {
		if scopeField.Relationship != nil {
			fieldType := scopeField.StructField.Struct.Type
			if fieldType.Kind() == reflect.Slice {
				fieldType = fieldType.Elem()
			}

			meta.GetCollection = func(value interface{}, context *qor.Context) (results [][]string) {
				values := reflect.New(reflect.SliceOf(fieldType)).Interface()
				context.GetDB().Find(values)
				reflectValues := reflect.Indirect(reflect.ValueOf(values))
				for i := 0; i < reflectValues.Len(); i++ {
					scope := scope.New(reflectValues.Index(i).Interface())
					primaryKey := fmt.Sprintf("%v", scope.PrimaryKeyValue())
					results = append(results, []string{primaryKey, utils.Stringify(reflectValues.Index(i).Interface())})
				}
				return
			}
		} else {
			utils.ExitWithMsg("%v meta type %v needs Collection", meta.Name, meta.Type)
		}
	}

	if meta.Setter == nil && hasColumn {
		if relationship := field.Relationship; relationship != nil {
			if meta.Type == "select_one" || meta.Type == "select_many" {
				meta.Setter = func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
					scope := &gorm.Scope{Value: resource}
					field := reflect.Indirect(reflect.ValueOf(resource)).FieldByName(meta.Alias)

					if field.Kind() == reflect.Ptr && field.IsNil() {
						field.Set(utils.NewValue(field.Type()).Elem())
					}

					for field.Kind() == reflect.Ptr {
						field = field.Elem()
					}

					if primaryKeys := utils.ToArray(metaValue.Value); len(primaryKeys) > 0 {
						context.GetDB().Where(primaryKeys).Find(field.Addr().Interface())
					}

					// Replace many 2 many relations
					if relationship.Kind == "many_to_many" {
						if !scope.PrimaryKeyZero() {
							context.GetDB().Model(resource).Association(meta.Alias).Replace(field.Interface())
						}
					}
				}
			}
		} else {
			meta.Setter = func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
				if metaValue == nil {
					return
				}

				value := metaValue.Value
				alias := meta.Alias
				if nestedField {
					fields := strings.Split(alias, ".")
					alias = fields[len(fields)-1]
				}

				field := reflect.Indirect(reflect.ValueOf(resource)).FieldByName(alias)
				if field.Kind() == reflect.Ptr && field.IsNil() {
					field.Set(utils.NewValue(field.Type()).Elem())
				}

				for field.Kind() == reflect.Ptr {
					field = field.Elem()
				}

				if field.IsValid() && field.CanAddr() {
					switch field.Kind() {
					case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
						field.SetInt(utils.ToInt(value))
					case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
						field.SetUint(utils.ToUint(value))
					case reflect.Float32, reflect.Float64:
						field.SetFloat(utils.ToFloat(value))
					case reflect.Bool:
						// TODO: add test
						if utils.ToString(value) == "true" {
							field.SetBool(true)
						} else {
							field.SetBool(false)
						}
					default:
						if scanner, ok := field.Addr().Interface().(sql.Scanner); ok {
							if scanner.Scan(value) != nil {
								scanner.Scan(utils.ToString(value))
							}
						} else if reflect.TypeOf("").ConvertibleTo(field.Type()) {
							field.Set(reflect.ValueOf(utils.ToString(value)).Convert(field.Type()))
						} else if reflect.TypeOf([]string{}).ConvertibleTo(field.Type()) {
							field.Set(reflect.ValueOf(utils.ToArray(value)).Convert(field.Type()))
						} else if rvalue := reflect.ValueOf(value); reflect.TypeOf(rvalue.Type()).ConvertibleTo(field.Type()) {
							field.Set(rvalue.Convert(field.Type()))
						} else if _, ok := field.Addr().Interface().(*time.Time); ok {
							if str := utils.ToString(value); str != "" {
								if newTime, err := now.Parse(str); err == nil {
									field.Set(reflect.ValueOf(newTime))
								}
							}
						} else {
							var buf = bytes.NewBufferString("")
							json.NewEncoder(buf).Encode(value)
							if err := json.NewDecoder(strings.NewReader(buf.String())).Decode(field.Addr().Interface()); err != nil {
								utils.ExitWithMsg("Can't set value %v to %v [meta %v]", reflect.ValueOf(value).Type(), field.Type(), meta)
							}
						}
					}
				}
			}
		}
	}

	if nestedField {
		oldvalue := meta.Valuer
		meta.Valuer = func(value interface{}, context *qor.Context) interface{} {
			return oldvalue(utils.GetNestedModel(value, meta.Alias, context), context)
		}
		oldSetter := meta.Setter
		meta.Setter = func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
			oldSetter(utils.GetNestedModel(resource, meta.Alias, context), metaValue, context)
		}
	}
}
<commit_msg>Get correct struct type for slice<commit_after>package admin

import (
	"bytes"
	"database/sql"
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/jinzhu/gorm"
	"github.com/jinzhu/now"
	"github.com/qor/qor"
	"github.com/qor/qor/media_library"
	"github.com/qor/qor/resource"
	"github.com/qor/qor/roles"
	"github.com/qor/qor/utils"
)

type Meta struct {
	base          *Resource
	Name          string
	DBName        string
	Alias         string
	Label         string
	Type          string
	Valuer        func(interface{}, *qor.Context) interface{}
	Setter        func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context)
	Metas         []resource.Metaor
	Resource      resource.Resourcer
	Collection    interface{}
	GetCollection func(interface{}, *qor.Context) [][]string
	Permission    *roles.Permission
}

func (meta *Meta) GetName() string {
	return meta.Name
}

func (meta *Meta) GetFieldName() string {
	return meta.Alias
}

func (meta *Meta) GetMetas() []resource.Metaor {
	if len(meta.Metas) > 0 {
		return meta.Metas
	} else if meta.Resource == nil {
		return []resource.Metaor{}
	} else {
		return meta.Resource.GetMetas([]string{})
	}
}

func (meta *Meta) GetResource() resource.Resourcer {
	return meta.Resource
}

func (meta *Meta) GetValuer() func(interface{}, *qor.Context) interface{} {
	return meta.Valuer
}

func (meta *Meta) GetSetter() func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
	return meta.Setter
}

func (meta *Meta) HasPermission(mode roles.PermissionMode, context *qor.Context) bool {
	if meta.Permission == nil {
		return true
	}
	return meta.Permission.HasPermission(mode, context.Roles...)
}

func getField(fields map[string]*gorm.Field, name string) (*gorm.Field, bool) {
	for _, field := range fields {
		if field.Name == name || field.DBName == name {
			return field, true
		}
	}
	return nil, false
}

func (meta *Meta) updateMeta() {
	if meta.Name == "" {
		utils.ExitWithMsg("Meta should have name: %v", reflect.ValueOf(meta).Type())
	} else if meta.Alias == "" {
		meta.Alias = meta.Name
	}

	if meta.Label == "" {
		meta.Label = utils.HumanizeString(meta.Name)
	}

	var (
		scope       = &gorm.Scope{Value: meta.base.Value}
		nestedField = strings.Contains(meta.Alias, ".")
		field       *gorm.Field
		hasColumn   bool
	)

	if nestedField {
		subModel, name := utils.ParseNestedField(reflect.ValueOf(meta.base.Value), meta.Alias)
		subScope := &gorm.Scope{Value: subModel.Interface()}
		field, hasColumn = getField(subScope.Fields(), name)
	} else {
		if field, hasColumn = getField(scope.Fields(), meta.Alias); hasColumn {
			meta.Alias = field.Name
			meta.DBName = field.DBName
		}
	}

	var fieldType reflect.Type
	if hasColumn {
		fieldType = field.Field.Type()
		for fieldType.Kind() == reflect.Ptr {
			fieldType = fieldType.Elem()
		}
	}

	// Set Meta Type
	if meta.Type == "" && hasColumn {
		if relationship := field.Relationship; relationship != nil {
			if relationship.Kind == "has_one" {
				meta.Type = "single_edit"
			} else if relationship.Kind == "has_many" {
				meta.Type = "collection_edit"
			} else if relationship.Kind == "belongs_to" {
				meta.Type = "select_one"
			} else if relationship.Kind == "many_to_many" {
				meta.Type = "select_many"
			}
		} else {
			switch fieldType.Kind().String() {
			case "string":
				if size, ok := utils.ParseTagOption(field.Tag.Get("sql"))["SIZE"]; ok {
					if i, _ := strconv.Atoi(size); i > 255 {
						meta.Type = "text"
					} else {
						meta.Type = "string"
					}
				} else if text, ok := utils.ParseTagOption(field.Tag.Get("sql"))["TYPE"]; ok && text == "text" {
					meta.Type = "text"
				} else {
					meta.Type = "string"
				}
			case "bool":
				meta.Type = "checkbox"
			default:
				if regexp.MustCompile(`^(.*)?(u)?(int)(\d+)?`).MatchString(fieldType.Kind().String()) {
					meta.Type = "number"
				} else if regexp.MustCompile(`^(.*)?(float)(\d+)?`).MatchString(fieldType.Kind().String()) {
					meta.Type = "float"
				} else if _, ok := reflect.New(fieldType).Interface().(*time.Time); ok {
					meta.Type = "datetime"
				} else if _, ok := reflect.New(fieldType).Interface().(media_library.MediaLibrary); ok {
					meta.Type = "file"
				}
			}
		}
	}

	// Set Meta Resource
	if meta.Resource == nil {
		if hasColumn && (field.Relationship != nil) {
			var result interface{}
			if fieldType.Kind().String() == "struct" {
				result = reflect.New(field.Field.Type()).Interface()
			} else if fieldType.Kind().String() == "slice" {
				refelectType := field.Field.Type().Elem()
				for refelectType.Kind() == reflect.Ptr {
					refelectType = refelectType.Elem()
				}
				result = reflect.New(refelectType).Interface()
			}

			res := meta.base.GetAdmin().NewResource(result)
			res.compile()
			meta.Resource = res
		}
	}

	if meta.Type == "serialize_argument" {
		type SerializeArgumentInterface interface {
			GetSerializeArgumentResource() *Resource
			GetSerializeArgument() interface{}
			SetSerializeArgument(value interface{})
		}

		if meta.Valuer == nil {
			meta.Valuer = func(value interface{}, context *qor.Context) interface{} {
				if serializeArgument, ok := value.(SerializeArgumentInterface); ok {
					return struct {
						Value    interface{}
						Resource *Resource
					}{
						Value:    serializeArgument.GetSerializeArgument(),
						Resource: serializeArgument.GetSerializeArgumentResource(),
					}
				}
				return nil
			}
		}

		if meta.Setter == nil {
			meta.Setter = func(result interface{}, metaValue *resource.MetaValue, context *qor.Context) {
				if serializeArgument, ok := result.(SerializeArgumentInterface); ok {
					if res := serializeArgument.GetSerializeArgumentResource(); res != nil {
						value := res.NewStruct()

						for _, meta := range res.GetMetas([]string{}) {
							metaValue := metaValue.MetaValues.Get(meta.GetName())
							if setter := meta.GetSetter(); setter != nil {
								setter(value, metaValue, context)
							}
						}

						serializeArgument.SetSerializeArgument(value)
					}
				}
			}
		}
	}

	// Set Meta Valuer
	if meta.Valuer == nil {
		if hasColumn {
			meta.Valuer = func(value interface{}, context *qor.Context) interface{} {
				scope := context.GetDB().NewScope(value)
				alias := meta.Alias
				if nestedField {
					fields := strings.Split(alias, ".")
					alias = fields[len(fields)-1]
				}

				if f, ok := scope.FieldByName(alias); ok {
					if field.Relationship != nil {
						if f.Field.CanAddr() && !scope.PrimaryKeyZero() {
							context.GetDB().Model(value).Related(f.Field.Addr().Interface(), meta.Alias)
						}
					}
					if f.Field.CanAddr() {
						return f.Field.Addr().Interface()
					} else {
						return f.Field.Interface()
					}
				}

				return ""
			}
		} else {
			utils.ExitWithMsg("Unsupported meta name %v for resource %v", meta.Name, reflect.TypeOf(meta.base.Value))
		}
	}

	scopeField, _ := scope.FieldByName(meta.Alias)

	// Set Meta Collection
	if meta.Collection != nil {
		if maps, ok := meta.Collection.([]string); ok {
			meta.GetCollection = func(interface{}, *qor.Context) (results [][]string) {
				for _, value := range maps {
					results = append(results, []string{value, value})
				}
				return
			}
		} else if maps, ok := meta.Collection.([][]string); ok {
			meta.GetCollection = func(interface{}, *qor.Context) [][]string {
				return maps
			}
		} else if f, ok := meta.Collection.(func(interface{}, *qor.Context) [][]string); ok {
			meta.GetCollection = f
		} else {
			utils.ExitWithMsg("Unsupported Collection format for meta %v of resource %v", meta.Name, reflect.TypeOf(meta.base.Value))
		}
	} else if meta.Type == "select_one" || meta.Type == "select_many" {
		if scopeField.Relationship != nil {
			fieldType := scopeField.StructField.Struct.Type
			if fieldType.Kind() == reflect.Slice {
				fieldType = fieldType.Elem()
			}

			meta.GetCollection = func(value interface{}, context *qor.Context) (results [][]string) {
				values := reflect.New(reflect.SliceOf(fieldType)).Interface()
				context.GetDB().Find(values)
				reflectValues := reflect.Indirect(reflect.ValueOf(values))
				for i := 0; i < reflectValues.Len(); i++ {
					scope := scope.New(reflectValues.Index(i).Interface())
					primaryKey := fmt.Sprintf("%v", scope.PrimaryKeyValue())
					results = append(results, []string{primaryKey, utils.Stringify(reflectValues.Index(i).Interface())})
				}
				return
			}
		} else {
			utils.ExitWithMsg("%v meta type %v needs Collection", meta.Name, meta.Type)
		}
	}

	if meta.Setter == nil && hasColumn {
		if relationship := field.Relationship; relationship != nil {
			if meta.Type == "select_one" || meta.Type == "select_many" {
				meta.Setter = func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
					scope := &gorm.Scope{Value: resource}
					field := reflect.Indirect(reflect.ValueOf(resource)).FieldByName(meta.Alias)

					if field.Kind() == reflect.Ptr && field.IsNil() {
						field.Set(utils.NewValue(field.Type()).Elem())
					}

					for field.Kind() == reflect.Ptr {
						field = field.Elem()
					}

					if primaryKeys := utils.ToArray(metaValue.Value); len(primaryKeys) > 0 {
						context.GetDB().Where(primaryKeys).Find(field.Addr().Interface())
					}

					// Replace many 2 many relations
					if relationship.Kind == "many_to_many" {
						if !scope.PrimaryKeyZero() {
							context.GetDB().Model(resource).Association(meta.Alias).Replace(field.Interface())
						}
					}
				}
			}
		} else {
			meta.Setter = func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
				if metaValue == nil {
					return
				}

				value := metaValue.Value
				alias := meta.Alias
				if nestedField {
					fields := strings.Split(alias, ".")
					alias = fields[len(fields)-1]
				}

				field := reflect.Indirect(reflect.ValueOf(resource)).FieldByName(alias)
				if field.Kind() == reflect.Ptr && field.IsNil() {
					field.Set(utils.NewValue(field.Type()).Elem())
				}

				for field.Kind() == reflect.Ptr {
					field = field.Elem()
				}

				if field.IsValid() && field.CanAddr() {
					switch field.Kind() {
					case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
						field.SetInt(utils.ToInt(value))
					case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
						field.SetUint(utils.ToUint(value))
					case reflect.Float32, reflect.Float64:
						field.SetFloat(utils.ToFloat(value))
					case reflect.Bool:
						// TODO: add test
						if utils.ToString(value) == "true" {
							field.SetBool(true)
						} else {
							field.SetBool(false)
						}
					default:
						if scanner, ok := field.Addr().Interface().(sql.Scanner); ok {
							if scanner.Scan(value) != nil {
								scanner.Scan(utils.ToString(value))
							}
						} else if reflect.TypeOf("").ConvertibleTo(field.Type()) {
							field.Set(reflect.ValueOf(utils.ToString(value)).Convert(field.Type()))
						} else if reflect.TypeOf([]string{}).ConvertibleTo(field.Type()) {
							field.Set(reflect.ValueOf(utils.ToArray(value)).Convert(field.Type()))
						} else if rvalue := reflect.ValueOf(value); reflect.TypeOf(rvalue.Type()).ConvertibleTo(field.Type()) {
							field.Set(rvalue.Convert(field.Type()))
						} else if _, ok := field.Addr().Interface().(*time.Time); ok {
							if str := utils.ToString(value); str != "" {
								if newTime, err := now.Parse(str); err == nil {
									field.Set(reflect.ValueOf(newTime))
								}
							}
						} else {
							var buf = bytes.NewBufferString("")
							json.NewEncoder(buf).Encode(value)
							if err := json.NewDecoder(strings.NewReader(buf.String())).Decode(field.Addr().Interface()); err != nil {
								utils.ExitWithMsg("Can't set value %v to %v [meta %v]", reflect.ValueOf(value).Type(), field.Type(), meta)
							}
						}
					}
				}
			}
		}
	}

	if nestedField {
		oldvalue := meta.Valuer
		meta.Valuer = func(value interface{}, context *qor.Context) interface{} {
			return oldvalue(utils.GetNestedModel(value, meta.Alias, context), context)
		}
		oldSetter := meta.Setter
		meta.Setter = func(resource interface{}, metaValue *resource.MetaValue, context *qor.Context) {
			oldSetter(utils.GetNestedModel(resource, meta.Alias, context), metaValue, context)
		}
	}
}
<|endoftext|>


<commit_before>// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package vmware

import (
	"errors"
	"net"
	"reflect"
	"testing"

	"github.com/coreos/coreos-cloudinit/datasource"
)

type MockHypervisor map[string]string

func (h MockHypervisor) ReadConfig(key string) (string, error) {
	return h[key], nil
}

func TestFetchMetadata(t *testing.T) {
	tests := []struct {
		variables MockHypervisor

		metadata datasource.Metadata
		err      error
	}{
		{
			variables: map[string]string{
				"interface.0.mac":  "test mac",
				"interface.0.dhcp": "yes",
			},
			metadata: datasource.Metadata{
				NetworkConfig: map[string]string{
					"interface.0.mac":  "test mac",
					"interface.0.dhcp": "yes",
				},
			},
		},
		{
			variables: map[string]string{
				"interface.0.name": "test name",
				"interface.0.dhcp": "yes",
			},
			metadata: datasource.Metadata{
				NetworkConfig: map[string]string{
					"interface.0.name": "test name",
					"interface.0.dhcp": "yes",
				},
			},
		},
		{
			variables: map[string]string{
				"hostname":                        "test host",
				"interface.0.mac":                 "test mac",
				"interface.0.role":                "private",
				"interface.0.ip.0.address":        "fe00::100/64",
				"interface.0.route.0.gateway":     "fe00::1",
				"interface.0.route.0.destination": "::",
			},
			metadata: datasource.Metadata{
				Hostname:    "test host",
				PrivateIPv6: net.ParseIP("fe00::100"),
				NetworkConfig: map[string]string{
					"interface.0.mac":                 "test mac",
					"interface.0.ip.0.address":        "fe00::100/64",
					"interface.0.route.0.gateway":     "fe00::1",
					"interface.0.route.0.destination": "::",
				},
			},
		},
		{
			variables: map[string]string{
				"hostname":                        "test host",
				"interface.0.name":                "test name",
				"interface.0.role":                "public",
				"interface.0.ip.0.address":        "10.0.0.100/24",
				"interface.0.ip.1.address":        "10.0.0.101/24",
				"interface.0.route.0.gateway":     "10.0.0.1",
				"interface.0.route.0.destination": "0.0.0.0",
				"interface.1.mac":                 "test mac",
				"interface.1.role":                "private",
				"interface.1.route.0.gateway":     "10.0.0.2",
				"interface.1.route.0.destination": "0.0.0.0",
				"interface.1.ip.0.address":        "10.0.0.102/24",
			},
			metadata: datasource.Metadata{
				Hostname:    "test host",
				PublicIPv4:  net.ParseIP("10.0.0.101"),
				PrivateIPv4: net.ParseIP("10.0.0.102"),
				NetworkConfig: map[string]string{
					"interface.0.name":                "test name",
					"interface.0.ip.0.address":        "10.0.0.100/24",
					"interface.0.ip.1.address":        "10.0.0.101/24",
					"interface.0.route.0.gateway":     "10.0.0.1",
					"interface.0.route.0.destination": "0.0.0.0",
					"interface.1.mac":                 "test mac",
					"interface.1.route.0.gateway":     "10.0.0.2",
					"interface.1.route.0.destination": "0.0.0.0",
					"interface.1.ip.0.address":        "10.0.0.102/24",
				},
			},
		},
	}

	for i, tt := range tests {
		v := vmware{tt.variables.ReadConfig}
		metadata, err := v.FetchMetadata()
		if !reflect.DeepEqual(tt.err, err) {
			t.Errorf("bad error (#%d): want %v, got %v", i, tt.err, err)
		}
		if !reflect.DeepEqual(tt.metadata, metadata) {
			t.Errorf("bad metadata (#%d): want %#v, got %#v", i, tt.metadata, metadata)
		}
	}
}

func TestFetchUserdata(t *testing.T) {
	tests := []struct {
		variables MockHypervisor

		userdata string
		err      error
	}{
		{},
		{
			variables: map[string]string{"coreos.config.data": "test config"},
			userdata:  "test config",
		},
		{
			variables: map[string]string{
				"coreos.config.data.encoding": "",
				"coreos.config.data":          "test config",
			},
			userdata: "test config",
		},
		{
			variables: map[string]string{
				"coreos.config.data.encoding": "base64",
				"coreos.config.data":          "dGVzdCBjb25maWc=",
			},
			userdata: "test config",
		},
		{
			variables: map[string]string{
				"coreos.config.data.encoding": "gzip+base64",
				"coreos.config.data":          "H4sIABaoWlUAAytJLS5RSM7PS8tMBwCQiHNZCwAAAA==",
			},
			userdata: "test config",
		},
		{
			variables: map[string]string{
				"coreos.config.data.encoding": "test encoding",
			},
			err: errors.New(`Unsupported encoding "test encoding"`),
		},
	}

	for i, tt := range tests {
		v := vmware{tt.variables.ReadConfig}
		userdata, err := v.FetchUserdata()
		if !reflect.DeepEqual(tt.err, err) {
			t.Errorf("bad error (#%d): want %v, got %v", i, nil, err)
		}
		if tt.userdata != string(userdata) {
			t.Errorf("bad userdata (#%d): want %q, got %q", i, tt.userdata, userdata)
		}
	}
}

func TestFetchUserdataError(t *testing.T) {
	testErr := errors.New("test error")
	_, err := vmware{func(_ string) (string, error) { return "", testErr }}.FetchUserdata()

	if testErr != err {
		t.Errorf("bad error: want %v, got %v", testErr, err)
	}
}
<commit_msg>datasource/vmware: fix assertion<commit_after>// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package vmware

import (
	"errors"
	"net"
	"reflect"
	"testing"

	"github.com/coreos/coreos-cloudinit/datasource"
)

type MockHypervisor map[string]string

func (h MockHypervisor) ReadConfig(key string) (string, error) {
	return h[key], nil
}

func TestFetchMetadata(t *testing.T) {
	tests := []struct {
		variables MockHypervisor

		metadata datasource.Metadata
		err      error
	}{
		{
			variables: map[string]string{
				"interface.0.mac":  "test mac",
				"interface.0.dhcp": "yes",
			},
			metadata: datasource.Metadata{
				NetworkConfig: map[string]string{
					"interface.0.mac":  "test mac",
					"interface.0.dhcp": "yes",
				},
			},
		},
		{
			variables: map[string]string{
				"interface.0.name": "test name",
				"interface.0.dhcp": "yes",
			},
			metadata: datasource.Metadata{
				NetworkConfig: map[string]string{
					"interface.0.name": "test name",
					"interface.0.dhcp": "yes",
				},
			},
		},
		{
			variables: map[string]string{
				"hostname":                        "test host",
				"interface.0.mac":                 "test mac",
				"interface.0.role":                "private",
				"interface.0.ip.0.address":        "fe00::100/64",
				"interface.0.route.0.gateway":     "fe00::1",
				"interface.0.route.0.destination": "::",
			},
			metadata: datasource.Metadata{
				Hostname:    "test host",
				PrivateIPv6: net.ParseIP("fe00::100"),
				NetworkConfig: map[string]string{
					"interface.0.mac":                 "test mac",
					"interface.0.ip.0.address":        "fe00::100/64",
					"interface.0.route.0.gateway":     "fe00::1",
					"interface.0.route.0.destination": "::",
				},
			},
		},
		{
			variables: map[string]string{
				"hostname":                        "test host",
				"interface.0.name":                "test name",
				"interface.0.role":                "public",
				"interface.0.ip.0.address":        "10.0.0.100/24",
				"interface.0.ip.1.address":        "10.0.0.101/24",
				"interface.0.route.0.gateway":     "10.0.0.1",
				"interface.0.route.0.destination": "0.0.0.0",
				"interface.1.mac":                 "test mac",
				"interface.1.role":                "private",
				"interface.1.route.0.gateway":     "10.0.0.2",
				"interface.1.route.0.destination": "0.0.0.0",
				"interface.1.ip.0.address":        "10.0.0.102/24",
			},
			metadata: datasource.Metadata{
				Hostname:    "test host",
				PublicIPv4:  net.ParseIP("10.0.0.101"),
				PrivateIPv4: net.ParseIP("10.0.0.102"),
				NetworkConfig: map[string]string{
					"interface.0.name":                "test name",
					"interface.0.ip.0.address":        "10.0.0.100/24",
					"interface.0.ip.1.address":        "10.0.0.101/24",
					"interface.0.route.0.gateway":     "10.0.0.1",
					"interface.0.route.0.destination": "0.0.0.0",
					"interface.1.mac":                 "test mac",
					"interface.1.route.0.gateway":     "10.0.0.2",
					"interface.1.route.0.destination": "0.0.0.0",
					"interface.1.ip.0.address":        "10.0.0.102/24",
				},
			},
		},
	}

	for i, tt := range tests {
		v := vmware{tt.variables.ReadConfig}
		metadata, err := v.FetchMetadata()
		if !reflect.DeepEqual(tt.err, err) {
			t.Errorf("bad error (#%d): want %v, got %v", i, tt.err, err)
		}
		if !reflect.DeepEqual(tt.metadata, metadata) {
			t.Errorf("bad metadata (#%d): want %#v, got %#v", i, tt.metadata, metadata)
		}
	}
}

func TestFetchUserdata(t *testing.T) {
	tests := []struct {
		variables MockHypervisor

		userdata string
		err      error
	}{
		{},
		{
			variables: map[string]string{"coreos.config.data": "test config"},
			userdata:  "test config",
		},
		{
			variables: map[string]string{
				"coreos.config.data.encoding": "",
				"coreos.config.data":          "test config",
			},
			userdata: "test config",
		},
		{
			variables: map[string]string{
				"coreos.config.data.encoding": "base64",
				"coreos.config.data":          "dGVzdCBjb25maWc=",
			},
			userdata: "test config",
		},
		{
			variables: map[string]string{
				"coreos.config.data.encoding": "gzip+base64",
				"coreos.config.data":          "H4sIABaoWlUAAytJLS5RSM7PS8tMBwCQiHNZCwAAAA==",
			},
			userdata: "test config",
		},
		{
			variables: map[string]string{
				"coreos.config.data.encoding": "test encoding",
			},
			err: errors.New(`Unsupported encoding "test encoding"`),
		},
	}

	for i, tt := range tests {
		v := vmware{tt.variables.ReadConfig}
		userdata, err := v.FetchUserdata()
		if !reflect.DeepEqual(tt.err, err) {
			t.Errorf("bad error (#%d): want %v, got %v", i, tt.err, err)
		}
		if tt.userdata != string(userdata) {
			t.Errorf("bad userdata (#%d): want %q, got %q", i, tt.userdata, userdata)
		}
	}
}

func TestFetchUserdataError(t *testing.T) {
	testErr := errors.New("test error")
	_, err := vmware{func(_ string) (string, error) { return "", testErr }}.FetchUserdata()

	if testErr != err {
		t.Errorf("bad error: want %v, got %v", testErr, err)
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2016 The Kubernetes 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 chartutil

import (
	"errors"
	"log"
	"strings"
	"time"

	"github.com/ghodss/yaml"
	"k8s.io/helm/pkg/proto/hapi/chart"
	"k8s.io/helm/pkg/version"
)

const (
	requirementsName = "requirements.yaml"
	lockfileName     = "requirements.lock"
)

var (
	// ErrRequirementsNotFound indicates that a requirements.yaml is not found.
	ErrRequirementsNotFound = errors.New(requirementsName + " not found")
	// ErrLockfileNotFound indicates that a requirements.lock is not found.
	ErrLockfileNotFound = errors.New(lockfileName + " not found")
)

// Dependency describes a chart upon which another chart depends.
//
// Dependencies can be used to express developer intent, or to capture the state
// of a chart.
type Dependency struct {
	// Name is the name of the dependency.
	//
	// This must mach the name in the dependency's Chart.yaml.
	Name string `json:"name"`
	// Version is the version (range) of this chart.
	//
	// A lock file will always produce a single version, while a dependency
	// may contain a semantic version range.
	Version string `json:"version,omitempty"`
	// The URL to the repository.
	//
	// Appending `index.yaml` to this string should result in a URL that can be
	// used to fetch the repository index.
	Repository string `json:"repository"`
	// A yaml path that resolves to a boolean, used for enabling/disabling charts (e.g. subchart1.enabled )
	Condition string `json:"condition,omitempty"`
	// Tags can be used to group charts for enabling/disabling together
	Tags []string `json:"tags,omitempty"`
	// Enabled bool determines if chart should be loaded
	Enabled bool `json:"enabled,omitempty"`
	// ImportValues holds the mapping of source values to parent key to be imported. Each item can be a
	// string or pair of child/parent sublist items.
	ImportValues []interface{} `json:"import-values,omitempty"`
	// Alias usable alias to be used for the chart
	Alias string `json:"alias,omitempty"`
}

// ErrNoRequirementsFile to detect error condition
type ErrNoRequirementsFile error

// Requirements is a list of requirements for a chart.
//
// Requirements are charts upon which this chart depends. This expresses
// developer intent.
type Requirements struct {
	Dependencies []*Dependency `json:"dependencies"`
}

// RequirementsLock is a lock file for requirements.
//
// It represents the state that the dependencies should be in.
type RequirementsLock struct {
	// Genderated is the date the lock file was last generated.
	Generated time.Time `json:"generated"`
	// Digest is a hash of the requirements file used to generate it.
	Digest string `json:"digest"`
	// Dependencies is the list of dependencies that this lock file has locked.
	Dependencies []*Dependency `json:"dependencies"`
}

// LoadRequirements loads a requirements file from an in-memory chart.
func LoadRequirements(c *chart.Chart) (*Requirements, error) {
	var data []byte
	for _, f := range c.Files {
		if f.TypeUrl == requirementsName {
			data = f.Value
		}
	}
	if len(data) == 0 {
		return nil, ErrRequirementsNotFound
	}
	r := &Requirements{}
	return r, yaml.Unmarshal(data, r)
}

// LoadRequirementsLock loads a requirements lock file.
func LoadRequirementsLock(c *chart.Chart) (*RequirementsLock, error) {
	var data []byte
	for _, f := range c.Files {
		if f.TypeUrl == lockfileName {
			data = f.Value
		}
	}
	if len(data) == 0 {
		return nil, ErrLockfileNotFound
	}
	r := &RequirementsLock{}
	return r, yaml.Unmarshal(data, r)
}

// ProcessRequirementsConditions disables charts based on condition path value in values
func ProcessRequirementsConditions(reqs *Requirements, cvals Values) {
	var cond string
	var conds []string
	if reqs == nil || len(reqs.Dependencies) == 0 {
		return
	}
	for _, r := range reqs.Dependencies {
		var hasTrue, hasFalse bool
		cond = string(r.Condition)
		// check for list
		if len(cond) > 0 {
			if strings.Contains(cond, ",") {
				conds = strings.Split(strings.TrimSpace(cond), ",")
			} else {
				conds = []string{strings.TrimSpace(cond)}
			}
			for _, c := range conds {
				if len(c) > 0 {
					// retrieve value
					vv, err := cvals.PathValue(c)
					if err == nil {
						// if not bool, warn
						if bv, ok := vv.(bool); ok {
							if bv {
								hasTrue = true
							} else {
								hasFalse = true
							}
						} else {
							log.Printf("Warning: Condition path '%s' for chart %s returned non-bool value", c, r.Name)
						}
					} else if _, ok := err.(ErrNoValue); !ok {
						// this is a real error
						log.Printf("Warning: PathValue returned error %v", err)

					}
					if vv != nil {
						// got first value, break loop
						break
					}
				}
			}
			if !hasTrue && hasFalse {
				r.Enabled = false
			} else if hasTrue {
				r.Enabled = true

			}
		}

	}

}

// ProcessRequirementsTags disables charts based on tags in values
func ProcessRequirementsTags(reqs *Requirements, cvals Values) {
	vt, err := cvals.Table("tags")
	if err != nil {
		return

	}
	if reqs == nil || len(reqs.Dependencies) == 0 {
		return
	}
	for _, r := range reqs.Dependencies {
		if len(r.Tags) > 0 {
			tags := r.Tags

			var hasTrue, hasFalse bool
			for _, k := range tags {
				if b, ok := vt[k]; ok {
					// if not bool, warn
					if bv, ok := b.(bool); ok {
						if bv {
							hasTrue = true
						} else {
							hasFalse = true
						}
					} else {
						log.Printf("Warning: Tag '%s' for chart %s returned non-bool value", k, r.Name)
					}
				}
			}
			if !hasTrue && hasFalse {
				r.Enabled = false
			} else if hasTrue || !hasTrue && !hasFalse {
				r.Enabled = true

			}

		}
	}

}

func getAliasDependency(charts []*chart.Chart, aliasChart *Dependency) *chart.Chart {
	var chartFound chart.Chart
	for _, existingChart := range charts {
		if existingChart == nil {
			continue
		}
		if existingChart.Metadata == nil {
			continue
		}
		if existingChart.Metadata.Name != aliasChart.Name {
			continue
		}
		if !version.IsCompatibleRange(aliasChart.Version, existingChart.Metadata.Version) {
			continue
		}
		chartFound = *existingChart
		newMetadata := *existingChart.Metadata
		if aliasChart.Alias != "" {
			newMetadata.Name = aliasChart.Alias
		}
		chartFound.Metadata = &newMetadata
		return &chartFound
	}
	return nil
}

// ProcessRequirementsEnabled removes disabled charts from dependencies
func ProcessRequirementsEnabled(c *chart.Chart, v *chart.Config) error {
	reqs, err := LoadRequirements(c)
	if err != nil {
		// if not just missing requirements file, return error
		if nerr, ok := err.(ErrNoRequirementsFile); !ok {
			return nerr
		}

		// no requirements to process
		return nil
	}

	var chartDependencies []*chart.Chart
	// If any dependency is not a part of requirements.yaml
	// then this should be added to chartDependencies.
	// However, if the dependency is already specified in requirements.yaml
	// we should not add it, as it would be anyways processed from requirements.yaml

	for _, existingDependency := range c.Dependencies {
		var dependencyFound bool
		for _, req := range reqs.Dependencies {
			if existingDependency.Metadata.Name == req.Name && version.IsCompatibleRange(req.Version, existingDependency.Metadata.Version) {
				dependencyFound = true
				break
			}
		}
		if !dependencyFound {
			chartDependencies = append(chartDependencies, existingDependency)
		}
	}

	for _, req := range reqs.Dependencies {
		if chartDependency := getAliasDependency(c.Dependencies, req); chartDependency != nil {
			chartDependencies = append(chartDependencies, chartDependency)
		}
		if req.Alias != "" {
			req.Name = req.Alias
		}
	}
	c.Dependencies = chartDependencies

	// set all to true
	for _, lr := range reqs.Dependencies {
		lr.Enabled = true
	}
	cvals, err := CoalesceValues(c, v)
	if err != nil {
		return err
	}
	// convert our values back into config
	yvals, err := cvals.YAML()
	if err != nil {
		return err
	}
	cc := chart.Config{Raw: yvals}
	// flag dependencies as enabled/disabled
	ProcessRequirementsTags(reqs, cvals)
	ProcessRequirementsConditions(reqs, cvals)
	// make a map of charts to remove
	rm := map[string]bool{}
	for _, r := range reqs.Dependencies {
		if !r.Enabled {
			// remove disabled chart
			rm[r.Name] = true
		}
	}
	// don't keep disabled charts in new slice
	cd := []*chart.Chart{}
	copy(cd, c.Dependencies[:0])
	for _, n := range c.Dependencies {
		if _, ok := rm[n.Metadata.Name]; !ok {
			cd = append(cd, n)
		}

	}
	// recursively call self to process sub dependencies
	for _, t := range cd {
		err := ProcessRequirementsEnabled(t, &cc)
		// if its not just missing requirements file, return error
		if nerr, ok := err.(ErrNoRequirementsFile); !ok && err != nil {
			return nerr
		}
	}
	c.Dependencies = cd

	return nil
}

// pathToMap creates a nested map given a YAML path in dot notation.
func pathToMap(path string, data map[string]interface{}) map[string]interface{} {
	if path == "." {
		return data
	}
	ap := strings.Split(path, ".")
	if len(ap) == 0 {
		return nil
	}
	n := []map[string]interface{}{}
	// created nested map for each key, adding to slice
	for _, v := range ap {
		nm := make(map[string]interface{})
		nm[v] = make(map[string]interface{})
		n = append(n, nm)
	}
	// find the last key (map) and set our data
	for i, d := range n {
		for k := range d {
			z := i + 1
			if z == len(n) {
				n[i][k] = data
				break
			}
			n[i][k] = n[z]
		}
	}

	return n[0]
}

// getParents returns a slice of parent charts in reverse order.
func getParents(c *chart.Chart, out []*chart.Chart) []*chart.Chart {
	if len(out) == 0 {
		out = []*chart.Chart{c}
	}
	for _, ch := range c.Dependencies {
		if len(ch.Dependencies) > 0 {
			out = append(out, ch)
			out = getParents(ch, out)
		}
	}

	return out
}

// processImportValues merges values from child to parent based on the chart's dependencies' ImportValues field.
func processImportValues(c *chart.Chart) error {
	reqs, err := LoadRequirements(c)
	if err != nil {
		return err
	}
	// combine chart values and empty config to get Values
	cvals, err := CoalesceValues(c, &chart.Config{})
	if err != nil {
		return err
	}
	b := make(map[string]interface{}, 0)
	// import values from each dependency if specified in import-values
	for _, r := range reqs.Dependencies {
		if len(r.ImportValues) > 0 {
			var outiv []interface{}
			for _, riv := range r.ImportValues {
				switch iv := riv.(type) {
				case map[string]interface{}:
					nm := map[string]string{
						"child":  iv["child"].(string),
						"parent": iv["parent"].(string),
					}
					outiv = append(outiv, nm)
					s := r.Name + "." + nm["child"]
					// get child table
					vv, err := cvals.Table(s)
					if err != nil {
						log.Printf("Warning: ImportValues missing table: %v", err)
						continue
					}
					// create value map from child to be merged into parent
					vm := pathToMap(nm["parent"], vv.AsMap())
					b = coalesceTables(cvals, vm)
				case string:
					nm := map[string]string{
						"child":  "exports." + iv,
						"parent": ".",
					}
					outiv = append(outiv, nm)
					s := r.Name + "." + nm["child"]
					vm, err := cvals.Table(s)
					if err != nil {
						log.Printf("Warning: ImportValues missing table: %v", err)
						continue
					}
					b = coalesceTables(b, vm.AsMap())
				}
			}
			// set our formatted import values
			r.ImportValues = outiv
		}
	}
	b = coalesceTables(b, cvals)
	y, err := yaml.Marshal(b)
	if err != nil {
		return err
	}

	// set the new values
	c.Values = &chart.Config{Raw: string(y)}

	return nil
}

// ProcessRequirementsImportValues imports specified chart values from child to parent.
func ProcessRequirementsImportValues(c *chart.Chart) error {
	pc := getParents(c, nil)
	for i := len(pc) - 1; i >= 0; i-- {
		processImportValues(pc[i])
	}

	return nil
}
<commit_msg>fix(helm): fix importValues warnings from disabled charts<commit_after>/*
Copyright 2016 The Kubernetes 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 chartutil

import (
	"errors"
	"log"
	"strings"
	"time"

	"github.com/ghodss/yaml"
	"k8s.io/helm/pkg/proto/hapi/chart"
	"k8s.io/helm/pkg/version"
)

const (
	requirementsName = "requirements.yaml"
	lockfileName     = "requirements.lock"
)

var (
	// ErrRequirementsNotFound indicates that a requirements.yaml is not found.
	ErrRequirementsNotFound = errors.New(requirementsName + " not found")
	// ErrLockfileNotFound indicates that a requirements.lock is not found.
	ErrLockfileNotFound = errors.New(lockfileName + " not found")
)

// Dependency describes a chart upon which another chart depends.
//
// Dependencies can be used to express developer intent, or to capture the state
// of a chart.
type Dependency struct {
	// Name is the name of the dependency.
	//
	// This must mach the name in the dependency's Chart.yaml.
	Name string `json:"name"`
	// Version is the version (range) of this chart.
	//
	// A lock file will always produce a single version, while a dependency
	// may contain a semantic version range.
	Version string `json:"version,omitempty"`
	// The URL to the repository.
	//
	// Appending `index.yaml` to this string should result in a URL that can be
	// used to fetch the repository index.
	Repository string `json:"repository"`
	// A yaml path that resolves to a boolean, used for enabling/disabling charts (e.g. subchart1.enabled )
	Condition string `json:"condition,omitempty"`
	// Tags can be used to group charts for enabling/disabling together
	Tags []string `json:"tags,omitempty"`
	// Enabled bool determines if chart should be loaded
	Enabled bool `json:"enabled,omitempty"`
	// ImportValues holds the mapping of source values to parent key to be imported. Each item can be a
	// string or pair of child/parent sublist items.
	ImportValues []interface{} `json:"import-values,omitempty"`
	// Alias usable alias to be used for the chart
	Alias string `json:"alias,omitempty"`
}

// ErrNoRequirementsFile to detect error condition
type ErrNoRequirementsFile error

// Requirements is a list of requirements for a chart.
//
// Requirements are charts upon which this chart depends. This expresses
// developer intent.
type Requirements struct {
	Dependencies []*Dependency `json:"dependencies"`
}

// RequirementsLock is a lock file for requirements.
//
// It represents the state that the dependencies should be in.
type RequirementsLock struct {
	// Genderated is the date the lock file was last generated.
	Generated time.Time `json:"generated"`
	// Digest is a hash of the requirements file used to generate it.
	Digest string `json:"digest"`
	// Dependencies is the list of dependencies that this lock file has locked.
	Dependencies []*Dependency `json:"dependencies"`
}

// LoadRequirements loads a requirements file from an in-memory chart.
func LoadRequirements(c *chart.Chart) (*Requirements, error) {
	var data []byte
	for _, f := range c.Files {
		if f.TypeUrl == requirementsName {
			data = f.Value
		}
	}
	if len(data) == 0 {
		return nil, ErrRequirementsNotFound
	}
	r := &Requirements{}
	return r, yaml.Unmarshal(data, r)
}

// LoadRequirementsLock loads a requirements lock file.
func LoadRequirementsLock(c *chart.Chart) (*RequirementsLock, error) {
	var data []byte
	for _, f := range c.Files {
		if f.TypeUrl == lockfileName {
			data = f.Value
		}
	}
	if len(data) == 0 {
		return nil, ErrLockfileNotFound
	}
	r := &RequirementsLock{}
	return r, yaml.Unmarshal(data, r)
}

// ProcessRequirementsConditions disables charts based on condition path value in values
func ProcessRequirementsConditions(reqs *Requirements, cvals Values) {
	var cond string
	var conds []string
	if reqs == nil || len(reqs.Dependencies) == 0 {
		return
	}
	for _, r := range reqs.Dependencies {
		var hasTrue, hasFalse bool
		cond = string(r.Condition)
		// check for list
		if len(cond) > 0 {
			if strings.Contains(cond, ",") {
				conds = strings.Split(strings.TrimSpace(cond), ",")
			} else {
				conds = []string{strings.TrimSpace(cond)}
			}
			for _, c := range conds {
				if len(c) > 0 {
					// retrieve value
					vv, err := cvals.PathValue(c)
					if err == nil {
						// if not bool, warn
						if bv, ok := vv.(bool); ok {
							if bv {
								hasTrue = true
							} else {
								hasFalse = true
							}
						} else {
							log.Printf("Warning: Condition path '%s' for chart %s returned non-bool value", c, r.Name)
						}
					} else if _, ok := err.(ErrNoValue); !ok {
						// this is a real error
						log.Printf("Warning: PathValue returned error %v", err)

					}
					if vv != nil {
						// got first value, break loop
						break
					}
				}
			}
			if !hasTrue && hasFalse {
				r.Enabled = false
			} else if hasTrue {
				r.Enabled = true

			}
		}

	}

}

// ProcessRequirementsTags disables charts based on tags in values
func ProcessRequirementsTags(reqs *Requirements, cvals Values) {
	vt, err := cvals.Table("tags")
	if err != nil {
		return

	}
	if reqs == nil || len(reqs.Dependencies) == 0 {
		return
	}
	for _, r := range reqs.Dependencies {
		if len(r.Tags) > 0 {
			tags := r.Tags

			var hasTrue, hasFalse bool
			for _, k := range tags {
				if b, ok := vt[k]; ok {
					// if not bool, warn
					if bv, ok := b.(bool); ok {
						if bv {
							hasTrue = true
						} else {
							hasFalse = true
						}
					} else {
						log.Printf("Warning: Tag '%s' for chart %s returned non-bool value", k, r.Name)
					}
				}
			}
			if !hasTrue && hasFalse {
				r.Enabled = false
			} else if hasTrue || !hasTrue && !hasFalse {
				r.Enabled = true

			}

		}
	}

}

func getAliasDependency(charts []*chart.Chart, aliasChart *Dependency) *chart.Chart {
	var chartFound chart.Chart
	for _, existingChart := range charts {
		if existingChart == nil {
			continue
		}
		if existingChart.Metadata == nil {
			continue
		}
		if existingChart.Metadata.Name != aliasChart.Name {
			continue
		}
		if !version.IsCompatibleRange(aliasChart.Version, existingChart.Metadata.Version) {
			continue
		}
		chartFound = *existingChart
		newMetadata := *existingChart.Metadata
		if aliasChart.Alias != "" {
			newMetadata.Name = aliasChart.Alias
		}
		chartFound.Metadata = &newMetadata
		return &chartFound
	}
	return nil
}

// ProcessRequirementsEnabled removes disabled charts from dependencies
func ProcessRequirementsEnabled(c *chart.Chart, v *chart.Config) error {
	reqs, err := LoadRequirements(c)
	if err != nil {
		// if not just missing requirements file, return error
		if nerr, ok := err.(ErrNoRequirementsFile); !ok {
			return nerr
		}

		// no requirements to process
		return nil
	}

	var chartDependencies []*chart.Chart
	// If any dependency is not a part of requirements.yaml
	// then this should be added to chartDependencies.
	// However, if the dependency is already specified in requirements.yaml
	// we should not add it, as it would be anyways processed from requirements.yaml

	for _, existingDependency := range c.Dependencies {
		var dependencyFound bool
		for _, req := range reqs.Dependencies {
			if existingDependency.Metadata.Name == req.Name && version.IsCompatibleRange(req.Version, existingDependency.Metadata.Version) {
				dependencyFound = true
				break
			}
		}
		if !dependencyFound {
			chartDependencies = append(chartDependencies, existingDependency)
		}
	}

	for _, req := range reqs.Dependencies {
		if chartDependency := getAliasDependency(c.Dependencies, req); chartDependency != nil {
			chartDependencies = append(chartDependencies, chartDependency)
		}
		if req.Alias != "" {
			req.Name = req.Alias
		}
	}
	c.Dependencies = chartDependencies

	// set all to true
	for _, lr := range reqs.Dependencies {
		lr.Enabled = true
	}
	cvals, err := CoalesceValues(c, v)
	if err != nil {
		return err
	}
	// convert our values back into config
	yvals, err := cvals.YAML()
	if err != nil {
		return err
	}
	cc := chart.Config{Raw: yvals}
	// flag dependencies as enabled/disabled
	ProcessRequirementsTags(reqs, cvals)
	ProcessRequirementsConditions(reqs, cvals)
	// make a map of charts to remove
	rm := map[string]bool{}
	for _, r := range reqs.Dependencies {
		if !r.Enabled {
			// remove disabled chart
			rm[r.Name] = true
		}
	}
	// don't keep disabled charts in new slice
	cd := []*chart.Chart{}
	copy(cd, c.Dependencies[:0])
	for _, n := range c.Dependencies {
		if _, ok := rm[n.Metadata.Name]; !ok {
			cd = append(cd, n)
		}

	}
	// recursively call self to process sub dependencies
	for _, t := range cd {
		err := ProcessRequirementsEnabled(t, &cc)
		// if its not just missing requirements file, return error
		if nerr, ok := err.(ErrNoRequirementsFile); !ok && err != nil {
			return nerr
		}
	}
	c.Dependencies = cd

	return nil
}

// pathToMap creates a nested map given a YAML path in dot notation.
func pathToMap(path string, data map[string]interface{}) map[string]interface{} {
	if path == "." {
		return data
	}
	ap := strings.Split(path, ".")
	if len(ap) == 0 {
		return nil
	}
	n := []map[string]interface{}{}
	// created nested map for each key, adding to slice
	for _, v := range ap {
		nm := make(map[string]interface{})
		nm[v] = make(map[string]interface{})
		n = append(n, nm)
	}
	// find the last key (map) and set our data
	for i, d := range n {
		for k := range d {
			z := i + 1
			if z == len(n) {
				n[i][k] = data
				break
			}
			n[i][k] = n[z]
		}
	}

	return n[0]
}

// getParents returns a slice of parent charts in reverse order.
func getParents(c *chart.Chart, out []*chart.Chart) []*chart.Chart {
	if len(out) == 0 {
		out = []*chart.Chart{c}
	}
	for _, ch := range c.Dependencies {
		if len(ch.Dependencies) > 0 {
			out = append(out, ch)
			out = getParents(ch, out)
		}
	}

	return out
}

// processImportValues merges values from child to parent based on the chart's dependencies' ImportValues field.
func processImportValues(c *chart.Chart) error {
	reqs, err := LoadRequirements(c)
	if err != nil {
		return err
	}
	// combine chart values and empty config to get Values
	cvals, err := CoalesceValues(c, &chart.Config{})
	if err != nil {
		return err
	}
	b := make(map[string]interface{}, 0)
	// import values from each dependency if specified in import-values
	for _, r := range reqs.Dependencies {
		// only process raw requirement that is found in chart's dependencies (enabled)
		found := false
		name := r.Name
		for _, v := range c.Dependencies {
			if v.Metadata.Name == r.Name {
				found = true
			}
			if v.Metadata.Name == r.Alias {
				found = true
				name = r.Alias
			}
		}
		if !found {
			continue
		}
		if len(r.ImportValues) > 0 {
			var outiv []interface{}
			for _, riv := range r.ImportValues {
				switch iv := riv.(type) {
				case map[string]interface{}:
					nm := map[string]string{
						"child":  iv["child"].(string),
						"parent": iv["parent"].(string),
					}
					outiv = append(outiv, nm)
					s := name + "." + nm["child"]
					// get child table
					vv, err := cvals.Table(s)
					if err != nil {
						log.Printf("Warning: ImportValues missing table: %v", err)
						continue
					}
					// create value map from child to be merged into parent
					vm := pathToMap(nm["parent"], vv.AsMap())
					b = coalesceTables(cvals, vm)
				case string:
					nm := map[string]string{
						"child":  "exports." + iv,
						"parent": ".",
					}
					outiv = append(outiv, nm)
					s := name + "." + nm["child"]
					vm, err := cvals.Table(s)
					if err != nil {
						log.Printf("Warning: ImportValues missing table: %v", err)
						continue
					}
					b = coalesceTables(b, vm.AsMap())
				}
			}
			// set our formatted import values
			r.ImportValues = outiv
		}
	}
	b = coalesceTables(b, cvals)
	y, err := yaml.Marshal(b)
	if err != nil {
		return err
	}

	// set the new values
	c.Values = &chart.Config{Raw: string(y)}

	return nil
}

// ProcessRequirementsImportValues imports specified chart values from child to parent.
func ProcessRequirementsImportValues(c *chart.Chart) error {
	pc := getParents(c, nil)
	for i := len(pc) - 1; i >= 0; i-- {
		processImportValues(pc[i])
	}

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package fileutil

import (
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"os"
	"os/user"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"time"
)

func TestIsDirWriteable(t *testing.T) {
	tmpdir, err := ioutil.TempDir("", "")
	if err != nil {
		t.Fatalf("unexpected ioutil.TempDir error: %v", err)
	}
	defer os.RemoveAll(tmpdir)
	if err = IsDirWriteable(tmpdir); err != nil {
		t.Fatalf("unexpected IsDirWriteable error: %v", err)
	}
	if err = os.Chmod(tmpdir, 0444); err != nil {
		t.Fatalf("unexpected os.Chmod error: %v", err)
	}
	me, err := user.Current()
	if err != nil {
		// err can be non-nil when cross compiled
		// http://stackoverflow.com/questions/20609415/cross-compiling-user-current-not-implemented-on-linux-amd64
		t.Skipf("failed to get current user: %v", err)
	}
	if me.Name == "root" || runtime.GOOS == "windows" {
		// ideally we should check CAP_DAC_OVERRIDE.
		// but it does not matter for tests.
		// Chmod is not supported under windows.
		t.Skipf("running as a superuser or in windows")
	}
	if err := IsDirWriteable(tmpdir); err == nil {
		t.Fatalf("expected IsDirWriteable to error")
	}
}

func TestCreateDirAll(t *testing.T) {
	tmpdir, err := ioutil.TempDir(os.TempDir(), "foo")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	tmpdir2 := filepath.Join(tmpdir, "testdir")
	if err = CreateDirAll(tmpdir2); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(tmpdir2, "text.txt"), []byte("test text"), PrivateFileMode); err != nil {
		t.Fatal(err)
	}

	if err = CreateDirAll(tmpdir2); err == nil || !strings.Contains(err.Error(), "to be empty, got") {
		t.Fatalf("unexpected error %v", err)
	}
}

func TestExist(t *testing.T) {
	fdir := filepath.Join(os.TempDir(), fmt.Sprint(time.Now().UnixNano()+rand.Int63n(1000)))
	os.RemoveAll(fdir)
	if err := os.Mkdir(fdir, 0666); err != nil {
		t.Skip(err)
	}
	defer os.RemoveAll(fdir)
	if !Exist(fdir) {
		t.Fatalf("expected Exist true, got %v", Exist(fdir))
	}

	f, err := ioutil.TempFile(os.TempDir(), "fileutil")
	if err != nil {
		t.Fatal(err)
	}
	f.Close()

	if g := Exist(f.Name()); !g {
		t.Errorf("exist = %v, want true", g)
	}

	os.Remove(f.Name())
	if g := Exist(f.Name()); g {
		t.Errorf("exist = %v, want false", g)
	}
}

func TestDirEmpty(t *testing.T) {
	dir, err := ioutil.TempDir(os.TempDir(), "empty_dir")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	if !DirEmpty(dir) {
		t.Fatalf("expected DirEmpty true, got %v", DirEmpty(dir))
	}

	file, err := ioutil.TempFile(dir, "new_file")
	if err != nil {
		t.Fatal(err)
	}
	file.Close()

	if DirEmpty(dir) {
		t.Fatalf("expected DirEmpty false, got %v", DirEmpty(dir))
	}
	if DirEmpty(file.Name()) {
		t.Fatalf("expected DirEmpty false, got %v", DirEmpty(file.Name()))
	}
}

func TestZeroToEnd(t *testing.T) {
	f, err := ioutil.TempFile(os.TempDir(), "fileutil")
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	// Ensure 0 size is a nop so zero-to-end on an empty file won't give EINVAL.
	if err = ZeroToEnd(f); err != nil {
		t.Fatal(err)
	}

	b := make([]byte, 1024)
	for i := range b {
		b[i] = 12
	}
	if _, err = f.Write(b); err != nil {
		t.Fatal(err)
	}
	if _, err = f.Seek(512, io.SeekStart); err != nil {
		t.Fatal(err)
	}
	if err = ZeroToEnd(f); err != nil {
		t.Fatal(err)
	}
	off, serr := f.Seek(0, io.SeekCurrent)
	if serr != nil {
		t.Fatal(serr)
	}
	if off != 512 {
		t.Fatalf("expected offset 512, got %d", off)
	}

	b = make([]byte, 512)
	if _, err = f.Read(b); err != nil {
		t.Fatal(err)
	}
	for i := range b {
		if b[i] != 0 {
			t.Errorf("expected b[%d] = 0, got %d", i, b[i])
		}
	}
}

func TestDirPermission(t *testing.T) {
	tmpdir, err := ioutil.TempDir(os.TempDir(), "foo")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	tmpdir2 := filepath.Join(tmpdir, "testpermission")
	// create a new dir with 0700
	if err = CreateDirAll(tmpdir2); err != nil {
		t.Fatal(err)
	}
	// check dir permission with mode different than created dir
	if err = CheckDirPermission(tmpdir2, 0600); err == nil {
		t.Errorf("expected error, got nil")
	}
}
<commit_msg>test: cleanup temporary files for TestZeroToEnd<commit_after>// Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package fileutil

import (
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"os"
	"os/user"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"time"
)

func TestIsDirWriteable(t *testing.T) {
	tmpdir, err := ioutil.TempDir("", "")
	if err != nil {
		t.Fatalf("unexpected ioutil.TempDir error: %v", err)
	}
	defer os.RemoveAll(tmpdir)
	if err = IsDirWriteable(tmpdir); err != nil {
		t.Fatalf("unexpected IsDirWriteable error: %v", err)
	}
	if err = os.Chmod(tmpdir, 0444); err != nil {
		t.Fatalf("unexpected os.Chmod error: %v", err)
	}
	me, err := user.Current()
	if err != nil {
		// err can be non-nil when cross compiled
		// http://stackoverflow.com/questions/20609415/cross-compiling-user-current-not-implemented-on-linux-amd64
		t.Skipf("failed to get current user: %v", err)
	}
	if me.Name == "root" || runtime.GOOS == "windows" {
		// ideally we should check CAP_DAC_OVERRIDE.
		// but it does not matter for tests.
		// Chmod is not supported under windows.
		t.Skipf("running as a superuser or in windows")
	}
	if err := IsDirWriteable(tmpdir); err == nil {
		t.Fatalf("expected IsDirWriteable to error")
	}
}

func TestCreateDirAll(t *testing.T) {
	tmpdir, err := ioutil.TempDir(os.TempDir(), "foo")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	tmpdir2 := filepath.Join(tmpdir, "testdir")
	if err = CreateDirAll(tmpdir2); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(tmpdir2, "text.txt"), []byte("test text"), PrivateFileMode); err != nil {
		t.Fatal(err)
	}

	if err = CreateDirAll(tmpdir2); err == nil || !strings.Contains(err.Error(), "to be empty, got") {
		t.Fatalf("unexpected error %v", err)
	}
}

func TestExist(t *testing.T) {
	fdir := filepath.Join(os.TempDir(), fmt.Sprint(time.Now().UnixNano()+rand.Int63n(1000)))
	os.RemoveAll(fdir)
	if err := os.Mkdir(fdir, 0666); err != nil {
		t.Skip(err)
	}
	defer os.RemoveAll(fdir)
	if !Exist(fdir) {
		t.Fatalf("expected Exist true, got %v", Exist(fdir))
	}

	f, err := ioutil.TempFile(os.TempDir(), "fileutil")
	if err != nil {
		t.Fatal(err)
	}
	f.Close()

	if g := Exist(f.Name()); !g {
		t.Errorf("exist = %v, want true", g)
	}

	os.Remove(f.Name())
	if g := Exist(f.Name()); g {
		t.Errorf("exist = %v, want false", g)
	}
}

func TestDirEmpty(t *testing.T) {
	dir, err := ioutil.TempDir(os.TempDir(), "empty_dir")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	if !DirEmpty(dir) {
		t.Fatalf("expected DirEmpty true, got %v", DirEmpty(dir))
	}

	file, err := ioutil.TempFile(dir, "new_file")
	if err != nil {
		t.Fatal(err)
	}
	file.Close()

	if DirEmpty(dir) {
		t.Fatalf("expected DirEmpty false, got %v", DirEmpty(dir))
	}
	if DirEmpty(file.Name()) {
		t.Fatalf("expected DirEmpty false, got %v", DirEmpty(file.Name()))
	}
}

func TestZeroToEnd(t *testing.T) {
	f, err := ioutil.TempFile(os.TempDir(), "fileutil")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(f.Name())
	defer f.Close()

	// Ensure 0 size is a nop so zero-to-end on an empty file won't give EINVAL.
	if err = ZeroToEnd(f); err != nil {
		t.Fatal(err)
	}

	b := make([]byte, 1024)
	for i := range b {
		b[i] = 12
	}
	if _, err = f.Write(b); err != nil {
		t.Fatal(err)
	}
	if _, err = f.Seek(512, io.SeekStart); err != nil {
		t.Fatal(err)
	}
	if err = ZeroToEnd(f); err != nil {
		t.Fatal(err)
	}
	off, serr := f.Seek(0, io.SeekCurrent)
	if serr != nil {
		t.Fatal(serr)
	}
	if off != 512 {
		t.Fatalf("expected offset 512, got %d", off)
	}

	b = make([]byte, 512)
	if _, err = f.Read(b); err != nil {
		t.Fatal(err)
	}
	for i := range b {
		if b[i] != 0 {
			t.Errorf("expected b[%d] = 0, got %d", i, b[i])
		}
	}
}

func TestDirPermission(t *testing.T) {
	tmpdir, err := ioutil.TempDir(os.TempDir(), "foo")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	tmpdir2 := filepath.Join(tmpdir, "testpermission")
	// create a new dir with 0700
	if err = CreateDirAll(tmpdir2); err != nil {
		t.Fatal(err)
	}
	// check dir permission with mode different than created dir
	if err = CheckDirPermission(tmpdir2, 0600); err == nil {
		t.Errorf("expected error, got nil")
	}
}
<|endoftext|>


<commit_before>package gitutils

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"testing"
)

func TestCloneArgsSmartHttp(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	serverURL, _ := url.Parse(server.URL)

	serverURL.Path = "/repo.git"
	gitURL := serverURL.String()

	mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query().Get("service")
		w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", q))
	})

	args := cloneArgs(serverURL, "/tmp")
	exp := []string{"clone", "--recursive", "--depth", "1", gitURL, "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsDumbHttp(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	serverURL, _ := url.Parse(server.URL)

	serverURL.Path = "/repo.git"
	gitURL := serverURL.String()

	mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
	})

	args := cloneArgs(serverURL, "/tmp")
	exp := []string{"clone", "--recursive", gitURL, "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsGit(t *testing.T) {
	u, _ := url.Parse("git://github.com/docker/docker")
	args := cloneArgs(u, "/tmp")
	exp := []string{"clone", "--recursive", "--depth", "1", "git://github.com/docker/docker", "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsStripFragment(t *testing.T) {
	u, _ := url.Parse("git://github.com/docker/docker#test")
	args := cloneArgs(u, "/tmp")
	exp := []string{"clone", "--recursive", "git://github.com/docker/docker", "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCheckoutGit(t *testing.T) {
	root, err := ioutil.TempDir("", "docker-build-git-checkout")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(root)

	eol := "\n"
	if runtime.GOOS == "windows" {
		eol = "\r\n"
	}

	gitDir := filepath.Join(root, "repo")
	_, err = git("init", gitDir)
	if err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644); err != nil {
		t.Fatal(err)
	}

	subDir := filepath.Join(gitDir, "subdir")
	if err = os.Mkdir(subDir, 0755); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if runtime.GOOS != "windows" {
		if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
			t.Fatal(err)
		}

		if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil {
			t.Fatal(err)
		}
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "First commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "-b", "test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "master"); err != nil {
		t.Fatal(err)
	}

	type singleCase struct {
		frag string
		exp  string
		fail bool
	}

	cases := []singleCase{
		{"", "FROM scratch", false},
		{"master", "FROM scratch", false},
		{":subdir", "FROM scratch" + eol + "EXPOSE 5000", false},
		{":nosubdir", "", true},   // missing directory error
		{":Dockerfile", "", true}, // not a directory error
		{"master:nosubdir", "", true},
		{"master:subdir", "FROM scratch" + eol + "EXPOSE 5000", false},
		{"master:../subdir", "", true},
		{"test", "FROM scratch" + eol + "EXPOSE 3000", false},
		{"test:", "FROM scratch" + eol + "EXPOSE 3000", false},
		{"test:subdir", "FROM busybox" + eol + "EXPOSE 5000", false},
	}

	if runtime.GOOS != "windows" {
		// Windows GIT (2.7.1 x64) does not support parentlink/absolutelink. Sample output below
		// 	git --work-tree .\repo --git-dir .\repo\.git add -A
		//	error: readlink("absolutelink"): Function not implemented
		// 	error: unable to index file absolutelink
		// 	fatal: adding files failed
		cases = append(cases, singleCase{frag: "master:absolutelink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
		cases = append(cases, singleCase{frag: "master:parentlink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
	}

	for _, c := range cases {
		r, err := checkoutGit(c.frag, gitDir)

		fail := err != nil
		if fail != c.fail {
			t.Fatalf("Expected %v failure, error was %v\n", c.fail, err)
		}
		if c.fail {
			continue
		}

		b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
		if err != nil {
			t.Fatal(err)
		}

		if string(b) != c.exp {
			t.Fatalf("Expected %v, was %v\n", c.exp, string(b))
		}
	}
}
<commit_msg>Fix gitconfig dependency in pkg/gitutils.TestCheckoutGit<commit_after>package gitutils

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"strings"
	"testing"
)

func TestCloneArgsSmartHttp(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	serverURL, _ := url.Parse(server.URL)

	serverURL.Path = "/repo.git"
	gitURL := serverURL.String()

	mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query().Get("service")
		w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", q))
	})

	args := cloneArgs(serverURL, "/tmp")
	exp := []string{"clone", "--recursive", "--depth", "1", gitURL, "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsDumbHttp(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	serverURL, _ := url.Parse(server.URL)

	serverURL.Path = "/repo.git"
	gitURL := serverURL.String()

	mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
	})

	args := cloneArgs(serverURL, "/tmp")
	exp := []string{"clone", "--recursive", gitURL, "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsGit(t *testing.T) {
	u, _ := url.Parse("git://github.com/docker/docker")
	args := cloneArgs(u, "/tmp")
	exp := []string{"clone", "--recursive", "--depth", "1", "git://github.com/docker/docker", "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsStripFragment(t *testing.T) {
	u, _ := url.Parse("git://github.com/docker/docker#test")
	args := cloneArgs(u, "/tmp")
	exp := []string{"clone", "--recursive", "git://github.com/docker/docker", "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func gitGetConfig(name string) string {
	b, err := git([]string{"config", "--get", name}...)
	if err != nil {
		// since we are interested in empty or non empty string,
		// we can safely ignore the err here.
		return ""
	}
	return strings.TrimSpace(string(b))
}

func TestCheckoutGit(t *testing.T) {
	root, err := ioutil.TempDir("", "docker-build-git-checkout")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(root)

	autocrlf := gitGetConfig("core.autocrlf")
	if !(autocrlf == "true" || autocrlf == "false" ||
		autocrlf == "input" || autocrlf == "") {
		t.Logf("unknown core.autocrlf value: \"%s\"", autocrlf)
	}
	eol := "\n"
	if autocrlf == "true" {
		eol = "\r\n"
	}

	gitDir := filepath.Join(root, "repo")
	_, err = git("init", gitDir)
	if err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644); err != nil {
		t.Fatal(err)
	}

	subDir := filepath.Join(gitDir, "subdir")
	if err = os.Mkdir(subDir, 0755); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if runtime.GOOS != "windows" {
		if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
			t.Fatal(err)
		}

		if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil {
			t.Fatal(err)
		}
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "First commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "-b", "test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "master"); err != nil {
		t.Fatal(err)
	}

	type singleCase struct {
		frag string
		exp  string
		fail bool
	}

	cases := []singleCase{
		{"", "FROM scratch", false},
		{"master", "FROM scratch", false},
		{":subdir", "FROM scratch" + eol + "EXPOSE 5000", false},
		{":nosubdir", "", true},   // missing directory error
		{":Dockerfile", "", true}, // not a directory error
		{"master:nosubdir", "", true},
		{"master:subdir", "FROM scratch" + eol + "EXPOSE 5000", false},
		{"master:../subdir", "", true},
		{"test", "FROM scratch" + eol + "EXPOSE 3000", false},
		{"test:", "FROM scratch" + eol + "EXPOSE 3000", false},
		{"test:subdir", "FROM busybox" + eol + "EXPOSE 5000", false},
	}

	if runtime.GOOS != "windows" {
		// Windows GIT (2.7.1 x64) does not support parentlink/absolutelink. Sample output below
		// 	git --work-tree .\repo --git-dir .\repo\.git add -A
		//	error: readlink("absolutelink"): Function not implemented
		// 	error: unable to index file absolutelink
		// 	fatal: adding files failed
		cases = append(cases, singleCase{frag: "master:absolutelink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
		cases = append(cases, singleCase{frag: "master:parentlink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
	}

	for _, c := range cases {
		r, err := checkoutGit(c.frag, gitDir)

		fail := err != nil
		if fail != c.fail {
			t.Fatalf("Expected %v failure, error was %v\n", c.fail, err)
		}
		if c.fail {
			continue
		}

		b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
		if err != nil {
			t.Fatal(err)
		}

		if string(b) != c.exp {
			t.Fatalf("Expected %v, was %v\n", c.exp, string(b))
		}
	}
}
<|endoftext|>


<commit_before>package gitutils

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"reflect"
	"testing"
)

func TestCloneArgsSmartHttp(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	serverURL, _ := url.Parse(server.URL)

	serverURL.Path = "/repo.git"
	gitURL := serverURL.String()

	mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query().Get("service")
		w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", q))
	})

	args := cloneArgs(serverURL, "/tmp")
	exp := []string{"clone", "--recursive", "--depth", "1", gitURL, "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsDumbHttp(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	serverURL, _ := url.Parse(server.URL)

	serverURL.Path = "/repo.git"
	gitURL := serverURL.String()

	mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
	})

	args := cloneArgs(serverURL, "/tmp")
	exp := []string{"clone", "--recursive", gitURL, "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsGit(t *testing.T) {
	u, _ := url.Parse("git://github.com/docker/docker")
	args := cloneArgs(u, "/tmp")
	exp := []string{"clone", "--recursive", "--depth", "1", "git://github.com/docker/docker", "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsStripFragment(t *testing.T) {
	u, _ := url.Parse("git://github.com/docker/docker#test")
	args := cloneArgs(u, "/tmp")
	exp := []string{"clone", "--recursive", "git://github.com/docker/docker", "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCheckoutGit(t *testing.T) {
	root, err := ioutil.TempDir("", "docker-build-git-checkout")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(root)

	gitDir := filepath.Join(root, "repo")
	_, err = git("init", gitDir)
	if err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644); err != nil {
		t.Fatal(err)
	}

	subDir := filepath.Join(gitDir, "subdir")
	if err = os.Mkdir(subDir, 0755); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
		t.Fatal(err)
	}

	if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "First commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "-b", "test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "master"); err != nil {
		t.Fatal(err)
	}

	cases := []struct {
		frag string
		exp  string
		fail bool
	}{
		{"", "FROM scratch", false},
		{"master", "FROM scratch", false},
		{":subdir", "FROM scratch\nEXPOSE 5000", false},
		{":nosubdir", "", true},   // missing directory error
		{":Dockerfile", "", true}, // not a directory error
		{"master:nosubdir", "", true},
		{"master:subdir", "FROM scratch\nEXPOSE 5000", false},
		{"master:parentlink", "FROM scratch\nEXPOSE 5000", false},
		{"master:absolutelink", "FROM scratch\nEXPOSE 5000", false},
		{"master:../subdir", "", true},
		{"test", "FROM scratch\nEXPOSE 3000", false},
		{"test:", "FROM scratch\nEXPOSE 3000", false},
		{"test:subdir", "FROM busybox\nEXPOSE 5000", false},
	}

	for _, c := range cases {
		r, err := checkoutGit(c.frag, gitDir)

		fail := err != nil
		if fail != c.fail {
			t.Fatalf("Expected %v failure, error was %v\n", c.fail, err)
		}
		if c.fail {
			continue
		}

		b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
		if err != nil {
			t.Fatal(err)
		}

		if string(b) != c.exp {
			t.Fatalf("Expected %v, was %v\n", c.exp, string(b))
		}
	}
}
<commit_msg>Windows CI: Unit tests - port pkg\gitutils<commit_after>package gitutils

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"testing"
)

func TestCloneArgsSmartHttp(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	serverURL, _ := url.Parse(server.URL)

	serverURL.Path = "/repo.git"
	gitURL := serverURL.String()

	mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
		q := r.URL.Query().Get("service")
		w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", q))
	})

	args := cloneArgs(serverURL, "/tmp")
	exp := []string{"clone", "--recursive", "--depth", "1", gitURL, "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsDumbHttp(t *testing.T) {
	mux := http.NewServeMux()
	server := httptest.NewServer(mux)
	serverURL, _ := url.Parse(server.URL)

	serverURL.Path = "/repo.git"
	gitURL := serverURL.String()

	mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
	})

	args := cloneArgs(serverURL, "/tmp")
	exp := []string{"clone", "--recursive", gitURL, "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsGit(t *testing.T) {
	u, _ := url.Parse("git://github.com/docker/docker")
	args := cloneArgs(u, "/tmp")
	exp := []string{"clone", "--recursive", "--depth", "1", "git://github.com/docker/docker", "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCloneArgsStripFragment(t *testing.T) {
	u, _ := url.Parse("git://github.com/docker/docker#test")
	args := cloneArgs(u, "/tmp")
	exp := []string{"clone", "--recursive", "git://github.com/docker/docker", "/tmp"}
	if !reflect.DeepEqual(args, exp) {
		t.Fatalf("Expected %v, got %v", exp, args)
	}
}

func TestCheckoutGit(t *testing.T) {
	root, err := ioutil.TempDir("", "docker-build-git-checkout")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(root)

	eol := "\n"
	if runtime.GOOS == "windows" {
		eol = "\r\n"
	}

	gitDir := filepath.Join(root, "repo")
	_, err = git("init", gitDir)
	if err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644); err != nil {
		t.Fatal(err)
	}

	subDir := filepath.Join(gitDir, "subdir")
	if err = os.Mkdir(subDir, 0755); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if runtime.GOOS != "windows" {
		if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
			t.Fatal(err)
		}

		if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil {
			t.Fatal(err)
		}
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "First commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "-b", "test"); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644); err != nil {
		t.Fatal(err)
	}

	if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit"); err != nil {
		t.Fatal(err)
	}

	if _, err = gitWithinDir(gitDir, "checkout", "master"); err != nil {
		t.Fatal(err)
	}

	type singleCase struct {
		frag string
		exp  string
		fail bool
	}

	cases := []singleCase{
		{"", "FROM scratch", false},
		{"master", "FROM scratch", false},
		{":subdir", "FROM scratch" + eol + "EXPOSE 5000", false},
		{":nosubdir", "", true},   // missing directory error
		{":Dockerfile", "", true}, // not a directory error
		{"master:nosubdir", "", true},
		{"master:subdir", "FROM scratch" + eol + "EXPOSE 5000", false},
		{"master:../subdir", "", true},
		{"test", "FROM scratch" + eol + "EXPOSE 3000", false},
		{"test:", "FROM scratch" + eol + "EXPOSE 3000", false},
		{"test:subdir", "FROM busybox" + eol + "EXPOSE 5000", false},
	}

	if runtime.GOOS != "windows" {
		// Windows GIT (2.7.1 x64) does not support parentlink/absolutelink. Sample output below
		// 	git --work-tree .\repo --git-dir .\repo\.git add -A
		//	error: readlink("absolutelink"): Function not implemented
		// 	error: unable to index file absolutelink
		// 	fatal: adding files failed
		cases = append(cases, singleCase{frag: "master:absolutelink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
		cases = append(cases, singleCase{frag: "master:parentlink", exp: "FROM scratch" + eol + "EXPOSE 5000", fail: false})
	}

	for _, c := range cases {
		r, err := checkoutGit(c.frag, gitDir)

		fail := err != nil
		if fail != c.fail {
			t.Fatalf("Expected %v failure, error was %v\n", c.fail, err)
		}
		if c.fail {
			continue
		}

		b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile"))
		if err != nil {
			t.Fatal(err)
		}

		if string(b) != c.exp {
			t.Fatalf("Expected %v, was %v\n", c.exp, string(b))
		}
	}
}
<|endoftext|>