Sha256: e978ca6b52103aa8ee6cb3753a5fd8b8c326a6bc77efe60f968ecf9ccfb504b7

Contents?: true

Size: 1.76 KB

Versions: 4

Compression:

Stored size: 1.76 KB

Contents

# frozen_string_literal: true

require 'fileutils'
require_relative 'test_code_generator'

module Dotcodegen
  class TestFileGenerator
    attr_reader :file_path, :matchers, :openai_key

    def initialize(file_path:, matchers:, openai_key:)
      @file_path = file_path
      @matchers = matchers
      @openai_key = openai_key
    end

    def run
      puts "Finding matcher for #{file_path}..."
      return puts "No matcher found for #{file_path}" unless matcher

      puts "Test file path: #{test_file_path}"
      ensure_test_file_presence

      write_generated_code_to_test_file
      open_test_file_in_editor unless $running_tests

      puts 'Running codegen...'
    end

    def ensure_test_file_presence
      puts "Creating test file if it doesn't exist..."
      return if File.exist?(test_file_path)

      FileUtils.mkdir_p(File.dirname(test_file_path))
      File.write(test_file_path, '')
    end

    def write_generated_code_to_test_file
      generated_code = Dotcodegen::TestCodeGenerator.new(config: matcher, file_to_test_path: file_path,
                                                         openai_key:).generate_test_code
      File.write(test_file_path, generated_code)
    end

    def open_test_file_in_editor
      system("code #{test_file_path}")
    end

    def matcher
      @matcher ||= matchers.find { |m| file_path.match?(m['regex']) }
    end

    def test_file_path
      @test_file_path ||= "#{test_root_path}#{relative_file_name}#{test_file_suffix}"
    end

    def relative_file_name
      file_path.sub(root_path, '').sub(/\.\w+$/, '')
    end

    def test_root_path
      matcher['test_root_path'] || ''
    end

    def root_path
      matcher['root_path'] || ''
    end

    def test_file_suffix
      matcher['test_file_suffix'] || ''
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dotcodegen-0.1.4 lib/dotcodegen/test_file_generator.rb
dotcodegen-0.1.3 lib/dotcodegen/test_file_generator.rb
dotcodegen-0.1.1 lib/dotcodegen/test_file_generator.rb
dotcodegen-0.1.0 lib/dotcodegen/test_file_generator.rb