Class: Synvert::Core::Rewriter

Inherits:
Object
  • Object
show all
Defined in:
lib/synvert/core/rewriter.rb

Overview

Rewriter is the top level namespace in a snippet.

One Rewriter checks if the depndency version matches, and it can contain one or many Instance, which define the behavior what files and what codes to detect and rewrite to what code.

Defined Under Namespace

Modules: Helper Classes: Condition, GemSpec, GotoScope, IfExistCondition, Instance, ReplaceErbStmtWithExprAction, RubyVersion, Scope, UnlessExistCondition, Warning, WithinScope

Constant Summary collapse

DEFAULT_OPTIONS =
{ run_instance: true, write_to_file: true, parser: 'parser' }.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(group, name) { ... } ⇒ Rewriter

Initialize a Rewriter. When a rewriter is initialized, it is already registered.

Parameters:

  • group (String)

    group of the rewriter.

  • name (String)

    name of the rewriter.

Yields:

  • defines the behaviors of the rewriter, block code won't be called when initialization.



113
114
115
116
117
118
119
120
121
122
# File 'lib/synvert/core/rewriter.rb', line 113

def initialize(group, name, &block)
  @group = group
  @name = name
  @block = block
  @helpers = []
  @sub_snippets = []
  @options = DEFAULT_OPTIONS.dup
  reset
  self.class.register(@group, @name, self)
end

Instance Attribute Details

#affected_filesSet (readonly)

Returns affected fileds.

Returns:

  • (Set)

    affected fileds



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

#gem_specRewriter::GemSpec (readonly)

Returns the gem spec.

Returns:



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

#groupString (readonly)

Returns the group of rewriter.

Returns:

  • (String)

    the group of rewriter



96
97
98
# File 'lib/synvert/core/rewriter.rb', line 96

def group
  @group
end

#helperArray (readonly)

Returns helper methods.

Returns:

  • (Array)

    helper methods.



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

#helpersObject (readonly)

Returns the value of attribute helpers.



96
97
98
# File 'lib/synvert/core/rewriter.rb', line 96

def helpers
  @helpers
end

#nameString (readonly)

Returns the unique name of rewriter.

Returns:

  • (String)

    the unique name of rewriter



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

#optionsHash

Returns the rewriter options.

Returns:

  • (Hash)

    the rewriter options



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

#ruby_versionRewriter::RubyVersion (readonly)

Returns the ruby version.

Returns:



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

#sub_snippetsArray<Synvert::Core::Rewriter> (readonly)

Returns all rewriters this rewiter calls.

Returns:



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

#test_resultsObject (readonly)

Returns the value of attribute test_results.



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

#warningsArray<Synvert::Core::Rewriter::Warning> (readonly)

Returns warning messages.

Returns:



96
97
98
99
100
101
102
103
104
# File 'lib/synvert/core/rewriter.rb', line 96

attr_reader :group,
:name,
:sub_snippets,
:helpers,
:warnings,
:affected_files,
:ruby_version,
:gem_spec,
:test_results

Class Method Details

.availablesHash<String, Hash<String, Synvert::Core::Rewriter>>

Get all available rewriters

Returns:



60
61
62
# File 'lib/synvert/core/rewriter.rb', line 60

def availables
  rewriters
end

.clearObject

Clear all registered rewriters.



65
66
67
# File 'lib/synvert/core/rewriter.rb', line 65

def clear
  rewriters.clear
end

.fetch(group, name) ⇒ Synvert::Core::Rewriter

Fetch a rewriter by group and name.

Parameters:

  • group (String)

    rewrtier group.

  • name (String)

    rewrtier name.

Returns:



51
52
53
54
55
# File 'lib/synvert/core/rewriter.rb', line 51

def fetch(group, name)
  group = group.to_s
  name = name.to_s
  rewriters.dig(group, name)
end

.register(group, name, rewriter) ⇒ Object

Register a rewriter with its group and name.

