goa_model_gen 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 10b556d055acc2054efa01a18fa0610dea43bdfa88be354ce818807cdd594a21
4
+ data.tar.gz: e456994ddafd3e12112af08d88bb797326b951ec979d15844187882f6e95eb82
5
+ SHA512:
6
+ metadata.gz: 1d9e5251f038931fd7381e0fe2520e0e10b9c79ccd5a699697878d2fc2d9721ea10cf49aca80e8d3ea4d42b455844b2d2e2e3aca9585053addda0cb7d74ad245
7
+ data.tar.gz: c2dcd3a32e11d48cb97be59d75fd12aa751192414bc64aa4b54ccbb167f0885e7c5c69d3eb48b029348805b5fb27bf269033f0e1879fee4f0024193cd90e011d
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ /Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.5.1
5
+ before_install: gem install bundler -v 1.16.2
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at akm2000@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in goa_model_gen.gemspec
6
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 akm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # GoaModelGen
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/goa_model_gen`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'goa_model_gen'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install goa_model_gen
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/goa_model_gen. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the GoaModelGen project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/goa_model_gen/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "goa_model_gen"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/exe/goa_model_gen ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "goa_model_gen/cli"
4
+
5
+ GoaModelGen::Cli.start(ARGV)
@@ -0,0 +1,33 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "goa_model_gen/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "goa_model_gen"
8
+ spec.version = GoaModelGen::VERSION
9
+ spec.authors = ["akm"]
10
+ spec.email = ["akm2000@gmail.com"]
11
+
12
+ spec.summary = %q{Generate model files for goa in golang}
13
+ spec.description = %q{Generate model files for goa in golang}
14
+ spec.homepage = "https://github.com/akm/goa_model_gen"
15
+ spec.license = "MIT"
16
+
17
+ # Specify which files should be added to the gem when it is released.
18
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
20
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
21
+ end
22
+ spec.bindir = "exe"
23
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
24
+ spec.require_paths = ["lib"]
25
+
26
+ spec.add_runtime_dependency "thor", "~> 0.20.0"
27
+ spec.add_runtime_dependency "activesupport"
28
+
29
+ spec.add_development_dependency "bundler", "~> 1.16"
30
+ spec.add_development_dependency "rake", "~> 10.0"
31
+ spec.add_development_dependency "rspec", "~> 3.0"
32
+ spec.add_development_dependency "pry"
33
+ end
@@ -0,0 +1,5 @@
1
+ require "goa_model_gen/version"
2
+
3
+ module GoaModelGen
4
+ # Your code goes here...
5
+ end
@@ -0,0 +1,77 @@
1
+ require "goa_model_gen"
2
+
3
+ require "erb"
4
+
5
+ require "thor"
6
+
7
+ require "goa_model_gen/loader"
8
+ require "goa_model_gen/generator"
9
+
10
+ module GoaModelGen
11
+ class Cli < Thor
12
+ class_option :swagger_yaml, type: :string, default: './swagger/swagger.yaml', desc: 'Swagger definition YAML file'
13
+
14
+ desc "show FILE1...", "Show model info from definition files"
15
+ def show(*paths)
16
+ load_types_for(paths, options[:swagger_yaml]) do |path, types|
17
+ puts "types in #{path}"
18
+ puts YAML.dump(types)
19
+ end
20
+ end
21
+
22
+ desc "model FILE1...", "Generate model files from definition files"
23
+ option :dir, type: :string, default: './model', desc: 'Output directory path'
24
+ option :gofmt, type: :boolean, default: true, desc: 'Run gofmt for generated file'
25
+ def model(*paths)
26
+ generator = GoaModelGen::Generator.new(File.expand_path('../templates/model.go.erb', __FILE__))
27
+ load_types_for(paths, options[:swagger_yaml]) do |path, types|
28
+ dest = File.join(options[:dir], File.basename(path, ".*") + ".go")
29
+ generator.run(types, dest)
30
+ if options[:gofmt]
31
+ system("gofmt -w #{dest}")
32
+ end
33
+ end
34
+ end
35
+
36
+ desc "converter FILE1...", "Generate converter files from definition files and swagger.yaml"
37
+ option :package, type: :string, default: 'controller', desc: 'package name'
38
+ option :dir, type: :string, default: './controller', desc: 'Output directory path'
39
+ option :gofmt, type: :boolean, default: true, desc: 'Run gofmt for generated file'
40
+ def converter(*paths)
41
+ generator = GoaModelGen::Generator.new(File.expand_path('../templates/converter.go.erb', __FILE__))
42
+ load_types_for(paths, options[:swagger_yaml]) do |path, types|
43
+ dest = File.join(options[:dir], File.basename(path, ".*") + "_conv.go")
44
+ if types.any?{|t| !!t.payload || !!t.media_type}
45
+ generator.run(types, dest)
46
+ if options[:gofmt]
47
+ system("gofmt -w #{dest}")
48
+ end
49
+ end
50
+ end
51
+ end
52
+
53
+ no_commands do
54
+
55
+ def load_types_for(paths, swagger_yaml)
56
+ swagger_loader = GoaModelGen::SwaggerLoader.new(swagger_yaml)
57
+ path_to_types = {}
58
+ defined_types = {}
59
+ paths.each do |path|
60
+ types = GoaModelGen::ModelLoader.new(path).load_types
61
+ types.each{|t| t.assign_swagger_types(swagger_loader) }
62
+ types.each{|t| defined_types[t.name] = t }
63
+ path_to_types[path] = types
64
+ end
65
+ paths.each do |path|
66
+ types = path_to_types[path]
67
+ types.each{|t| t.assign_field_type_base(defined_types) }
68
+ end
69
+ paths.each do |path|
70
+ yield(path, path_to_types[path])
71
+ end
72
+ end
73
+
74
+ end
75
+
76
+ end
77
+ end
@@ -0,0 +1,85 @@
1
+ require 'goa_model_gen'
2
+ require 'goa_model_gen/goa'
3
+
4
+ require "active_support/core_ext/string"
5
+
6
+ module GoaModelGen
7
+ class Field
8
+ attr_reader :name, :type, :default
9
+ attr_accessor :format # for swagger. See https://swagger.io/docs/specification/data-models/data-types/
10
+ attr_accessor :required
11
+ attr_reader :type_obj
12
+ attr_reader :datastore_tag
13
+
14
+ def initialize(name, attrs)
15
+ @name = name
16
+ @type = attrs['type']
17
+ @format = attrs['format']
18
+ @required = attrs['required']
19
+ @default = attrs['default']
20
+ @datastore_tag = attrs['datastore_tag']
21
+ end
22
+
23
+ # https://goa.design/design/overview/
24
+ PRIMITIVE_TYPES = %q[bool int int64 float string time.Time uuid.UUID interface{}]
25
+
26
+ def goa_name
27
+ Goa.capitalize_join(name.split("_"))
28
+ end
29
+
30
+ def primitive?
31
+ PRIMITIVE_TYPES.include?(type)
32
+ end
33
+
34
+ def custom?
35
+ !primitive?
36
+ end
37
+
38
+ def optional?
39
+ !required
40
+ end
41
+
42
+ def not_null?
43
+ required || !default.nil?
44
+ end
45
+ def nullable?
46
+ !not_null?
47
+ end
48
+
49
+ def assign_type_base(types)
50
+ @type_obj = types[self.type]
51
+ end
52
+
53
+ def tag
54
+ json_tag = name.underscore.dup
55
+ json_tag << ',omitempty' if nullable?
56
+ validate_tag = 'required' unless nullable?
57
+ [
58
+ ['json', json_tag],
59
+ ['validate', validate_tag],
60
+ ['datastore', datastore_tag],
61
+ ].map{|k,v| v ? "#{k}:\"#{v}\"" : nil}.compact.join(' ')
62
+ end
63
+
64
+ # https://swagger.io/docs/specification/data-models/data-types/
65
+ # https://tour.golang.org/basics/11
66
+ # https://golang.org/pkg/go/types/#pkg-variables
67
+ SWAGGER_TYPE_TO_GOLANG_TYPE = {
68
+ "string" => Hash.new("string").update(
69
+ "date" => "time.Time",
70
+ "date-time" => "time.Time",
71
+ ),
72
+ "number" => Hash.new("float32").update(
73
+ "double" => "float64",
74
+ ),
75
+ "integer" => Hash.new("int"),
76
+ "boolean" => Hash.new("bool"),
77
+ }
78
+
79
+ def golang_type
80
+ format2type = SWAGGER_TYPE_TO_GOLANG_TYPE[type]
81
+ raise "Golang type not found for #{type}" unless format2type
82
+ return format2type[format]
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,22 @@
1
+ require "goa_model_gen"
2
+
3
+ require "erb"
4
+
5
+ ## Used in templates
6
+ require "active_support/core_ext/string"
7
+
8
+ module GoaModelGen
9
+ class Generator
10
+ def initialize(template_path)
11
+ content = File
12
+ @erb = ERB.new(File.read(template_path), nil, "-")
13
+ @erb.filename = template_path
14
+ end
15
+
16
+ def run(types, path)
17
+ content = @erb.result(binding)
18
+ open(path, 'w'){|f| f.puts(content) }
19
+ end
20
+
21
+ end
22
+ end
@@ -0,0 +1,17 @@
1
+ require 'goa_model_gen'
2
+
3
+ module GoaModelGen
4
+ module Goa
5
+ module_function
6
+
7
+ SPECIAL_NAMES = {
8
+ "id" => "ID",
9
+ "vm" => "VM",
10
+ }
11
+
12
+ def capitalize_join(names, separator = nil)
13
+ names.map{|s| SPECIAL_NAMES[s] || s.capitalize}.join(separator)
14
+ end
15
+
16
+ end
17
+ end
@@ -0,0 +1,98 @@
1
+ require "goa_model_gen"
2
+
3
+ require "yaml"
4
+
5
+ require "goa_model_gen/type"
6
+ require "goa_model_gen/field"
7
+
8
+ module GoaModelGen
9
+ class BaseLoader
10
+ attr_reader :path, :raw
11
+ attr_reader :kind, :types_key, :fields_key
12
+ def initialize(path, kind, types_key, fields_key)
13
+ @path = path
14
+ @kind = kind
15
+ @types_key, @fields_key = types_key, fields_key
16
+ @raw = YAML.load_file(path)
17
+ end
18
+
19
+ def load_types
20
+ raw[types_key].map do |name, definition|
21
+ build_type(name, definition)
22
+ end
23
+ end
24
+
25
+ def build_type(name, d)
26
+ kind.new(name, d).tap do |t|
27
+ if d[fields_key]
28
+ d[fields_key].each do |fname, f|
29
+ t.fields << build_field(fname, f)
30
+ end
31
+ end
32
+ end
33
+ end
34
+
35
+ def build_field(name, f)
36
+ Field.new(name, f)
37
+ end
38
+
39
+ def dig(path)
40
+ dig_into(raw, path.split('/'), [])
41
+ end
42
+
43
+ def dig_into(hash, keys, footprints)
44
+ # puts "dig_into(hash, #{keys.inspect}, #{footprints.inspect})"
45
+ key = keys.shift
46
+ value = hash[key]
47
+ return value if keys.empty?
48
+ raise "No data for #{key} in #{footprints.join('/')}" if value.nil?
49
+ return dig_into(value, keys, footprints + [key])
50
+ end
51
+ end
52
+
53
+ class ModelLoader < BaseLoader
54
+ def initialize(path)
55
+ super(path, Model, 'types', 'fields')
56
+ end
57
+
58
+ def build_field(name, f)
59
+ fd = f.is_a?(Hash) ? f : {'type' => f.to_s}
60
+ fd['type'] ||= 'string'
61
+ super(name, fd)
62
+ end
63
+ end
64
+
65
+ class SwaggerLoader < BaseLoader
66
+ def initialize(path)
67
+ super(path, SwaggerDef, 'definitions', 'properties')
68
+ end
69
+
70
+ def build_type(name, d)
71
+ super(name, d).tap do |r|
72
+ required_fields = d['required']
73
+ r.fields.each do |f|
74
+ f.required = (required_fields || []).include?(f.name)
75
+ end
76
+ end
77
+ end
78
+
79
+ def lookup(name)
80
+ raw[types_key][name]
81
+ end
82
+
83
+ def load(name)
84
+ d = lookup(name)
85
+ unless d
86
+ $stderr.puts("WARNING #{name} not found in #{path}")
87
+ return nil
88
+ end
89
+ build_type(name, d)
90
+ end
91
+
92
+ def load!(name)
93
+ r = load(name)
94
+ raise "#{name} not found in #{path}" unless r
95
+ r
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,78 @@
1
+ package controller
2
+
3
+ import (
4
+ "github.com/groovenauts/blocks-concurrent-batch-server/app"
5
+ "github.com/groovenauts/blocks-concurrent-batch-server/model"
6
+ )
7
+
8
+ <%- types.select(&:gen_converter?).each do |type| -%>
9
+ <%- if type.payload -%>
10
+ func <%= type.name %>PayloadToModel(src *app.<%= type.payload_name %>) model.<%= type.name %> {
11
+ if src == nil {
12
+ return model.<%= type.name %>{}
13
+ }
14
+ return model.<%= type.name %>{
15
+ <%-
16
+ comments = []
17
+
18
+ type.fields_including_id.each do |f|
19
+ pf = type.payload.fields.detect{|pf| f.name.underscore == pf.name }
20
+ if pf.nil?
21
+ comments << "#{f.name} no payload field"
22
+ elsif f.custom?
23
+ -%>
24
+ <%= f.name %>: <%= f.type %>PayloadToModel(src.<%= f.name %>),
25
+ <%- elsif pf.nullable? -%>
26
+ <%= f.name %>: <%= f.type.camelize %>PointerTo<%= f.type.camelize %>(src.<%= f.name %>),
27
+ <%- else -%>
28
+ <%= f.name %>: src.<%= f.name %>,
29
+ <%- end -%>
30
+ <%- end -%>
31
+ <%- comments.each do |comment| -%>
32
+ // <%= comment %>
33
+ <%- end -%>
34
+ <%- type.payload.field_diffs(type.fields.map{|f| f.name.underscore}).each do |pf| -%>
35
+ // No model field for payload field "<%= pf.name %>"
36
+ <%- end -%>
37
+ }
38
+ }
39
+
40
+ <%- end -%>
41
+ <%- if type.media_type -%>
42
+ func <%= type.name %>ModelToMediaType(src *model.<%= type.name %>) *app.<%= type.media_type_name_for_go %> {
43
+ if src == nil {
44
+ return nil
45
+ }
46
+ return &app.<%= type.media_type_name_for_go %>{
47
+ <%-
48
+ comments = []
49
+
50
+ type.fields_including_id.each do |f|
51
+ mf = type.media_type.fields.detect{|mf| f.name == mf.name.camelize }
52
+ if mf.nil?
53
+ comments << "#{f.name} no media type field"
54
+ elsif f.custom?
55
+ if f.type_obj && f.type_obj.base -%>
56
+ <%= mf.goa_name %>: <%= f.type_obj.base %>(src.<%= f.name %>),
57
+ <%- else -%>
58
+ <%= mf.goa_name %>: <%= f.type %>ModelToMediaType(&src.<%= f.name %>),
59
+ <%- end
60
+ else -%>
61
+ <%- if mf.golang_type == f.type -%>
62
+ <%= mf.goa_name %>: <%= mf.nullable? ? '&' : '' %>src.<%= f.name %>,
63
+ <%- else -%>
64
+ <%= mf.goa_name %>: <%= f.type.camelize %>To<%= mf.golang_type.camelize %><%= mf.nullable? ? 'Pointer' : '' %>(src.<%= f.name %>),
65
+ <%- end -%>
66
+ <%- end -%>
67
+ <%- end -%>
68
+ <%- comments.each do |comment| -%>
69
+ // <%= comment %>
70
+ <%- end -%>
71
+ <%- type.media_type.field_diffs(type.fields.map{|f| f.name.underscore}).each do |mf| -%>
72
+ // No field for media type field "<%= mf.name %>"
73
+ <%- end -%>
74
+ }
75
+ }
76
+
77
+ <%- end -%>
78
+ <%- end -%>
@@ -0,0 +1,281 @@
1
+ package model
2
+
3
+ import (
4
+ "fmt"
5
+ "time"
6
+
7
+ "golang.org/x/net/context"
8
+ "google.golang.org/appengine/datastore"
9
+ "google.golang.org/appengine/log"
10
+
11
+ <%- if types.select(&:store?).any?{|m| m.goon['id_type'] == 'UUID'} -%>
12
+ "github.com/goadesign/goa/uuid"
13
+ <%- end -%>
14
+ )
15
+
16
+ <%- types.each do |type| -%>
17
+ <%- if !type.fields.empty? -%>
18
+ type <%= type.name %> struct {
19
+ <%- if type.goon -%>
20
+ <%= type.id_name %> <%= type.id_golang_type %> `datastore:"-" goon:"id" json:"<%= type.id_name.underscore %>"`
21
+ <%- if type.parent -%>
22
+ ParentKey *datastore.Key `datastore:"-" goon:"parent" json:"-"`
23
+ <%- end -%>
24
+ <%- end -%>
25
+ <%- type.fields.each do |field| -%>
26
+ <%= field.name %> <%= field.type %> `<%= field.tag %>`
27
+ <%- end -%>
28
+ }
29
+ <%- elsif type.base -%>
30
+ type <%= type.name %> <%= type.base %>
31
+
32
+ <%- if type.enum_items -%>
33
+ const (
34
+ <%- type.enum_items.each do |item| -%>
35
+ <%= item.camelize %> <%= type.name %> = <%= item.inspect %>
36
+ <%- end -%>
37
+ )
38
+ <%- end -%>
39
+ <%- end -%>
40
+
41
+ <%- end -%>
42
+
43
+ <%- types.select(&:store?).each do |model| -%>
44
+ func (m *<%= model.name %>) PrepareToCreate() error {
45
+ <%- if model.fields.any?{|f| f.name == "CreatedAt"} -%>
46
+ if m.CreatedAt.IsZero() {
47
+ m.CreatedAt = time.Now()
48
+ }
49
+ <%- end -%>
50
+ <%- if model.fields.any?{|f| f.name == "UpdatedAt"} -%>
51
+ if m.UpdatedAt.IsZero() {
52
+ m.UpdatedAt = time.Now()
53
+ }
54
+ <%- end -%>
55
+ return nil
56
+ }
57
+
58
+ func (m *<%= model.name %>) PrepareToUpdate() error {
59
+ <%- if model.fields.any?{|f| f.name == "UpdatedAt"} -%>
60
+ m.UpdatedAt = time.Now()
61
+ <%- end -%>
62
+ return nil
63
+ }
64
+
65
+ <%- if model.parent -%>
66
+ func (m *<%= model.name %>) Parent(ctx context.Context) (*<%= model.parent %>, error) {
67
+ parentStore := &<%= model.parent %>Store{}
68
+ return parentStore.ByKey(ctx, m.ParentKey)
69
+ }
70
+ <%- end -%>
71
+
72
+ <%- end -%>
73
+
74
+ <%- types.select(&:store?).each do |model| -%>
75
+ <%- store_name = "#{model.name}Store" -%>
76
+ type <%= store_name %> struct{
77
+ <%- if model.parent -%>
78
+ ParentKey *datastore.Key
79
+ <%- end -%>
80
+ }
81
+
82
+ func (s *<%= store_name %>) All(ctx context.Context) ([]*<%= model.name %>, error) {
83
+ g := GoonFromContext(ctx)
84
+ r := []*<%= model.name %>{}
85
+ k := g.Kind(new(<%= model.name %>))
86
+ log.Infof(ctx, "Kind is %v\n", k)
87
+ q := datastore.NewQuery(k)
88
+ <%- if model.parent -%>
89
+ q = q.Ancestor(s.ParentKey)
90
+ <%- end -%>
91
+ log.Infof(ctx, "q is %v\n", q)
92
+ _, err := g.GetAll(q.EventualConsistency(), &r)
93
+ if err != nil {
94
+ log.Errorf(ctx, "Failed to GetAll <%= model.name %> because of %v\n", err)
95
+ return nil, err
96
+ }
97
+ return r, nil
98
+ }
99
+
100
+ func (s *<%= store_name %>) ByID(ctx context.Context, <%= model.id_name_var %> <%= model.id_golang_type %>) (*<%= model.name %>, error) {
101
+ <%- if model.parent -%>
102
+ r := <%= model.name %>{ParentKey: s.ParentKey, <%= model.id_name %>: <%= model.id_name_var %>}
103
+ <%- else -%>
104
+ r := <%= model.name %>{<%= model.id_name %>: <%= model.id_name_var %>}
105
+ <%- end -%>
106
+ err := s.Get(ctx, &r)
107
+ if err != nil {
108
+ return nil, err
109
+ }
110
+ return &r, nil
111
+ }
112
+
113
+ func (s *<%= store_name %>) ByKey(ctx context.Context, key *datastore.Key) (*<%= model.name %>, error) {
114
+ if err := s.IsValidKey(ctx, key); err != nil {
115
+ log.Errorf(ctx, "<%= store_name %>.ByKey got Invalid key: %v because of %v\n", key, err)
116
+ return nil, err
117
+ }
118
+
119
+ <%- if model.parent -%>
120
+ r := <%= model.name %>{ParentKey: key.Parent(), <%= model.id_name %>: key.<%= model.key_id_method %>()}
121
+ <%- else -%>
122
+ r := <%= model.name %>{<%= model.id_name %>: key.<%= model.key_id_method %>()}
123
+ <%- end -%>
124
+ err := s.Get(ctx, &r)
125
+ if err != nil {
126
+ return nil, err
127
+ }
128
+ return &r, nil
129
+ }
130
+
131
+ func (s *<%= store_name %>) Get(ctx context.Context, m *<%= model.name %>) error {
132
+ g := GoonFromContext(ctx)
133
+ err := g.Get(m)
134
+ if err != nil {
135
+ log.Errorf(ctx, "Failed to Get <%= model.name %> because of %v\n", err)
136
+ return err
137
+ }
138
+ <%- if model.parent -%>
139
+ if err := s.ValidateParent(m); err != nil {
140
+ log.Errorf(ctx, "Invalid parent key for <%= model.name %> because of %v\n", err)
141
+ return err
142
+ }
143
+ <%- end -%>
144
+
145
+ return nil
146
+ }
147
+
148
+ func (s *<%= store_name %>) IsValidKey(ctx context.Context, key *datastore.Key) error {
149
+ if key == nil {
150
+ return fmt.Errorf("key is nil")
151
+ }
152
+ g := GoonFromContext(ctx)
153
+ expected := g.Kind(&<%= model.name %>{})
154
+ if key.Kind() != expected {
155
+ return fmt.Errorf("key kind must be %s but was %s", expected, key.Kind())
156
+ }
157
+ <%- if model.parent -%>
158
+ if key.Parent() == nil {
159
+ return fmt.Errorf("key parent must not be nil but was nil")
160
+ }
161
+ <%- end -%>
162
+ return nil
163
+ }
164
+
165
+ func (s *<%= store_name %>) Exist(ctx context.Context, m *<%= model.name %>) (bool, error) {
166
+ g := GoonFromContext(ctx)
167
+ key, err := g.KeyError(m)
168
+ if err != nil {
169
+ log.Errorf(ctx, "Failed to Get Key of %v because of %v\n", m, err)
170
+ return false, err
171
+ }
172
+ _, err = s.ByKey(ctx, key)
173
+ if err == datastore.ErrNoSuchEntity {
174
+ return false, nil
175
+ } else if err != nil {
176
+ log.Errorf(ctx, "Failed to get existance of %v because of %v\n", m, err)
177
+ return false, err
178
+ } else {
179
+ return true, nil
180
+ }
181
+ }
182
+
183
+ func (s *<%= store_name %>) Create(ctx context.Context, m *<%= model.name %>) (*datastore.Key, error) {
184
+ err := m.PrepareToCreate()
185
+ if err != nil {
186
+ return nil, err
187
+ }
188
+ if err := m.Validate(); err != nil {
189
+ return nil, err
190
+ }
191
+
192
+ <%- if model.goon['id_type'] == 'string' -%>
193
+ exist, err := s.Exist(ctx, m)
194
+ if err != nil {
195
+ return nil, err
196
+ }
197
+ if exist {
198
+ log.Errorf(ctx, "Failed to create %v because of another entity has same key\n", m)
199
+ return nil, fmt.Errorf("Duplicate Name error: %q of %v\n", m.Name, m)
200
+ }
201
+ <%- end -%>
202
+
203
+ return s.Put(ctx, m)
204
+ }
205
+
206
+ func (s *<%= store_name %>) Update(ctx context.Context, m *<%= model.name %>) (*datastore.Key, error) {
207
+ err := m.PrepareToUpdate()
208
+ if err != nil {
209
+ return nil, err
210
+ }
211
+ if err := m.Validate(); err != nil {
212
+ return nil, err
213
+ }
214
+
215
+ <%- if model.goon['id_type'] == 'string' -%>
216
+ exist, err := s.Exist(ctx, m)
217
+ if err != nil {
218
+ return nil, err
219
+ }
220
+ if !exist {
221
+ log.Errorf(ctx, "Failed to update %v because it doesn't exist\n", m)
222
+ return nil, fmt.Errorf("No data to update %q of %v\n", m.Name, m)
223
+ }
224
+ <%- end -%>
225
+
226
+ return s.Put(ctx, m)
227
+ }
228
+
229
+ func (s *<%= store_name %>) Put(ctx context.Context, m *<%= model.name %>) (*datastore.Key, error) {
230
+ <%- if model.goon['id_type'] == 'UUID' -%>
231
+ if m.Id == "" {
232
+ m.Id = uuid.NewV4().String()
233
+ }
234
+ <%- end -%>
235
+ <%- if model.parent -%>
236
+ if err := s.ValidateParent(m); err != nil {
237
+ log.Errorf(ctx, "Invalid parent key for <%= model.name %> because of %v\n", err)
238
+ return nil, err
239
+ }
240
+ <%- end -%>
241
+ g := GoonFromContext(ctx)
242
+ key, err := g.Put(m)
243
+ if err != nil {
244
+ log.Errorf(ctx, "Failed to Put %v because of %v\n", m, err)
245
+ return nil, err
246
+ }
247
+ return key, nil
248
+ }
249
+
250
+ <%- if model.parent -%>
251
+ func (s *<%= store_name %>) ValidateParent(m *<%= model.name %>) error {
252
+ if s.ParentKey == nil {
253
+ return nil
254
+ }
255
+ if m.ParentKey == nil {
256
+ m.ParentKey = s.ParentKey
257
+ }
258
+ if !s.ParentKey.Equal(m.ParentKey) {
259
+ return fmt.Errorf("Invalid ParentKey for %v", m)
260
+ }
261
+ return nil
262
+ }
263
+
264
+ func (s *<%= store_name %>) Delete(ctx context.Context, m *<%= model.name %>) error {
265
+ g := GoonFromContext(ctx)
266
+ key, err := g.KeyError(m)
267
+ if err != nil {
268
+ log.Errorf(ctx, "Failed to Get %v because of %v\n", m, err)
269
+ return err
270
+ }
271
+ err = g.Delete(key)
272
+ if err != nil {
273
+ log.Errorf(ctx, "Failed to Delete %v because of %v\n", m, err)
274
+ return err
275
+ }
276
+ return nil
277
+ }
278
+
279
+ <%- end -%>
280
+
281
+ <%- end -%>
@@ -0,0 +1,117 @@
1
+ require "goa_model_gen"
2
+
3
+ module GoaModelGen
4
+ class Type
5
+ attr_reader :name, :fields
6
+
7
+ def initialize(name, attrs)
8
+ @name = name
9
+ @fields = []
10
+ end
11
+
12
+ def field_diffs(names)
13
+ self.fields.reject{|f| names.include?(f.name) }
14
+ end
15
+
16
+ def assign_field_type_base(types)
17
+ self.fields.each{|f| f.assign_type_base(types) }
18
+ end
19
+ end
20
+
21
+ class Model < Type
22
+ attr_reader :enum_items, :enum_path
23
+ attr_reader :payload, :media_type
24
+ attr_reader :payload_name, :media_type_name
25
+ attr_reader :goon
26
+ attr_reader :base
27
+ attr_reader :conv
28
+
29
+ def initialize(name, attrs)
30
+ super(name, attrs)
31
+ @base = attrs['base']
32
+ @enum_path = attrs['enum']
33
+ @goon = attrs['goon']
34
+ @payload_name = check_blank(attrs['payload']){ store? ? "#{@name}Payload" : @name }
35
+ @media_type_name = check_blank(attrs['media_type']){ @name }
36
+ @conv = attrs['conv'] || 'generate'
37
+ end
38
+
39
+ def check_blank(s)
40
+ s.nil? ? (block_given? ? yield : nil) :
41
+ (s.empty? || s == '-') ? nil : s
42
+ end
43
+
44
+ def id_golang_type
45
+ if goon && goon['id_type'] == 'UUID'
46
+ return 'string'
47
+ else
48
+ goon && goon['id_type']
49
+ end
50
+ end
51
+
52
+ def id_name
53
+ goon && (goon['id_name'] || 'Id')
54
+ end
55
+
56
+ def id_name_var
57
+ s = id_name
58
+ s.blank? ? nil : s[0].downcase + s[1..-1]
59
+ end
60
+
61
+ def parent
62
+ goon && goon['parent']
63
+ end
64
+
65
+ def store?
66
+ !!goon
67
+ end
68
+
69
+ def key_id_method
70
+ case id_golang_type
71
+ when 'int64' then 'IntID'
72
+ when 'string' then 'StringID'
73
+ else 'UnknownTypeID'
74
+ end
75
+ end
76
+
77
+ def assign_swagger_types(loader)
78
+ $stderr.puts "assign_swagger_types for #{name.inspect}"
79
+ # Original Type: VmDisk
80
+ # Swagger type : VmDisk
81
+ # Goa struct : VMDisk
82
+ # Goa struct name is a little different from others.
83
+ # Use underscore and camelize to regularize it.
84
+ if !fields.empty?
85
+ @payload = loader.load(to_swagger_name(payload_name)) if payload_name
86
+ @media_type = loader.load(media_type_name) if media_type_name
87
+ elsif enum_path
88
+ @enum_items = loader.dig(enum_path)
89
+ end
90
+ end
91
+
92
+ def to_swagger_name(name)
93
+ name.split('-').map{|n| n.underscore.camelize }.join('-')
94
+ end
95
+
96
+ def media_type_name_for_go
97
+ Goa.capitalize_join(media_type_name.split('-').map(&:underscore).map{|n| n.split('_')}.flatten)
98
+ end
99
+
100
+ def gen_converter?
101
+ (conv == 'generate') && !fields.empty?
102
+ end
103
+
104
+ def fields_including_id
105
+ if goon && goon['id_type'] == 'string'
106
+ id_field = Field.new(goon['id_name'], {'type' => 'string'})
107
+ [id_field] + fields
108
+ else
109
+ fields
110
+ end
111
+ end
112
+
113
+ end
114
+
115
+ class SwaggerDef < Type
116
+ end
117
+ end
@@ -0,0 +1,3 @@
1
+ module GoaModelGen
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,151 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: goa_model_gen
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - akm
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-08-17 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: thor
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 0.20.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 0.20.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.16'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.16'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: pry
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description: Generate model files for goa in golang
98
+ email:
99
+ - akm2000@gmail.com
100
+ executables:
101
+ - goa_model_gen
102
+ extensions: []
103
+ extra_rdoc_files: []
104
+ files:
105
+ - ".gitignore"
106
+ - ".rspec"
107
+ - ".travis.yml"
108
+ - CODE_OF_CONDUCT.md
109
+ - Gemfile
110
+ - LICENSE.txt
111
+ - README.md
112
+ - Rakefile
113
+ - bin/console
114
+ - bin/setup
115
+ - exe/goa_model_gen
116
+ - goa_model_gen.gemspec
117
+ - lib/goa_model_gen.rb
118
+ - lib/goa_model_gen/cli.rb
119
+ - lib/goa_model_gen/field.rb
120
+ - lib/goa_model_gen/generator.rb
121
+ - lib/goa_model_gen/goa.rb
122
+ - lib/goa_model_gen/loader.rb
123
+ - lib/goa_model_gen/templates/converter.go.erb
124
+ - lib/goa_model_gen/templates/model.go.erb
125
+ - lib/goa_model_gen/type.rb
126
+ - lib/goa_model_gen/version.rb
127
+ homepage: https://github.com/akm/goa_model_gen
128
+ licenses:
129
+ - MIT
130
+ metadata: {}
131
+ post_install_message:
132
+ rdoc_options: []
133
+ require_paths:
134
+ - lib
135
+ required_ruby_version: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - ">="
138
+ - !ruby/object:Gem::Version
139
+ version: '0'
140
+ required_rubygems_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ requirements: []
146
+ rubyforge_project:
147
+ rubygems_version: 2.7.3
148
+ signing_key:
149
+ specification_version: 4
150
+ summary: Generate model files for goa in golang
151
+ test_files: []