Example #1
0
File: parser.go Project: kego/ke
func scanForTypesAndExports(ctx context.Context, env *envctx.Env, cache *sysctx.SysPackageInfo, hash *PackageHasher) error {

	// While we're scanning for types, we should use a custom unpacking env,
	// because the env from the context is the one of the local package.

	files := scanner.ScanDirToFiles(ctx, env.Dir, env.Recursive)
	bytes := scanner.ScanFilesToBytes(ctx, files)
	localContext := envctx.NewContext(ctx, env)
	for b := range bytes {
		if b.Err != nil {
			return kerr.Wrap("JACKALTIGG", b.Err)
		}

		o := &system.ObjectStub{}
		if err := system.Unmarshal(localContext, b.Bytes, o); err != nil {
			return kerr.Wrap("HCYGNBDFFA", err)
		}
		if o.Type == nil {
			return kerr.New("NUKWIHYFMQ", "%s has no type", b.File)
		}
		if o.Id == nil && *o.Type != *system.NewReference("kego.io/system", "package") {
			// we tolerate missing ID only for system:package
			return kerr.New("DLLMKTDYFW", "%s has no id", b.File)
		}
		relativeFile, err := filepath.Rel(env.Dir, b.File)
		if err != nil {
			return kerr.Wrap("AWYRJSCYQS", err)
		}
		switch *o.Type {
		case *system.NewReference("kego.io/system", "type"):
			if err := ProcessTypeFileBytes(ctx, env, relativeFile, b.Bytes, cache, hash); err != nil {
				return kerr.Wrap("IVEFDDSKHE", err)
			}
		case *system.NewReference("kego.io/system", "package"):
			cache.PackageBytes = b.Bytes
			cache.PackageFilename = relativeFile
		default:
			cache.Globals.Set(o.Id.Name, relativeFile)
			if o.Export {
				cache.Exports.Set(o.Id.Name, o.Type.Name, o.Type.Package, b.Bytes)
				if hash != nil {
					hash.Exports[o.Id.Name+" "+o.Type.Name+" "+o.Type.Package] = cityhash.CityHash64(b.Bytes, uint32(len(b.Bytes)))
				}
			}
		}

	}
	return nil
}
Example #2
0
func TestNode_Label(t *testing.T) {
	n := node.NewNode()
	n.Parent = node.NewNode()
	n.Key = ""
	n.Value = ""
	n.Index = -1

	assert.Equal(t, "(?)", n.Label(context.Background()))

	n.Index = 1
	assert.Equal(t, "1", n.Label(context.Background()))

	n.Value = &lab{}
	assert.Equal(t, "b", n.Label(context.Background()))

	n.Key = "a"
	assert.Equal(t, "a", n.Label(context.Background()))

	n.Value = &system.Object{Id: system.NewReference("a.b/c", "d")}
	n.Parent = nil
	assert.Equal(t, "d", n.Label(context.Background()))

	n.Value = nil
	assert.Equal(t, "root", n.Label(context.Background()))

	n = nil
	assert.Equal(t, "(nil)", n.Label(context.Background()))

}
Example #3
0
File: parser.go Project: kego/ke
func ProcessTypeFileBytes(ctx context.Context, env *envctx.Env, filename string, bytes []byte, cache *sysctx.SysPackageInfo, hash *PackageHasher) error {
	t := new(system.Type)
	if err := system.Unmarshal(envctx.NewContext(ctx, env), bytes, t); err != nil {
		return kerr.Wrap("NLRRVIDVWM", err)
	}
	if hash != nil {
		hash.Types[t.Id.Name] = cityhash.CityHash64(bytes, uint32(len(bytes)))
	}
	cache.Types.Set(t.Id.Name, filename, t)
	cache.Files.Set(t.Id.Name, filename, bytes)
	if t.Rule != nil {
		id := system.NewReference(t.Id.Package, fmt.Sprint("@", t.Id.Name))
		if t.Rule.Id != nil && *t.Rule.Id != *id {
			return kerr.New("JKARKEDTIW", "Incorrect id for %v - it should be %v", t.Rule.Id.String(), id.String())
		}
		t.Rule.Id = id

		// Check that the rule embeds system:rule
		found := false
		for _, em := range t.Rule.Embed {
			if *em == *system.NewReference("kego.io/system", "rule") {
				found = true
			}
		}
		if !found {
			return kerr.New("LMALEMKFDI", "%s does not embed system:rule", id.String())
		}

		cache.Types.Set(id.Name, filename, t.Rule)
	} else {
		// If the rule is missing, automatically create a default.
		id := system.NewReference(t.Id.Package, fmt.Sprint("@", t.Id.Name))
		rule := &system.Type{
			Object: &system.Object{
				Description: fmt.Sprintf("Automatically created basic rule for %s", t.Id.Name),
				Type:        system.NewReference("kego.io/system", "type"),
				Id:          id,
			},
			Embed:     []*system.Reference{system.NewReference("kego.io/system", "rule")},
			Native:    system.NewString("object"),
			Interface: false,
		}
		cache.Types.Set(id.Name, filename, rule)
	}

	return nil
}
Example #4
0
func TestRuleWrapper_ZeroValue(t *testing.T) {
	cb := tests.Context("kego.io/system").Jauto().Sauto(parser.Parse)
	r := system.WrapRule(cb.Ctx(), &system.MapRule{
		Object: &system.Object{Type: system.NewReference("kego.io/system", "@map")},
		Rule:   &system.Rule{},
		Items: &system.StringRule{
			Object: &system.Object{Type: system.NewReference("kego.io/system", "@string")},
			Rule:   &system.Rule{},
		},
	})

	v, err := r.ZeroValue(true)
	require.NoError(t, err)
	assert.IsType(t, map[string]*system.String{}, v.Interface())
	assert.Nil(t, v.Interface())

	v, err = r.ZeroValue(false)
	require.NoError(t, err)
	assert.IsType(t, map[string]*system.String{}, v.Interface())
	assert.NotNil(t, v.Interface())
	vv := v.Interface().(map[string]*system.String)
	vv["a"] = system.NewString("")

	r = system.WrapRule(cb.Ctx(), &system.MapRule{
		Object: &system.Object{Type: system.NewReference("kego.io/system", "@array")},
		Rule:   &system.Rule{},
		Items: &system.StringRule{
			Object: &system.Object{Type: system.NewReference("kego.io/system", "@string")},
			Rule:   &system.Rule{},
		},
	})

	v, err = r.ZeroValue(true)
	require.NoError(t, err)
	assert.IsType(t, []*system.String{}, v.Interface())
	assert.Nil(t, v.Interface())

	v, err = r.ZeroValue(false)
	require.NoError(t, err)
	assert.IsType(t, []*system.String{}, v.Interface())
	assert.NotNil(t, v.Interface())
	va := v.Interface().([]*system.String)
	va = append(va, system.NewString(""))
}
Example #5
0
File: ke_test.go Project: kego/ke
func TestKego(t *testing.T) {

	ctx := ke.NewContext(context.Background(), "kego.io/system", nil)

	_, err := ke.Open(ctx, "")
	assert.IsError(t, err, "CXIULJCEBE")

	systemDir, err := packages.GetDirFromPackage(ctx, "kego.io/system")
	require.NoError(t, err)

	i, err := ke.Open(ctx, filepath.Join(systemDir, "type.json"))
	require.NoError(t, err)
	_, ok := i.(*system.Type)
	assert.True(t, ok)

	b, err := ioutil.ReadFile(filepath.Join(systemDir, "type.json"))
	require.NoError(t, err)

	var i1 interface{}
	err = ke.Unmarshal(ctx, b, &i1)
	require.NoError(t, err)
	_, ok = i1.(*system.Type)
	assert.True(t, ok)

	r := &system.Reference{}
	err = ke.Unmarshal(ctx, []byte(`"type"`), r)
	require.NoError(t, err)
	assert.Equal(t, *system.NewReference("kego.io/system", "type"), *r)

	b3, err := ke.Marshal(ctx, system.NewReference("kego.io/system", "type"))
	require.NoError(t, err)
	assert.Equal(t, "{\"type\":\"reference\",\"value\":\"type\"}", string(b3))

	b4, err := ke.MarshalIndent(ctx, &system.Package{Recursive: true}, "", " ")
	require.NoError(t, err)
	assert.Equal(t, "{\n \"recursive\": true\n}", string(b4))

}
Example #6
0
File: branch.go Project: kego/ke
func mutateAppendBranch(s *BranchStore, p *node.Node, n *node.Node, name string, filename string) (child *models.BranchModel, parent *models.BranchModel, err error) {
	var parentBranch *models.BranchModel
	if p == nil {
		if *n.Type.Id == *system.NewReference("kego.io/system", "type") {
			parentBranch = s.types
		} else {
			parentBranch = s.data
		}
	} else {
		var ok bool
		if parentBranch, ok = s.nodeBranches[p]; !ok {
			return nil, nil, nil
		}
	}
	childBranch := s.AppendNodeBranchModelChild(parentBranch, n, name, filename)
	return childBranch, parentBranch, nil
}
Example #7
0
File: node_test.go Project: kego/ke
func TestNode_extractFields(t *testing.T) {
	cb := tests.Context("a.b/c").Sempty()

	ty := &system.Type{}
	f := map[string]*system.Field{}
	err := extractFields(cb.Ctx(), f, ty)
	assert.IsError(t, err, "YRFWOTIGFT")

	cb.Ssystem(parser.Parse)

	ty = &system.Type{Embed: []*system.Reference{system.NewReference("a.b/c", "d")}}
	err = extractFields(cb.Ctx(), f, ty)
	assert.IsError(t, err, "SLIRILCARQ")

	f = map[string]*system.Field{"a": nil}
	ty = &system.Type{Fields: map[string]system.RuleInterface{"a": nil}}
	err = extractFields(cb.Ctx(), f, ty)
	assert.IsError(t, err, "BARXPFXQNB")
}
Example #8
0
File: package.go Project: kego/ke
func Scan(ctx context.Context, path string) (*Package, error) {
	p := new(Package)
	// use a new system context for the duration of the scan
	ctx = sysctx.NewContext(ctx)
	env, err := parser.ScanForEnv(ctx, path)
	if err != nil {
		return nil, kerr.Wrap("SFPSTLPKMX", err)
	}
	p.Env = env
	files := scanner.ScanDirToFiles(ctx, env.Dir, env.Recursive)
	bytes := scanner.ScanFilesToBytes(ctx, files)
	localContext := envctx.NewContext(ctx, env)
	for b := range bytes {
		f := new(File)
		f.Package = p
		if b.Err != nil {
			return nil, kerr.Wrap("IPUHPBBWEA", b.Err)
		}
		o := &system.ObjectStub{}
		if err := system.Unmarshal(localContext, b.Bytes, o); err != nil {
			return nil, kerr.Wrap("DCAGIDLXRT", err)
		}
		if o.Type == nil {
			return nil, kerr.New("AJPCEQTWPS", "%s has no type", b.File)
		}
		if o.Id == nil && *o.Type != *system.NewReference("kego.io/system", "package") {
			// we tolerate missing ID only for system:package
			return nil, kerr.New("YDKYLXTGYC", "%s has no id", b.File)
		}
		f.AbsoluteFilepath = b.File
		f.Type = o.Type
		f.Id = o.Id
		if f.RelativeFilepath, err = filepath.Rel(env.Dir, b.File); err != nil {
			return nil, kerr.Wrap("QDAEGOWTWP", err)
		}
		f.Directory, f.Filename = filepath.Split(b.File)
		f.IsInRoot = DirEqual(f.Directory, env.Dir)
		f.Extension = filepath.Ext(b.File)
		f.Yaml = f.Extension == ".yaml" || f.Extension == ".yml"
		p.Files = append(p.Files, f)
	}
	return p, nil
}
Example #9
0
func newNonEmptyNode() *node.Node {
	n := node.NewNode()
	n.Parent = node.NewNode()
	n.Array = []*node.Node{node.NewNode(), node.NewNode()}
	n.Map = map[string]*node.Node{"a": node.NewNode(), "b": node.NewNode()}
	n.Key = "a"
	n.Index = 1
	n.Origin = system.NewReference("a", "b")
	n.ValueString = "a"
	n.ValueNumber = 2.0
	n.ValueBool = true
	n.Value = "a"
	n.Val = reflect.ValueOf("a")
	n.Null = false
	n.Missing = false
	n.Rule = &system.RuleWrapper{}
	n.Type = &system.Type{}
	n.JsonType = system.J_OBJECT
	return n
}
Example #10
0
func setupForSuccessfulFileLoad(t *testing.T, cb *ctests.ClientContextBuilder) {

	// We have to unmarshal the received object, so we'll have to load some types.
	cb.Base.Path("").Jauto().Sauto(parser.Parse)

	done := make(chan error, 1)

	do := func(method shared.Method, args interface{}, reply interface{}, fail chan error) chan error {
		// Create a simple ke object and marshal it to a []byte
		var bytes []byte
		bytes, err := system.Marshal(cb.Ctx(), &system.Object{Type: system.NewReference("system", "object")})
		require.NoError(t, err)
		reply.(*shared.DataResponse).Found = true
		reply.(*shared.DataResponse).Data = bytes
		close(done)
		return done
	}

	cb.GetConnection().EXPECT().Go(shared.Data, gomock.Any(), gomock.Any(), gomock.Any()).Do(do).Return(done)
}
Example #11
0
File: generated.go Project: kego/ke
func (v *Columns) Repack(ctx context.Context) (data interface{}, typePackage string, typeName string, jsonType system.JsonType, err error) {
	if v == nil {
		return nil, "kego.io/demo/site", "columns", system.J_NULL, nil
	}
	m := map[string]interface{}{}
	if v.Object != nil {
		ob, _, _, _, err := v.Object.Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		for key, val := range ob.(map[string]interface{}) {
			m[key] = val
		}
	}
	if v.Columns != nil {
		ob0 := []interface{}{}
		for i0 := range v.Columns {
			var ob1 interface{}
			ob1_value, pkg, name, typ, err := v.Columns[i0].(system.Repacker).Repack(ctx)
			if err != nil {
				return nil, "", "", "", err
			}
			if system.ShouldUseExplicitTypeNotation(pkg, name, typ, "kego.io/demo/site", "section") {
				typRef := system.NewReference(pkg, name)
				typeVal, err := typRef.ValueContext(ctx)
				if err != nil {
					return nil, "", "", "", err
				}
				ob1 = map[string]interface{}{
					"type":  typeVal,
					"value": ob1_value,
				}
			} else {
				ob1 = ob1_value
			}
			ob0 = append(ob0, ob1)
		}
		m["columns"] = ob0
	}
	return m, "kego.io/demo/site", "columns", system.J_OBJECT, nil
}
Example #12
0
File: parser.go Project: kego/ke
func scanForPackage(ctx context.Context, env *envctx.Env) (*system.Package, error) {
	localContext := envctx.NewContext(ctx, env)
	files := scanner.ScanDirToFiles(ctx, env.Dir, false)
	bytes := scanner.ScanFilesToBytes(ctx, files)
	for b := range bytes {
		if b.Err != nil {
			return nil, kerr.Wrap("GATNNQKNHY", b.Err, b.File)
		}
		o := &system.ObjectStub{}
		if err := system.Unmarshal(localContext, b.Bytes, o); err != nil {
			switch kerr.Source(err).(type) {
			case system.UnknownPackageError, system.UnknownTypeError:
				// don't return error
			default:
				return nil, kerr.Wrap("MTDCXBYBEJ", err, b.File)
			}
		}
		if o.Type == nil {
			return nil, kerr.New("MSNIGTIDIO", "%s has no type", b.File)
		}
		switch *o.Type {
		case *system.NewReference("kego.io/system", "package"):
			var i interface{}
			err := system.Unmarshal(localContext, b.Bytes, &i)
			if err != nil {
				switch kerr.Source(err).(type) {
				case system.UnknownPackageError, system.UnknownTypeError:
					// don't return error
				default:
					return nil, kerr.Wrap("XTEQCAYQJP", err)
				}
			}
			if pkg, ok := i.(*system.Package); ok {
				return pkg, nil
			}
		}
	}
	return nil, nil
}
Example #13
0
File: generated.go Project: kego/ke
func (v *D) Repack(ctx context.Context) (data interface{}, typePackage string, typeName string, jsonType system.JsonType, err error) {
	if v == nil {
		return nil, "kego.io/process/validate/tests", "d", system.J_NULL, nil
	}
	m := map[string]interface{}{}
	if v.Object != nil {
		ob, _, _, _, err := v.Object.Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		for key, val := range ob.(map[string]interface{}) {
			m[key] = val
		}
	}
	if v.A != nil {
		var ob0 interface{}
		ob0_value, pkg, name, typ, err := v.A.(system.Repacker).Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		if system.ShouldUseExplicitTypeNotation(pkg, name, typ, "kego.io/process/validate/tests", "c") {
			typRef := system.NewReference(pkg, name)
			typeVal, err := typRef.ValueContext(ctx)
			if err != nil {
				return nil, "", "", "", err
			}
			ob0 = map[string]interface{}{
				"type":  typeVal,
				"value": ob0_value,
			}
		} else {
			ob0 = ob0_value
		}
		m["a"] = ob0
	}
	return m, "kego.io/process/validate/tests", "d", system.J_OBJECT, nil
}
Example #14
0
func TestRuleWrapper_InnerType(t *testing.T) {
	cb := tests.Context("kego.io/system").Jauto().Sauto(parser.Parse)
	r := system.WrapRule(cb.Ctx(), &system.MapRule{
		Object: &system.Object{Type: system.NewReference("kego.io/system", "@map")},
		Rule:   &system.Rule{},
		Items: &system.StringRule{
			Object: &system.Object{Type: system.NewReference("kego.io/system", "@string")},
			Rule:   &system.Rule{},
		},
	})
	inner := r.InnerType(cb.Ctx())
	assert.Equal(t, "kego.io/system:string", inner.Id.String())

	kind, alias := r.Kind(cb.Ctx())
	assert.False(t, alias)
	assert.Equal(t, kind, system.KindMap)

	assert.False(t, r.PassedAsPointer(cb.Ctx()))

	r = system.WrapRule(cb.Ctx(), &system.DummyRule{
		Object: &system.Object{Type: system.NewReference("kego.io/system", "@int")},
		Rule:   &system.Rule{},
	})
	assert.Equal(t, "kego.io/system:int", r.InnerType(cb.Ctx()).Id.String())

	kind, alias = r.Kind(cb.Ctx())
	assert.True(t, alias)
	assert.Equal(t, kind, system.KindValue)

	assert.True(t, r.PassedAsPointer(cb.Ctx()))

	r = system.WrapRule(cb.Ctx(), &system.DummyRule{
		Object: &system.Object{Type: system.NewReference("kego.io/system", "@int")},
		Rule: &system.Rule{
			Interface: true,
		},
	})
	assert.Equal(t, "kego.io/system:int", r.InnerType(cb.Ctx()).Id.String())

	kind, alias = r.Kind(cb.Ctx())
	assert.False(t, alias)
	assert.Equal(t, kind, system.KindInterface)

	assert.False(t, r.PassedAsPointer(cb.Ctx()))

	r = system.WrapRule(cb.Ctx(), &system.DummyRule{
		Object: &system.Object{Type: system.NewReference("kego.io/json", "@string")},
		Rule:   &system.Rule{},
	})
	assert.Equal(t, "kego.io/json:string", r.InnerType(cb.Ctx()).Id.String())

	assert.False(t, r.PassedAsPointer(cb.Ctx()))

	r = system.WrapRule(cb.Ctx(), &system.DummyRule{
		Object: &system.Object{Type: system.NewReference("kego.io/system", "@package")},
		Rule:   &system.Rule{},
	})
	assert.Equal(t, "kego.io/system:package", r.InnerType(cb.Ctx()).Id.String())

	kind, alias = r.Kind(cb.Ctx())
	assert.False(t, alias)
	assert.Equal(t, kind, system.KindStruct)

	assert.True(t, r.PassedAsPointer(cb.Ctx()))
}
Example #15
0
File: object.go Project: kego/ke
func (v *ObjectEditorView) Render() *vecty.HTML {

	sections := vecty.List{}
	sections = append(sections,
		views.NewPanelNavView(v.Ctx, v.branch).Contents(
			func() vecty.MarkupOrComponentOrHTML {
				return elem.UnorderedList(
					prop.Class("nav navbar-nav navbar-right"),
					elem.ListItem(
						prop.Class("dropdown"),
						elem.Anchor(
							prop.Href("#"),
							prop.Class("dropdown-toggle"),
							vecty.Data("toggle", "dropdown"),
							vecty.Property("role", "button"),
							vecty.Property("aria-haspopup", "true"),
							vecty.Property("aria-expanded", "false"),
							vecty.Text("Options"),
							elem.Span(
								prop.Class("caret"),
							),
						),
						elem.UnorderedList(
							prop.Class("dropdown-menu"),
							elem.ListItem(
								elem.Anchor(
									prop.Href("#"),
									event.Click(func(ev *vecty.Event) {
										v.App.Dispatch(&actions.ToggleSystemControls{
											Node: v.model.Node,
										})
									}).PreventDefault(),
									elem.Italic(
										vecty.ClassMap{
											"dropdown-icon":       true,
											"glyphicon":           true,
											"glyphicon-check":     v.node.ShowSystemControls,
											"glyphicon-unchecked": !v.node.ShowSystemControls,
										},
									),
									vecty.Text("System controls"),
								),
							),
							elem.ListItem(
								prop.Class("divider"),
								vecty.Property("role", "separator"),
							),
							elem.ListItem(
								elem.Anchor(
									prop.Href("#"),
									vecty.Text("Delete"),
									event.Click(func(e *vecty.Event) {
										v.App.Dispatch(&actions.Delete{
											Undoer: &actions.Undoer{},
											Node:   v.model.Node,
											Parent: v.model.Node.Parent,
										})
									}).PreventDefault(),
								),
							),
						),
					),
				)
			},
		),
	)

	d := v.model.Node.Map["description"]
	if !d.Null && !d.Missing && d.ValueString != "" {
		sections = append(sections, elem.Paragraph(
			prop.Class("lead"),
			vecty.Text(d.ValueString),
		))
	}

	if v.App.Misc.Info() {
		dt, err := v.node.Node.DisplayType(v.Ctx)
		if err != nil {
			v.App.Fail <- kerr.Wrap("KFKGCGFULR", err)
			return nil
		}
		sections = append(sections,
			elem.Paragraph(
				prop.Class("lead"),
				vecty.Text("type: "+dt),
			),
		)
	}

	if v.node.ShowSystemControls {
		sections = append(sections,
			elem.Div(
				prop.Class("well object-editor"),
				views.NewEditorListView(v.Ctx, v.model, system.NewReference("kego.io/system", "object"), []string{"id", "type"}),
			),
		)
	}

	return elem.Div(
		sections,
	)

}
Example #16
0
File: file.go Project: kego/ke
func (s *FileStore) Handle(payload *flux.Payload) bool {
	switch action := payload.Action.(type) {
	case *actions.Add:
		payload.Wait(s.app.Nodes)
		if action.Parent != nil {
			// only root nodes are files
			break
		}
		switch action.Direction() {
		case actions.New, actions.Redo:
			n := action.Node
			n.RecomputeHash(s.ctx, true)
			fm := &models.FileModel{
				Package:  false,
				Type:     *action.Type.Id == *system.NewReference("kego.io/system", "type"),
				Filename: action.BranchFile,
				Node:     n,
				Hash:     n.Hash(),
			}
			s.files[n] = fm
		case actions.Undo:
			delete(s.files, action.Node)
		}
		payload.Notify(nil, FileChangedStateChange)
	case *actions.SaveFileSuccess:
		for _, file := range action.Response.Files {
			f := s.fileByName(file.File)
			if f == nil {
				s.app.Fail <- kerr.New("FPXNHFJNOR", "File %s not found", file.File)
			}
			f.SaveHash = file.Hash
		}
		payload.Notify(nil, FileChangedStateChange)
	case *actions.InitialState:
		payload.Wait(s.app.Nodes)
		n := s.app.Package.Node()
		fm := &models.FileModel{
			Package:  true,
			Type:     false,
			Filename: s.app.Package.Filename(),
			Node:     n,
			Hash:     n.Hash(),
			LoadHash: n.Hash(),
		}
		s.files[n] = fm

		for _, ti := range s.app.Types.All() {
			n := ti.Node
			fm := &models.FileModel{
				Package:  false,
				Type:     true,
				Filename: ti.File,
				Node:     n,
				Hash:     n.Hash(),
				LoadHash: n.Hash(),
			}
			s.files[n] = fm
		}
	case *actions.LoadFileSuccess:
		sci, ok := action.Branch.Contents.(models.FileContentsInterface)
		if !ok {
			break
		}
		n := sci.GetNode()
		fm := &models.FileModel{
			Package:  false,
			Type:     false,
			Filename: sci.GetFilename(),
			Node:     n,
			Hash:     n.Hash(),
			LoadHash: n.Hash(),
		}
		s.files[n] = fm
	}

	if m, ok := payload.Action.(actions.Mutator); ok {
		payload.Wait(s.app.Nodes)
		n := m.CommonAncestor().Root()
		f, ok := s.files[n]
		if ok {
			prevChanged := f.Changed()
			f.Hash = n.Hash()
			newChanged := f.Changed()
			if prevChanged != newChanged {
				// state changed!
				payload.Notify(n, FileChangedStateChange)
			}
		}
	}
	return true
}
Example #17
0
File: calls.go Project: kego/ke
func (s *Server) Save(request *shared.SaveRequest, response *shared.SaveResponse) error {
	if !s.auth.Auth([]byte(request.Path), request.Hash) {
		return kerr.New("GIONMMGOWA", "Auth failed")
	}
	pkg, err := pkghelp.Scan(s.ctx, request.Path)
	if err != nil {
		return kerr.Wrap("YKYVDSDGNV", err)
	}
	localContext := envctx.NewContext(s.ctx, pkg.Env)
	for _, info := range request.Files {

		// Check we only have yml, yaml or json extension.
		ext := filepath.Ext(info.File)
		if ext != ".json" && ext != ".yml" && ext != ".yaml" {
			return kerr.New("NDTPTCDOET", "Unsupported extension %s in %s", ext, info.File)
		}

		// Check the bytes are well formed json...
		o := &system.ObjectStub{}
		if err := system.Unmarshal(localContext, info.Bytes, o); err != nil {
			return kerr.Wrap("QISVPOXTCJ", err)
		}
		// Check type field exists
		if o.Type == nil {
			return kerr.New("PHINYFTGEC", "%s has no type", info.File)
		}
		// Check id field exists apart from system:package type.
		if o.Id == nil && *o.Type != *system.NewReference("kego.io/system", "package") {
			return kerr.New("NNOEQPRQXS", "%s has no id", info.File)
		}
		// Convert output to YAML if needed.
		output := info.Bytes
		if ext == ".yaml" || ext == ".yml" {
			var err error
			if output, err = yaml.JSONToYAML(output); err != nil {
				return kerr.Wrap("EAMEWSCAGB", err)
			}
		}

		var mode os.FileMode
		var full string

		file := pkg.File(info.File)
		if file != nil {
			// The file already exists, so we should use the existing filemode
			full = file.AbsoluteFilepath
			fs, err := os.Stat(full)
			if err != nil {
				return kerr.Wrap("VLIJSSVSXU", err)
			}
			mode = fs.Mode()
		} else {
			if full, err = pkghelp.Check(pkg.Env.Dir, info.File, pkg.Env.Recursive); err != nil {
				return kerr.Wrap("YSQEHPFIVF", err)
			}
			mode = 0644
			if _, err := os.Stat(full); err == nil || !os.IsNotExist(err) {
				return kerr.New("XOEPAUNCXB", "Can't overwrite %s - existing file is not a valid ke data file", info.File)
			}
		}

		if err := ioutil.WriteFile(full, output, mode); err != nil {
			return kerr.Wrap("KPDYGCYOYQ", err)
		}

		response.Files = append(response.Files, shared.SaveResponseFile{
			File: info.File,
			Hash: info.Hash,
		})
	}
	return nil
}
Example #18
0
File: generated.go Project: kego/ke
func (v *Body) Repack(ctx context.Context) (data interface{}, typePackage string, typeName string, jsonType system.JsonType, err error) {
	if v == nil {
		return nil, "kego.io/demo/site", "body", system.J_NULL, nil
	}
	m := map[string]interface{}{}
	if v.Object != nil {
		ob, _, _, _, err := v.Object.Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		for key, val := range ob.(map[string]interface{}) {
			m[key] = val
		}
	}
	if v.Align != nil {
		ob0, _, _, _, err := v.Align.Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		m["align"] = ob0
	}
	if v.Copy != nil {
		var ob0 interface{}
		ob0_value, pkg, name, typ, err := v.Copy.(system.Repacker).Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		if system.ShouldUseExplicitTypeNotation(pkg, name, typ, "kego.io/system", "string") {
			typRef := system.NewReference(pkg, name)
			typeVal, err := typRef.ValueContext(ctx)
			if err != nil {
				return nil, "", "", "", err
			}
			ob0 = map[string]interface{}{
				"type":  typeVal,
				"value": ob0_value,
			}
		} else {
			ob0 = ob0_value
		}
		m["copy"] = ob0
	}
	if v.Title != nil {
		var ob0 interface{}
		ob0_value, pkg, name, typ, err := v.Title.(system.Repacker).Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		if system.ShouldUseExplicitTypeNotation(pkg, name, typ, "kego.io/system", "string") {
			typRef := system.NewReference(pkg, name)
			typeVal, err := typRef.ValueContext(ctx)
			if err != nil {
				return nil, "", "", "", err
			}
			ob0 = map[string]interface{}{
				"type":  typeVal,
				"value": ob0_value,
			}
		} else {
			ob0 = ob0_value
		}
		m["title"] = ob0
	}
	return m, "kego.io/demo/site", "body", system.J_OBJECT, nil
}
Example #19
0
File: generated.go Project: kego/ke
func (v *Hero) Repack(ctx context.Context) (data interface{}, typePackage string, typeName string, jsonType system.JsonType, err error) {
	if v == nil {
		return nil, "kego.io/demo/site", "hero", system.J_NULL, nil
	}
	m := map[string]interface{}{}
	if v.Object != nil {
		ob, _, _, _, err := v.Object.Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		for key, val := range ob.(map[string]interface{}) {
			m[key] = val
		}
	}
	if v.Head != nil {
		var ob0 interface{}
		ob0_value, pkg, name, typ, err := v.Head.(system.Repacker).Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		if system.ShouldUseExplicitTypeNotation(pkg, name, typ, "kego.io/system", "string") {
			typRef := system.NewReference(pkg, name)
			typeVal, err := typRef.ValueContext(ctx)
			if err != nil {
				return nil, "", "", "", err
			}
			ob0 = map[string]interface{}{
				"type":  typeVal,
				"value": ob0_value,
			}
		} else {
			ob0 = ob0_value
		}
		m["head"] = ob0
	}
	if v.Image != nil {
		var ob0 interface{}
		ob0_value, pkg, name, typ, err := v.Image.(system.Repacker).Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		if system.ShouldUseExplicitTypeNotation(pkg, name, typ, "kego.io/demo/common/images", "image") {
			typRef := system.NewReference(pkg, name)
			typeVal, err := typRef.ValueContext(ctx)
			if err != nil {
				return nil, "", "", "", err
			}
			ob0 = map[string]interface{}{
				"type":  typeVal,
				"value": ob0_value,
			}
		} else {
			ob0 = ob0_value
		}
		m["image"] = ob0
	}
	if v.Subhead != nil {
		var ob0 interface{}
		ob0_value, pkg, name, typ, err := v.Subhead.(system.Repacker).Repack(ctx)
		if err != nil {
			return nil, "", "", "", err
		}
		if system.ShouldUseExplicitTypeNotation(pkg, name, typ, "kego.io/system", "string") {
			typRef := system.NewReference(pkg, name)
			typeVal, err := typRef.ValueContext(ctx)
			if err != nil {
				return nil, "", "", "", err
			}
			ob0 = map[string]interface{}{
				"type":  typeVal,
				"value": ob0_value,
			}
		} else {
			ob0 = ob0_value
		}
		m["subhead"] = ob0
	}
	return m, "kego.io/demo/site", "hero", system.J_OBJECT, nil
}