Parameters:

  • group (String)

    the rewriter group.

  • name (String)

    the unique rewriter name.

  • rewriter (Synvert::Core::Rewriter)

    the rewriter to register.



39
40
41
42
43
44
# File 'lib/synvert/core/rewriter.rb', line 39

def register(group, name, rewriter)
  group = group.to_s
  name = name.to_s
  rewriters[group] ||= {}
  rewriters[group][name] = rewriter
end

Instance Method Details

#add_affected_file(file_path) ⇒ Object

Add an affected file.

Parameters:

  • file_path (String)


176
177
178
# File 'lib/synvert/core/rewriter.rb', line 176

def add_affected_file(file_path)
  @affected_files.add(file_path)
end

#add_file(filename, content) ⇒ Object

It adds a new file.

Examples:

Synvert::Rewriter.new 'rails', 'add_application_record' do
  add_file 'app/models/application_record.rb', <<~EOS
    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
    end
  EOS
end

Parameters:

  • filename (String)

    file name of newly created file.

  • content (String)

    file body of newly created file.



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/synvert/core/rewriter.rb', line 289

def add_file(filename, content)
  return unless @options[:run_instance]

  unless @options[:write_to_file]
    result = NodeMutation::Result.new(affected: true, conflicted: false)
    if Configuration.test_result == 'new_source'
      result.new_source = content
    else
      result.actions = [NodeMutation::Struct::Action.new(:add_file, 0, 0, content)]
    end
    result.file_path = filename
    merge_test_result(result)
    return
  end

  filepath = File.join(Configuration.root_path, filename)
  if File.exist?(filepath)
    puts "File #{filepath} already exists."
    return
  end

  FileUtils.mkdir_p File.dirname(filepath)
  File.write(filepath, content)
end

#add_snippet(group, name = nil) ⇒ Object

It calls anther rewriter.

Examples:

Synvert::Rewriter.new 'minitest', 'better_syntax' do
  add_snippet 'minitest', 'assert_empty'
  add_snippet 'minitest', 'assert_equal_arguments_order'
  add_snippet 'minitest/assert_instance_of'
  add_snippet 'minitest/assert_kind_of'
  add_snippet '/Users/flyerhzm/.synvert-ruby/lib/minitest/assert_match.rb'
  add_snippet '/Users/flyerhzm/.synvert-ruby/lib/minitest/assert_nil.rb'
  add_snippet 'https://github.com/synvert-hq/synvert-snippets-ruby/blob/main/lib/minitest/assert_silent.rb'
  add_snippet 'https://github.com/synvert-hq/synvert-snippets-ruby/blob/main/lib/minitest/assert_truthy.rb'
end

Parameters:

  • group (String)

    group of another rewriter, if there's no name parameter, the group can be http url, file path or snippet name.

  • name (String) (defaults to: nil)

    name of another rewriter.



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/synvert/core/rewriter.rb', line 353

def add_snippet(group, name = nil)
  rewriter =
    if name
      Rewriter.fetch(group, name) || Utils.eval_snippet([group, name].join('/'))
    else
      Utils.eval_snippet(group)
    end
  return unless rewriter && rewriter.is_a?(Rewriter)

  rewriter.options = @options
  preserve_current_parser do
    if !rewriter.options[:write_to_file]
      results = rewriter.test
      merge_test_results(results)
    elsif rewriter.options[:run_instance]
      rewriter.process
    else
      rewriter.process_with_sandbox
    end
  end
  @sub_snippets << rewriter
end

#add_warning(warning) ⇒ Object

Add a warning.

Parameters:



169
170
171
# File 'lib/synvert/core/rewriter.rb', line 169

def add_warning(warning)
  @warnings << warning
end

#call_helper(name, options = {}) ⇒ Object

It calls a shared rewriter.

Examples:

