From 2f2afc4068f36b77f6084d80c0804beedbebd91b Mon Sep 17 00:00:00 2001 From: Fernando Briano Date: Thu, 3 Jul 2025 14:05:41 +0100 Subject: [PATCH 1/3] Refactors perform_request_spec, removes dependency on outdated generator code. --- .../spec/unit/perform_request_spec.rb | 51 +++++++++++++++++-- 1 file changed, 47 insertions(+), 4 deletions(-) diff --git a/elasticsearch-api/spec/unit/perform_request_spec.rb b/elasticsearch-api/spec/unit/perform_request_spec.rb index 59324aebc2..1a5cf6541d 100644 --- a/elasticsearch-api/spec/unit/perform_request_spec.rb +++ b/elasticsearch-api/spec/unit/perform_request_spec.rb @@ -18,12 +18,55 @@ require 'elastic-transport' require 'spec_helper' -require_relative File.expand_path('../../utils/thor/endpoint_spec', __dir__) -require_relative File.expand_path('../../utils/thor/generator/files_helper', __dir__) +# Helper Class to replace the EndpointSpec class from the old code generator. The created object +# will store some relevant data to the endpoint specification so that it can be used to test +# OpenTelemetry. +class EndpointSpec + attr_reader :module_namespace, + :method_name, + :endpoint_name, + :visibility + + def initialize(filepath) + @path = Pathname(filepath) + json = MultiJson.load(File.read(@path)) + @endpoint_name = json.keys.first + + full_namespace = parse_full_namespace + @namespace_depth = full_namespace.size.positive? ? full_namespace.size - 1 : 0 + @module_namespace = full_namespace[0, @namespace_depth] + @visivility = json.values.first['visibility'] + end + + def parse_full_namespace + names = @endpoint_name.split('.') + # Return an array to expand 'ccr', 'ilm', 'ml' and 'slm' + names.map do |name| + name + .gsub(/^ml$/, 'machine_learning') + .gsub(/^ilm$/, 'index_lifecycle_management') + .gsub(/^ccr/, 'cross_cluster_replication') + .gsub(/^slm/, 'snapshot_lifecycle_management') + end + end +end + +# JSON spec files to test +# This is a helper which used to be in the FilesHelper module in the old code generator. It goes +# through the files in the Elasticsearch JSON specification to see which methods need to be tested +# and how. +def files + src_path = File.expand_path('../../../tmp/rest-api-spec/api/', __dir__) + + Dir.entries(src_path).reject do |file| + File.extname(file) != '.json' || + File.basename(file) == '_common.json' + end.map { |file| "#{src_path}/#{file}" } +end describe 'Perform request args' do - Elasticsearch::API::FilesHelper.files.each do |filepath| - spec = Elasticsearch::API::EndpointSpec.new(filepath) + files.each do |filepath| + spec = EndpointSpec.new(filepath) next if spec.module_namespace.flatten.first == '_internal' || spec.visibility != 'public' || # TODO: Once the test suite is migrated to elasticsearch-specification, these should be removed From 1b139f9dd696cf585f0075c85585f994fa05d8d8 Mon Sep 17 00:00:00 2001 From: Fernando Briano Date: Thu, 3 Jul 2025 14:06:15 +0100 Subject: [PATCH 2/3] Removes outdated code from perform_request_spec --- elasticsearch-api/spec/unit/perform_request_spec.rb | 2 -- 1 file changed, 2 deletions(-) diff --git a/elasticsearch-api/spec/unit/perform_request_spec.rb b/elasticsearch-api/spec/unit/perform_request_spec.rb index 1a5cf6541d..4ab94c0db9 100644 --- a/elasticsearch-api/spec/unit/perform_request_spec.rb +++ b/elasticsearch-api/spec/unit/perform_request_spec.rb @@ -99,8 +99,6 @@ def files params.merge(part.to_sym => 'testing') end - required_params.merge!(body: {}) if ['inference.put', 'inference.update', 'inference.chat_completion_unified'].include? spec.endpoint_name - let(:client_double) do Class.new { include Elasticsearch::API }.new.tap do |client| expect(client).to receive(:perform_request) do |_, _, _, _, _, request_params| From 8e4eb54005e115e7d35f7ae7d78470b53c9e8984 Mon Sep 17 00:00:00 2001 From: Fernando Briano Date: Thu, 3 Jul 2025 14:06:36 +0100 Subject: [PATCH 3/3] Clean up: Removes old generator code --- Rakefile | 3 +- elasticsearch-api/spec/spec_helper.rb | 10 +- elasticsearch-api/utils/Gemfile | 28 --- elasticsearch-api/utils/README.md | 48 ----- elasticsearch-api/utils/Thorfile | 6 - elasticsearch-api/utils/thor/.rubocop.yml | 4 - elasticsearch-api/utils/thor/endpoint_spec.rb | 201 ------------------ .../utils/thor/endpoint_specifics.rb | 158 -------------- .../utils/thor/generate_source.rb | 127 ----------- .../utils/thor/generator/build_hash_helper.rb | 64 ------ .../utils/thor/generator/docs_helper.rb | 62 ------ .../utils/thor/generator/files_helper.rb | 68 ------ elasticsearch-api/utils/thor/lister.rb | 57 ----- .../utils/thor/templates/_body.erb | 34 --- .../thor/templates/_documentation_top.erb | 56 ----- .../utils/thor/templates/_method_setup.erb | 37 ---- .../utils/thor/templates/_perform_request.erb | 50 ----- .../utils/thor/templates/method.erb | 79 ------- .../utils/thor/templates/test.erb | 43 ---- .../utils/thor/templates/test_helper.rb | 83 -------- 20 files changed, 5 insertions(+), 1213 deletions(-) delete mode 100644 elasticsearch-api/utils/Gemfile delete mode 100644 elasticsearch-api/utils/README.md delete mode 100644 elasticsearch-api/utils/Thorfile delete mode 100644 elasticsearch-api/utils/thor/.rubocop.yml delete mode 100644 elasticsearch-api/utils/thor/endpoint_spec.rb delete mode 100644 elasticsearch-api/utils/thor/endpoint_specifics.rb delete mode 100644 elasticsearch-api/utils/thor/generate_source.rb delete mode 100644 elasticsearch-api/utils/thor/generator/build_hash_helper.rb delete mode 100644 elasticsearch-api/utils/thor/generator/docs_helper.rb delete mode 100644 elasticsearch-api/utils/thor/generator/files_helper.rb delete mode 100644 elasticsearch-api/utils/thor/lister.rb delete mode 100644 elasticsearch-api/utils/thor/templates/_body.erb delete mode 100644 elasticsearch-api/utils/thor/templates/_documentation_top.erb delete mode 100644 elasticsearch-api/utils/thor/templates/_method_setup.erb delete mode 100644 elasticsearch-api/utils/thor/templates/_perform_request.erb delete mode 100644 elasticsearch-api/utils/thor/templates/method.erb delete mode 100644 elasticsearch-api/utils/thor/templates/test.erb delete mode 100644 elasticsearch-api/utils/thor/templates/test_helper.rb diff --git a/Rakefile b/Rakefile index 62a6205a2b..a2d7a7e6d9 100644 --- a/Rakefile +++ b/Rakefile @@ -56,8 +56,7 @@ require 'pathname' CURRENT_PATH = Pathname(File.expand_path(__dir__)) SUBPROJECTS = [ 'elasticsearch', - 'elasticsearch-api', - 'elasticsearch-api/utils' + 'elasticsearch-api' ].freeze RELEASE_TOGETHER = [ diff --git a/elasticsearch-api/spec/spec_helper.rb b/elasticsearch-api/spec/spec_helper.rb index 420a4aecd3..c5904b9d98 100644 --- a/elasticsearch-api/spec/spec_helper.rb +++ b/elasticsearch-api/spec/spec_helper.rb @@ -18,7 +18,6 @@ require 'simplecov' SimpleCov.start do add_filter %r{^/test|spec/} - add_filter 'utils/thor' end end @@ -27,14 +26,13 @@ else require 'debug' end -require 'yaml' -# require 'active_support/isolated_execution_state' unless RUBY_VERSION < '2.7.0' -require 'jbuilder' -require 'jsonify' require 'elasticsearch' require 'elasticsearch-api' -require 'openssl' +require 'jbuilder' +require 'jsonify' require 'logger' +require 'openssl' +require 'yaml' tracer = ::Logger.new(STDERR) tracer.formatter = lambda { |s, d, p, m| "#{m.gsub(/^.*$/) { |n| ' ' + n } }\n" } diff --git a/elasticsearch-api/utils/Gemfile b/elasticsearch-api/utils/Gemfile deleted file mode 100644 index d7a0fe4d5a..0000000000 --- a/elasticsearch-api/utils/Gemfile +++ /dev/null @@ -1,28 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -source 'https://rubygems.org' - -gem 'coderay' - -gem 'json' -gem 'multi_json' -gem 'pry' -gem 'thor' - -gem 'rubocop', '>= 1.51' unless defined?(JRUBY_VERSION) -gem 'debug' unless defined?(JRUBY_VERSION) diff --git a/elasticsearch-api/utils/README.md b/elasticsearch-api/utils/README.md deleted file mode 100644 index c69113941c..0000000000 --- a/elasticsearch-api/utils/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# Utils - -## The Generator - -This directory hosts The Generator, a tool that generates the classes for each API endpoint from the [Elasticsearch REST API JSON Specification](https://github.com/elastic/elasticsearch/tree/main/rest-api-spec). - -### Generate - -To generate the code, you need to have the Elasticsearch REST API spec files in `tmp/rest-api-spec` in the root of the project. You can run a rake task from the root of the project to download the specs corresponding to the current running cluster: -```bash -$ rake es:download_artifacts -``` - -Once the JSON files have been downloaded, you need to run (from this folder): -```bash -$ thor code:generate -``` - -- The Ruby code will be generated in `elasticsearch-api/lib/elasticsearch/api/actions`. -- The generator runs Rubocop to autolint and clean up the generated files. -- You can use the environment variable `IGNORE_VERSION` to ignore the current version of the client when generating the source code documentation urls. This is currently used when generating code from `main`: - -```bash -$ IGNORE_VERSION=true thor code:generate -``` - -- You can use the environment variable `BUILD_HASH` to update the build hash for the generated code from the `tmp/rest-api-spec/build_hash` file. This file is updated every time you use the `es:download_artifacts` Rake task is used in the root of the project to download the latest Elasticsearch specs and tests: -```bash -$ BUILD_HASH=true thor code:generate -``` - -### Development - -The main entry point is `generate_source.rb`, which contains a class that implements a Thor task: `generate`: - -``` -$ thor api:code:generate -``` - -It uses [Thor::Actions](https://github.com/erikhuda/thor/wiki/Actions)' `template` method and `templates/method.erb` to generate the final code. The `generator` directory contains some helpers used to generate the code. The ERB template is split into partials and you can find all ERB files in the `templates` directory. - -There's also a lister task: - -``` -$ thor api:list -``` - -It's implemented in `lister.rb` and it lists all the REST API endpoints from the JSON specification. diff --git a/elasticsearch-api/utils/Thorfile b/elasticsearch-api/utils/Thorfile deleted file mode 100644 index 294dbe9661..0000000000 --- a/elasticsearch-api/utils/Thorfile +++ /dev/null @@ -1,6 +0,0 @@ -# Licensed to Elasticsearch B.V under one or more agreements. -# Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -# See the LICENSE file in the project root for more information - -require File.expand_path('./thor/generate_source') -require File.expand_path('./thor/lister') diff --git a/elasticsearch-api/utils/thor/.rubocop.yml b/elasticsearch-api/utils/thor/.rubocop.yml deleted file mode 100644 index 98a88a262f..0000000000 --- a/elasticsearch-api/utils/thor/.rubocop.yml +++ /dev/null @@ -1,4 +0,0 @@ -Layout/EndAlignment: - AutoCorrect: true -Layout/EmptyComment: - Enabled: false diff --git a/elasticsearch-api/utils/thor/endpoint_spec.rb b/elasticsearch-api/utils/thor/endpoint_spec.rb deleted file mode 100644 index 6b7aca4bdf..0000000000 --- a/elasticsearch-api/utils/thor/endpoint_spec.rb +++ /dev/null @@ -1,201 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# encoding: UTF-8 - -require_relative 'endpoint_specifics' - -module Elasticsearch - module API - class EndpointSpec - include EndpointSpecifics - - def initialize(filepath) - @path = Pathname(filepath) - json = MultiJson.load(File.read(@path)) - @spec = json.values.first - @endpoint_name = json.keys.first - - full_namespace = parse_full_namespace - @namespace_depth = full_namespace.size.positive? ? full_namespace.size - 1 : 0 - @module_namespace = full_namespace[0, @namespace_depth] - @method_name = full_namespace.last - - @path_parts = parse_endpoint_parts(@spec) - @params = @spec['params'] || {} - @paths = @spec['url']['paths'].map { |b| b['path'] } if @spec['url'] - @path_params = path_variables.flatten.uniq.collect(&:to_sym) - @http_method = parse_http_method(@spec) - @deprecation_note = @spec['url']['paths'].last&.[]('deprecated') - @http_path = parse_http_path(@paths) - @required_parts = parse_required_parts(@spec) - end - - attr_reader :module_namespace, - :method_name, - :endpoint_name, - :path, - :path_parts, - :params, - :deprecation_note, - :namespace_depth, - :http_path, - :required_parts, - :http_method, - :path_params, - :perform_request_opts - - def body - @spec['body'] - end - - def documentation - @spec['documentation'] - end - - def stability - @spec['stability'] - end - - def visibility - @spec['visibility'] - end - - def skippable? - module_namespace.flatten.first == '_internal' || visibility != 'public' - end - - # Function that adds the listified h param code - def specific_params - super(@module_namespace.first, @method_name) - end - - private - - def parse_full_namespace - names = @endpoint_name.split('.') - # Return an array to expand 'ccr', 'ilm', 'ml' and 'slm' - names.map do |name| - name - .gsub(/^ml$/, 'machine_learning') - .gsub(/^ilm$/, 'index_lifecycle_management') - .gsub(/^ccr/, 'cross_cluster_replication') - .gsub(/^slm/, 'snapshot_lifecycle_management') - end - end - - def parse_endpoint_parts(spec) - parts = spec['url']['paths'].select do |a| - a.keys.include?('parts') - end.map do |path| - path&.[]('parts') - end - (parts.inject(&:merge) || []) - end - - def parse_http_method(spec) - return '_id ? Elasticsearch::API::HTTP_PUT : Elasticsearch::API::HTTP_POST' if @endpoint_name == 'index' - return '_name ? Elasticsearch::API::HTTP_PUT : Elasticsearch::API::HTTP_POST' if @method_name == 'create_service_token' - return post_and_get if @endpoint_name == 'count' - - default_method = spec['url']['paths'].map { |a| a['methods'] }.flatten.first - if spec['body'] && default_method == 'GET' - # When default method is GET and body is required, we should always use POST - if spec['body']['required'] - 'Elasticsearch::API::HTTP_POST' - else - post_and_get - end - else - "Elasticsearch::API::HTTP_#{default_method}" - end - end - - def parse_http_path(paths) - return "\"#{parse_path(paths.first)}\"" if paths.size == 1 - - result = '' - anchor_string = [] - paths.sort { |a, b| b.length <=> a.length }.each_with_index do |path, i| - var_string = extract_path_variables(path).map { |var| "_#{var}" }.join(' && ') - next if anchor_string.include? var_string - - anchor_string << var_string - result += if i.zero? - "if #{var_string}\n" - elsif (i == paths.size - 1) || var_string.empty? - "else\n" - else - "elsif #{var_string}\n" - end - result += "\"#{parse_path(path)}\"\n" - end - result += 'end' - result - end - - def parse_path(path) - path.gsub(/^\//, '') - .gsub(/\/$/, '') - .gsub('{', "\#{Utils.__listify(_") - .gsub('}', ')}') - end - - def path_variables - @paths.map do |path| - extract_path_variables(path) - end - end - - def parse_path_variables - @paths.map do |path| - extract_path_variables(path) - end - end - - # extract values that are in the {var} format: - def extract_path_variables(path) - path.scan(/{(\w+)}/).flatten - end - - # Find parts that are definitely required and should raise an error if - # they're not present - # - def parse_required_parts(spec) - required = [] - return required if @endpoint_name == 'tasks.get' - - required << 'body' if (spec['body'] && spec['body']['required']) - # Get required variables from paths: - req_variables = parse_path_variables.inject(:&) # find intersection - required << req_variables unless req_variables.empty? - required.flatten - end - - def post_and_get - # the METHOD is defined after doing arguments.delete(:body), so we need to check for `body` - <<~SRC - if body - Elasticsearch::API::HTTP_POST - else - Elasticsearch::API::HTTP_GET - end - SRC - end - end - end -end diff --git a/elasticsearch-api/utils/thor/endpoint_specifics.rb b/elasticsearch-api/utils/thor/endpoint_specifics.rb deleted file mode 100644 index d521b5160b..0000000000 --- a/elasticsearch-api/utils/thor/endpoint_specifics.rb +++ /dev/null @@ -1,158 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -module Elasticsearch - module API - # Handles specific exceptional parameters and code snippets that need to be - # included in the generated code. This module is included in SourceGenerator - # so its methods can be used from the ERB template (method.erb). This will - # potentially be refactored into different templates. - module EndpointSpecifics - # Endpoints that need Utils.__rescue_from_not_found - IGNORE_404 = %w[ - exists - indices.exists - indices.exists_alias - indices.exists_template - ].freeze - - # Endpoints that need Utils.__rescue_from_not_found if the ignore - # parameter is included - COMPLEX_IGNORE_404 = %w[ - clear_scroll - delete - get - indices.delete - indices.delete_template - indices.flush_synced - query_rules.delete_ruleset - security.get_role - security.get_user - snapshot.delete - snapshot.delete_repository - snapshot.get - snapshot.get_repository - snapshot.status - update - watcher.delete_watch - ].freeze - - # Endpoints that need params[:h] listified - H_PARAMS = %w[aliases allocation count health indices nodes pending_tasks - recovery shards thread_pool].freeze - - # Function that adds the listified h param code - def specific_params(namespace, method_name) - params = [] - if H_PARAMS.include?(method_name) && namespace == 'cat' - if method_name == 'nodes' - params << 'params[:h] = Utils.__listify(params[:h], escape: false) if params[:h]' - else - params << 'params[:h] = Utils.__listify(params[:h]) if params[:h]' - end - end - params - end - - def needs_ignore_404?(endpoint) - IGNORE_404.include? endpoint - end - - def needs_complex_ignore_404?(endpoint) - COMPLEX_IGNORE_404.include? endpoint - end - - def module_name_helper(name) - return name.upcase if %w[sql ssl].include? name - - name.split('_').map(&:capitalize).map{ |n| n == 'Xpack' ? 'XPack' : n }.join - end - - def ping_perform_request - <<~SRC - begin - perform_request(method, path, params, body, headers, request_opts).status == 200 ? true : false - rescue Exception => e - if e.class.to_s =~ /NotFound|ConnectionFailed/ || e.message =~ /Not\s*Found|404|ConnectionFailed/i - false - else - raise e - end - end - SRC - end - - def msearch_body_helper - <<~SRC - case - when body.is_a?(Array) && body.any? { |d| d.has_key? :search } - payload = body.inject([]) do |sum, item| - meta = item - data = meta.delete(:search) - - sum << meta - sum << data - sum - end.map { |item| Elasticsearch::API.serializer.dump(item) } - payload << "" unless payload.empty? - payload = payload.join("\\n") - when body.is_a?(Array) - payload = body.map { |d| d.is_a?(String) ? d : Elasticsearch::API.serializer.dump(d) } - payload << "" unless payload.empty? - payload = payload.join("\\n") - else - payload = body - end - SRC - end - - def msearch_template_body_helper - <<~SRC - case - when body.is_a?(Array) - payload = body.map { |d| d.is_a?(String) ? d : Elasticsearch::API.serializer.dump(d) } - payload << "" unless payload.empty? - payload = payload.join("\n") - else - payload = body - end - SRC - end - - def bulk_body_helper - <<~SRC - payload = if body.is_a? Array - Elasticsearch::API::Utils.bulkify(body) - else - body - end - SRC - end - - def find_structure_body_helper - bulk_body_helper - end - - def bulk_doc_helper(info) - <<~SRC - # @option arguments [String|Array] :body #{info}. Array of Strings, Header/Data pairs, - # or the conveniency "combined" format can be passed, refer to Elasticsearch::API::Utils.bulkify documentation. - SRC - end - end - end -end diff --git a/elasticsearch-api/utils/thor/generate_source.rb b/elasticsearch-api/utils/thor/generate_source.rb deleted file mode 100644 index acdf8bb41d..0000000000 --- a/elasticsearch-api/utils/thor/generate_source.rb +++ /dev/null @@ -1,127 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# encoding: UTF-8 - -require 'thor' -require 'pathname' -require 'multi_json' -require 'coderay' -require 'pry' -require_relative 'generator/build_hash_helper' -require_relative 'generator/docs_helper' -require_relative 'generator/files_helper' -require_relative './endpoint_spec' - -module Elasticsearch - module API - # A command line application based on [Thor](https://github.com/wycats/thor), - # which will read the JSON API spec file(s), and generate - # the Ruby source code (one file per API endpoint) with correct - # module namespace, method names, and RDoc documentation, - # as well as test files for each endpoint. - # - # Specific exceptions and code snippets that need to be included are written - # in EndpointSpecifics (generator/endpoint_specifics) and the module is included - # here. - # - class SourceGenerator < Thor - namespace 'code' - include Thor::Actions - include EndpointSpecifics - include DocsHelper - - desc 'generate', 'Generate source code and tests from the REST API JSON specification' - method_option :verbose, type: :boolean, default: false, desc: 'Output more information' - method_option :tests, type: :boolean, default: false, desc: 'Generate test files' - - def generate - @build_hash = BuildHashHelper.build_hash - self.class.source_root File.expand_path(__dir__) - generate_source - - # -- Tree output - print_tree if options[:verbose] - end - - private - - def generate_source - output = FilesHelper.output_dir - cleanup_directory!(output) - - FilesHelper.files.each do |filepath| - @spec = EndpointSpec.new(filepath) - say_status 'json', @spec.path, :yellow - # Don't generate code for internal APIs: - next if @spec.skippable? - - path_to_file = output.join(@spec.module_namespace.join('/')).join("#{@spec.method_name}.rb") - dir = output.join(@spec.module_namespace.join('/')) - empty_directory(dir, verbose: false) - - # Write the file with the ERB template: - template('templates/method.erb', path_to_file, force: true) - - # Optionals: - print_source_code(path_to_file) if options[:verbose] - generate_tests if options[:tests] - end - run_rubocop - BuildHashHelper.add_hash(@build_hash) - end - - def generate_tests - copy_file 'templates/test_helper.rb', @output.join('test').join('test_helper.rb') - - @test_directory = @output.join('test/api').join(@module_namespace.join('/')) - @test_file = @test_directory.join("#{@method_name}_test.rb") - - empty_directory @test_directory - template 'templates/test.erb', @test_file - - print_source_code(@test_file) if options[:verbose] - end - - def print_source_code(path_to_file) - colorized_output = CodeRay.scan_file(path_to_file, :ruby).terminal - lines = colorized_output.split("\n") - formatted = lines.first + "\n" + lines[1, lines.size].map { |l| ' ' * 14 + l }.join("\n") - - say_status('ruby', formatted, :yellow) - end - - def print_tree - return unless `which tree > /dev/null 2>&1; echo $?`.to_i < 1 - - lines = `tree #{@output}`.split("\n") - say_status('tree', lines.first + "\n" + lines[1, lines.size].map { |l| ' ' * 14 + l }.join("\n")) - end - - def cleanup_directory!(output) - Dir["#{output}/**/*.rb"].each do |file| - # file = File.join(@output, f) - File.delete(file) unless (['.', '..'].include? file) || Pathname(file).directory? - end - end - - def run_rubocop - system("rubocop -c ./thor/.rubocop.yml --format autogenconf -a #{FilesHelper::output_dir}") - end - end - end -end diff --git a/elasticsearch-api/utils/thor/generator/build_hash_helper.rb b/elasticsearch-api/utils/thor/generator/build_hash_helper.rb deleted file mode 100644 index bd5d78b59f..0000000000 --- a/elasticsearch-api/utils/thor/generator/build_hash_helper.rb +++ /dev/null @@ -1,64 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -module Elasticsearch - module API - # Helper for the Elasticsearch build hash in source code docs - module BuildHashHelper - class << self - def build_hash - if ENV['BUILD_HASH'] - File.read(File.expand_path('../../../tmp/rest-api-spec/build_hash',__dir__)) - else - original_build_hash - end - end - - def add_hash(build_hash) - Dir.glob("#{FilesHelper.output_dir}/**/*.rb").each do |file| - content = File.read(file) - new_content = content.gsub(/(^#\sunder\sthe\sLicense.\n#)/) do |_| - match = Regexp.last_match - "#{match[1]}\n#{build_hash_comment(build_hash)}" - end - File.open(file, 'w') { |f| f.puts new_content } - end - end - - def build_hash_comment(build_hash) - [ - "Auto generated from build hash #{build_hash}", - '@see https://github.com/elastic/elasticsearch/tree/main/rest-api-spec', - '' - ].map { |b| "# #{b}" }.join("\n").strip - end - - private - - def original_build_hash - content = File.read("#{FilesHelper.output_dir}/info.rb") - - return unless (match = content.match(/Auto generated from build hash ([a-f0-9]+)/)) - - match[1] - rescue - return 'Unavailable' - end - end - end - end -end diff --git a/elasticsearch-api/utils/thor/generator/docs_helper.rb b/elasticsearch-api/utils/thor/generator/docs_helper.rb deleted file mode 100644 index fc41b885da..0000000000 --- a/elasticsearch-api/utils/thor/generator/docs_helper.rb +++ /dev/null @@ -1,62 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -module Elasticsearch - module API - # Helper with file related methods for code generation - module DocsHelper - def docs(name, info) - info['type'] = 'String' if info['type'] == 'enum' # Rename 'enums' to 'strings' - info['type'] = 'Integer' if info['type'] == 'int' # Rename 'int' to 'Integer' - tipo = info['type'] ? info['type'].capitalize : 'String' - description = info['description'] ? info['description'].strip : '[TODO]' - options = info['options'] ? "(options: #{info['options'].join(', ').strip})" : nil - required = info['required'] ? '(*Required*)' : '' - deprecated = info['deprecated'] ? '*Deprecated*' : '' - optionals = [required, deprecated, options].join(' ').strip - - "# @option arguments [#{tipo}] :#{name} #{description} #{optionals}\n" - end - - def stability_doc_helper(stability) - return if stability == 'stable' - - if stability == 'experimental' - <<~MSG - # This functionality is Experimental and may be changed or removed - # completely in a future release. Elastic will take a best effort approach - # to fix any issues, but experimental features are not subject to the - # support SLA of official GA features. - MSG - elsif stability == 'beta' - <<~MSG - # This functionality is in Beta and is subject to change. The design and - # code is less mature than official GA features and is being provided - # as-is with no warranties. Beta features are not subject to the support - # SLA of official GA features. - MSG - else - <<~MSG - # This functionality is subject to potential breaking changes within a - # minor version, meaning that your referencing code may break when this - # library is upgraded. - MSG - end - end - end - end -end diff --git a/elasticsearch-api/utils/thor/generator/files_helper.rb b/elasticsearch-api/utils/thor/generator/files_helper.rb deleted file mode 100644 index be43abc960..0000000000 --- a/elasticsearch-api/utils/thor/generator/files_helper.rb +++ /dev/null @@ -1,68 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -require 'pathname' -require_relative '../../../lib/elasticsearch/api/version.rb' - -module Elasticsearch - module API - # Helper with file related methods for code generation - module FilesHelper - - PROJECT_PATH = File.join(File.dirname(__FILE__), '..') - SRC_PATH = File.join(PROJECT_PATH, '..', '..', '..', 'tmp/rest-api-spec/api/') - OUTPUT_DIR = '../../elasticsearch-api/lib/elasticsearch/api/actions'.freeze - TESTS_DIRECTORY = "#{PROJECT_PATH}/../../../tmp/rest-api-spec/test/free".freeze - - class << self - # Only get JSON files and remove hidden files - def files - json_files = Dir.entries(SRC_PATH) - - json_files.reject do |file| - File.extname(file) != '.json' || - File.basename(file) == '_common.json' - end.map { |file| "#{SRC_PATH}#{file}" } - end - - # Path to directory to copy generated files - def output_dir - Pathname(OUTPUT_DIR) - end - - def documentation_url(documentation_url) - branch = `git rev-parse --abbrev-ref HEAD` - return documentation_url.gsub(/\/(master|main)\//, "/current/") if branch == "main\n" - - regex = /([0-9]{1,2}\.[0-9x]{1,2})/ - version = Elasticsearch::API::VERSION.match(regex)[0] - # TODO - How do we fix this so it doesn't depend on which branch we're running from - if ENV['IGNORE_VERSION'] - documentation_url.gsub(/\/(master|main)\//, "/current/") - else - documentation_url.gsub(/\/(current|master|main)\//, "/#{version}/") - end - end - end - - def cleanup_output_dir! - FileUtils.remove_dir(OUTPUT_DIR) - Dir.mkdir(OUTPUT_DIR) - end - end - end -end diff --git a/elasticsearch-api/utils/thor/lister.rb b/elasticsearch-api/utils/thor/lister.rb deleted file mode 100644 index 6aebe38956..0000000000 --- a/elasticsearch-api/utils/thor/lister.rb +++ /dev/null @@ -1,57 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -# encoding: UTF-8 - -require 'thor' - -require 'pathname' - -module Elasticsearch - module API - class Lister < Thor - namespace 'api' - - DEFAULT_PATH = '../../tmp/elasticsearch/rest-api-spec/src/main/resources/rest-api-spec/api/'.freeze - - desc "list ", "List all the REST API endpoints from the JSON specification" - method_option :verbose, type: :boolean, default: false, desc: 'Output more information' - method_option :format, default: 'text', desc: 'Output format (text, json)' - def list(directory = DEFAULT_PATH) - input = Pathname(directory).join('*.json') - apis = Dir[input.to_s].map do |f| - File.basename(f, '.json') - end.sort - - if options[:verbose] - say_status 'Count', apis.size - say '▬'*terminal_width - end - - case options[:format] - when 'text' - apis.each { |a| puts "* #{a}" } - when 'json' - puts apis.inspect - else - puts "[!] ERROR: Unknown output format '#{options[:format]}'" - exit(1) - end - end - end - end -end diff --git a/elasticsearch-api/utils/thor/templates/_body.erb b/elasticsearch-api/utils/thor/templates/_body.erb deleted file mode 100644 index 458bebeae1..0000000000 --- a/elasticsearch-api/utils/thor/templates/_body.erb +++ /dev/null @@ -1,34 +0,0 @@ -<%# -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -%> -<%- -case @spec.endpoint_name -when 'mtermvectors' --%> - body = if(ids = arguments.delete(:ids)) - { :ids => ids } - else - arguments.delete(:body) - end -<%- when 'cluster.reroute', 'cluster.put_settings' %> - body = arguments.delete(:body) || {} -<%- when 'ml.find_file_structure' %> - body = Utils.bulkify(arguments.delete(:body)) -<%- else -%> - body = <%= @spec.body.nil? ? 'nil' : 'arguments.delete(:body)' %> -<%- end -%> diff --git a/elasticsearch-api/utils/thor/templates/_documentation_top.erb b/elasticsearch-api/utils/thor/templates/_documentation_top.erb deleted file mode 100644 index eb0e6822c2..0000000000 --- a/elasticsearch-api/utils/thor/templates/_documentation_top.erb +++ /dev/null @@ -1,56 +0,0 @@ -<%# -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -%> -<%- if @spec.documentation['description'] -%> - # <%= @spec.documentation['description'].gsub("\n", "\n # ") -%> -<%- else %> - # TODO: Description -<%- end %> -<%= stability_doc_helper(@spec.stability) -%> -# -<%- unless @spec.path_parts.nil? || @spec.path_parts.empty? %><%# URL parts -%> - <%- @spec.path_parts.each do |name, info| -%> - <%= docs(name, info) -%> - <%- end -%> -<%- end -%><%# Body -%> -<%# URL parameters -%> -<%- @spec.params.each do |name, info| -%> - <%= docs(name, info) unless (!@spec.path_parts.empty? && @spec.path_parts.keys.include?(name)) -%> -<%- end -%> -# @option arguments [Hash] :headers Custom HTTP headers -<%- if @spec.body -%> - <%- if @spec.method_name == 'bulk' -%> - <%= bulk_doc_helper(@spec.body['description']) -%> - <%- else -%> - <%= '# @option arguments [Hash] :body ' + (@spec.body['description'] ? - @spec.body['description'].strip : 'TODO: Description') + - (@spec.body['required'] ? ' (*Required*)' : '') + "\n" - -%> - <%- end -%> -<%- end -%> -<% if @spec.deprecation_note -%> - # - # *Deprecation notice*: - # <%= @spec.deprecation_note['description'] %> - # Deprecated since version <%= @spec.deprecation_note['version'] %> - # -<% end -%> -# -<%# Documentation link -%> -# @see <%= @spec.documentation['url'] ? Elasticsearch::API::FilesHelper.documentation_url(@spec.documentation['url']) : "[TODO]" %> -# diff --git a/elasticsearch-api/utils/thor/templates/_method_setup.erb b/elasticsearch-api/utils/thor/templates/_method_setup.erb deleted file mode 100644 index 0e4f14658e..0000000000 --- a/elasticsearch-api/utils/thor/templates/_method_setup.erb +++ /dev/null @@ -1,37 +0,0 @@ -<%# -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -%> -<%- @spec.path_parts.each do |name, _| %> - <%- unless @spec.method_name == 'get_field_mapping' && name == 'fields' %> - <%= "_#{name}" %> = arguments.delete(:<%=name %>) - <%- end -%> -<%- end -%> - -method = <%= @spec.http_method %> -<%- if @spec.method_name == 'termvectors' %> - arguments.delete(:endpoint) -<%- end -%> -path = <%= @spec.http_path %> -<%- if !@spec.params.empty? || needs_ignore_404?(@spec.endpoint_name) || needs_complex_ignore_404?(@spec.endpoint_name)-%> - params = Utils.process_params(arguments) -<%- else -%> - params = {} -<%- end -%> -<%- @spec.specific_params.each do |param| -%> - <%= param %> -<%- end -%> diff --git a/elasticsearch-api/utils/thor/templates/_perform_request.erb b/elasticsearch-api/utils/thor/templates/_perform_request.erb deleted file mode 100644 index cfd50a9d99..0000000000 --- a/elasticsearch-api/utils/thor/templates/_perform_request.erb +++ /dev/null @@ -1,50 +0,0 @@ -<%# -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -%> -<%- if ['bulk', 'msearch', 'msearch_template', 'find_structure'].include? @spec.method_name -%> - <%= self.send("#{@spec.method_name}_body_helper".to_s) %> - headers.merge!("Content-Type" => "application/x-ndjson") - Elasticsearch::API::Response.new( - perform_request(method, path, params, payload, headers, request_opts) - ) -<%- elsif @spec.method_name == 'ping' -%> - <%= ping_perform_request %> -<%- else -%> - <%- if needs_ignore_404?(@spec.endpoint_name) %> - Utils.__rescue_from_not_found do - perform_request(method, path, params, body, headers, request_opts).status == 200 ? true : false - end - <%- elsif needs_complex_ignore_404?(@spec.endpoint_name) -%> - if Array(arguments[:ignore]).include?(404) - Utils.__rescue_from_not_found { - Elasticsearch::API::Response.new( - perform_request(method, path, params, body, headers, request_opts) - ) - } - else - Elasticsearch::API::Response.new( - perform_request(method, path, params, body, headers, request_opts) - ) - end - <%- else -%> - Elasticsearch::API::Response.new( - perform_request(method, path, params, body, headers, request_opts) - ) - <%- end -%> -<%- end -%> -end diff --git a/elasticsearch-api/utils/thor/templates/method.erb b/elasticsearch-api/utils/thor/templates/method.erb deleted file mode 100644 index 5a2a121d24..0000000000 --- a/elasticsearch-api/utils/thor/templates/method.erb +++ /dev/null @@ -1,79 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -module Elasticsearch -module API -<%- @spec.module_namespace.each_with_index do |name, i| -%> - <%= ' '*i %>module <%= module_name_helper(name) %> -<%- end -%> -module Actions -<%= ERB.new(File.new("./thor/templates/_documentation_top.erb").read, trim_mode: '-').result(binding) -%> -<%# Method definition -%> -def <%= @spec.method_name %>(arguments = {}) - request_opts = { endpoint: arguments[:endpoint] || "<%= @spec.endpoint_name %>" } -<%- unless @spec.path_params.empty? %> - defined_params =<%= @spec.path_params %>.inject({}) do |set_variables, variable| - set_variables[variable] = arguments[variable] if arguments.key?(variable) - set_variables - end - request_opts[:defined_params] = defined_params unless defined_params.empty? -<%- end %> -<%- %> -<%- if @spec.endpoint_name == 'create' -%> -if arguments[:id] - index arguments.update op_type: 'create' -else - index arguments -end -end -<%- else -%> - <%- if @spec.method_name == 'get_field_mapping' %> - arguments = arguments.clone - _fields = arguments.delete(:field) || arguments.delete(:fields) - raise ArgumentError, "Required argument 'field' missing" unless _fields - <%- else -%> - <%- @spec.required_parts.each do |required| %><%# Arguments -%> - <%= "raise ArgumentError, \"Required argument '#{required}' missing\" unless arguments[:#{required}]" + "\n" -%> - <%- end -%> - arguments = arguments.clone - <%- end -%> - headers = arguments.delete(:headers) || {} - <%- #Body %> - <%= ERB.new(File.new("./thor/templates/_body.erb").read, trim_mode: '-').result(binding) %> - <%- # Method setup -%> - <%= ERB.new(File.new("./thor/templates/_method_setup.erb").read, trim_mode: '-').result(binding) %> - <%- # Perform request -%> - <%= ERB.new(File.new("./thor/templates/_perform_request.erb").read, trim_mode: '-').result(binding) %> -<%- end -%> -<%- if @spec.method_name.match?(/^exists\S*/) -%> - alias_method :<%= @spec.method_name %>?, :<%= @spec.method_name %> -<%- end -%> -<%- if @spec.method_name == 'termvectors' %> - # Deprecated: Use the plural version, {#termvectors} - # - def termvector(arguments={}) - warn "[DEPRECATION] `termvector` is deprecated. Please use the plural version, `termvectors` instead." - termvectors(arguments.merge(endpoint: '_termvector')) - end -<%- end -%> -<%- @spec.namespace_depth.downto(1) do |i| -%> - <%= ' '*(i-1) %>end -<%- end if @spec.namespace_depth > 0 -%> - - end - end -end diff --git a/elasticsearch-api/utils/thor/templates/test.erb b/elasticsearch-api/utils/thor/templates/test.erb deleted file mode 100644 index 78b5466650..0000000000 --- a/elasticsearch-api/utils/thor/templates/test.erb +++ /dev/null @@ -1,43 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -require 'test_helper' - -module Elasticsearch - module Test - class <%= @module_namespace.map {|n| n.capitalize}.map { |n| n == 'Xpack' ? 'XPack' : n }.join('') + @method_name.camelize %>Test < ::Test::Unit::TestCase - - context "<%= @module_namespace.map {|n| n.capitalize}.map { |n| n == 'Xpack' ? 'XPack' : n }.join(' ') + ': ' %><%= @method_name.humanize %>" do - subject { FakeClient.new } - - should "perform correct request" do - subject.expects(:perform_request).with do |method, url, params, body| - assert_equal 'FAKE', method - assert_equal 'test', url - assert_equal Hash.new, params - <%= @spec['body'].nil? ? 'assert_nil body' : 'assert_equal Hash.new, body' %> - true - end.returns(FakeResponse.new) - - subject.<%= @full_namespace.join('.') %> <%= @spec['url']['parts'].select { |name, info| info['required'] }.keys.map { |d| ":#{d} => 'foo'" }.join(', ') rescue '' %> - end - - end - - end - end -end diff --git a/elasticsearch-api/utils/thor/templates/test_helper.rb b/elasticsearch-api/utils/thor/templates/test_helper.rb deleted file mode 100644 index 8b8f2749c4..0000000000 --- a/elasticsearch-api/utils/thor/templates/test_helper.rb +++ /dev/null @@ -1,83 +0,0 @@ -# Licensed to Elasticsearch B.V. under one or more contributor -# license agreements. See the NOTICE file distributed with -# this work for additional information regarding copyright -# ownership. Elasticsearch B.V. licenses this file to you under -# the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. - -require 'simplecov' and SimpleCov.start { add_filter "/test|test_/" } if ENV["COVERAGE"] - -require 'test/unit' -require 'shoulda-context' -require 'mocha/setup' - -require 'require-prof' if ENV["REQUIRE_PROF"] -Dir[ File.expand_path('../../lib/elasticsearch/api/**/*.rb', __FILE__) ].each do |f| - puts 'Loading: ' + f.to_s if ENV['DEBUG'] - require f -end -RequireProf.print_timing_infos if ENV["REQUIRE_PROF"] - -module Elasticsearch - module Utils - def __validate_and_extract_params(*args) - {} - end - - extend self - end - - module Test - def __full_namespace(o) - o.constants.inject([o]) do |sum, c| - m = o.const_get(c.to_s.to_sym) - sum << __full_namespace(m).flatten if m.is_a?(Module) - sum - end.flatten - end; module_function :__full_namespace - - module Namespace - def cluster - self - end - end - - class FakeClient - # Include all "Actions" modules into the fake client - Elasticsearch::Test.__full_namespace(Elasticsearch::API).select { |m| m.to_s =~ /Actions$/ }.each do |m| - puts "Including: #{m}" if ENV['DEBUG'] - include m - end - - # Include the fake "namespace" methods in the client - include Namespace - - def perform_request(method, path, params, body) - puts "PERFORMING REQUEST:", "--> #{method.to_s.upcase} #{path} #{params} #{body}" - FakeResponse.new(200, 'FAKE', {}) - end - end - - FakeResponse = Struct.new(:status, :body, :headers) do - def status - values[0] || 200 - end - def body - values[1] || '{}' - end - def headers - values[2] || {} - end - end - end -end