Synvert::Rewriter.new 'rails', 'upgrade_6_0_to_6_1' do
  call_helper 'rails/set_load_defaults', rails_version: '6.1'
  add_snippet '/Users/flyerhzm/.synvert-ruby/lib/rails/set_load_defaults.rb', rails_version: '6.1'
  add_snippet 'https://github.com/synvert-hq/synvert-snippets-ruby/blob/main/lib/rails/set_load_defaults.rb', rails_version: '6.1'
end

Parameters:

  • name (String)

    name of helper.

  • options (Hash) (defaults to: {})

    options to pass to helper.



385
386
387
388
389
390
391
392
# File 'lib/synvert/core/rewriter.rb', line 385

def call_helper(name, options = {})
  helper = Synvert::Core::Helper.fetch(name) || Utils.eval_snippet(name)
  return unless helper && helper.is_a?(Synvert::Core::Helper)

  preserve_current_parser do
    instance_exec(options, &helper.block)
  end
end

#configure(options) ⇒ Object

Configure the rewriter

Examples:

configure({ parser: Synvert::PARSER_PARSER })
configure({ strategy: 'allow_insert_at_same_position' })

Parameters:

  • options (Hash)
  • parser (Hash)

    a customizable set of options

  • strategy (Hash)

    a customizable set of options



202
203
204
205
206
207
# File 'lib/synvert/core/rewriter.rb', line 202

def configure(options)
  @options = @options.merge(options)
  if options[:parser] && !Synvert::ALL_PARSERS.include?(options[:parser])
    raise Errors::ParserNotSupported.new("Parser #{options[:parser]} not supported")
  end
end

#description(description = nil) ⇒ Object

It sets description of the rewrite or get description.

Examples:

Synvert::Rewriter.new 'rspec', 'use_new_syntax' do
  description 'It converts rspec code to new syntax, it calls all rspec sub snippets.'
end

Parameters:

  • description (String) (defaults to: nil)

    rewriter description.

Returns:

  • rewriter description.



216
217
218
219
220
221
222
# File 'lib/synvert/core/rewriter.rb', line 216

def description(description = nil)
  if description
    @description = description
  else
    @description
  end
end

#helper_method(name) { ... } ⇒ Object

It defines helper method for Instance.

Examples:

Synvert::Rewriter.new 'rails', 'convert_active_record_dirty_5_0_to_5_1' do
  helper_method :find_callbacks_and_convert do |callback_names, callback_changes|
    # do anything, method find_callbacks_and_convert can be reused later.
  end
  within_files Synvert::RAILS_MODEL_FILES + Synvert::RAILS_OBSERVER_FILES do
    find_callbacks_and_convert(before_callback_names, before_callback_changes)
    find_callbacks_and_convert(after_callback_names, after_callback_changes)
  end
end

Parameters:

  • name (String)

    helper method name.

Yields:

  • helper method block.



407
408
409
# File 'lib/synvert/core/rewriter.rb', line 407

def helper_method(name, &block)
  @helpers << { name: name, block: block }
end

#if_gem(name, version) ⇒ Object

It compares version of the specified gem.

Examples:

Synvert::Rewriter.new 'rails', 'upgrade_5_2_to_6_0' do
  if_gem 'rails', '>= 6.0'
end

Parameters:

  • name (String)

    gem name.

  • version (String)

    equal, less than or greater than specified version, e.g. '>= 2.0.0',



241
242
243
# File 'lib/synvert/core/rewriter.rb', line 241

def if_gem(name, version)
  @gem_spec = Rewriter::GemSpec.new(name, version)
end

#if_ruby(version) ⇒ Object

It checks if ruby version is greater than or equal to the specified ruby version.

Examples:

Synvert::Rewriter.new 'ruby', 'new_safe_navigation_operator' do
  if_ruby '2.3.0'
end

Parameters:

  • version (String)

    specified ruby version.



230
231
232
# File 'lib/synvert/core/rewriter.rb', line 230

def if_ruby(version)
  @ruby_version = Rewriter::RubyVersion.new(version)
end

#parserObject



180
181
182
# File 'lib/synvert/core/rewriter.rb', line 180

def parser
  @options[:parser]
end

#processObject

Process the rewriter. It will call the block.



126
127
128
129
# File 'lib/synvert/core/rewriter.rb', line 126

def process
  @affected_files = Set.new
  instance_eval(&@block)
end

#process_with_sandboxObject

Process rewriter with sandbox mode. It will call the block but doesn't change any file.



133
134
135
136
# File 'lib/synvert/core/rewriter.rb', line 133

def process_with_sandbox
  @options[:run_instance] = false
  process
end

#remove_file(filename) ⇒ Object

It removes a file.

Examples:

Synvert::Rewriter.new 'rails', 'upgrade_4_0_to_4_1' do
  remove_file 'config/initializers/secret_token.rb'
end

Parameters:

  • filename (String)

    file name.



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/synvert/core/rewriter.rb', line 320

def remove_file(filename)
  return unless @options[:run_instance]

  unless @options[:write_to_file]
    result = NodeMutation::Result.new(affected: true, conflicted: false)
    if Configuration.test_result == 'new_source'
      result.new_source = nil
    else
      result.actions = [NodeMutation::Struct::Action.new(:remove_file, 0, -1)]
    end
    result.file_path = filename
    merge_test_result(result)
    return
  end

  file_path = File.join(Configuration.root_path, filename)
  File.delete(file_path) if File.exist?(file_path)
end

#resetObject

Reset @warnings, @affected_files, and @test_results.



185
186
187
188
189
# File 'lib/synvert/core/rewriter.rb', line 185

def reset
  @warnings = []
  @affected_files = Set.new
  @test_results = Hash.new { |h, k| h[k] = [] }
end

#testObject



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/synvert/core/rewriter.rb', line 138

def test
  @options[:write_to_file] = false
  @affected_files = Set.new
  instance_eval(&@block)

  if Configuration.test_result == 'new_source'
    @test_results.values.flatten
  else
    @test_results.map do |filename, test_results|
      new_actions = test_results.map(&:actions).flatten.sort_by(&:end)
      last_start = -1
      conflicted =
        new_actions.any? do |action|
          if last_start > action.end
            true
          else
            last_start = action.start
            false
          end
        end
      result = NodeMutation::Result.new(affected: true, conflicted: conflicted)
      result.actions = new_actions
      result.file_path = filename
      result
    end
  end
end

#with_configurations(configurations) { ... } ⇒ Object

Executes a block of code with temporary configurations.

Parameters:

  • configurations (Hash)

    The temporary configurations to apply.

Yields:

  • The block of code to execute.



415
416
417
# File 'lib/synvert/core/rewriter.rb', line 415

def with_configurations(configurations, &block)
  Configuration.with_temporary_configurations(configurations, &block)
end

#within_files(file_patterns, &block) ⇒ Object Also known as: within_file

It finds specified files, and for each file, it will delegate to Instance to rewrite code. It creates a Instance to rewrite code.

Examples:

Synvert::Rewriter.new 'rspec', 'be_close_to_be_within' do
  within_files '**/*.rb' do
  end
end

Parameters:

  • file_patterns (String|Array<String>)

    string pattern or list of string pattern to find files, e.g. ['spec/*/_spec.rb']

  • block (Block)

    the block to rewrite code in the matching files.



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/synvert/core/rewriter.rb', line 254

def within_files(file_patterns, &block)
  return unless @options[:run_instance]

  return if @ruby_version && !@ruby_version.match?
  return if @gem_spec && !@gem_spec.match?

  if @options[:write_to_file]
    handle_one_file(Array(file_patterns)) do |file_path|
      instance = Instance.new(self, file_path, &block)
      instance.process
    end
  else
    results =
      handle_one_file(Array(file_patterns)) do |file_path|
        instance = Instance.new(self, file_path, &block)
        instance.test
      end
    merge_test_results(results)
  end
end