Module: WordSmith::CommandRunner

Extended by:
T::Sig
Defined in:
lib/command_runner/index.rb,
lib/command_runner/translation.rb

Defined Under Namespace

Modules: Translation Classes: ArgumentError, BadPermutationOfArgumentsError, Options

Constant Summary collapse

EXECUTABLE_NAME =
'ws'
OPENAI_API_KEY_COMMAND =
'--set-openai-api-key'
OPENAI_ORG_ID_COMMAND =
'--set-openai-org-id'

Class Method Summary collapse

Class Method Details

.run(args) ⇒ Object

Raises:



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/command_runner/index.rb', line 30

def run(args)
  args_clone = args.clone
  options = Options.new(no_cache: false, file_path: nil, target_language: nil)

  parser = OptionParser.new do |opts|
    opts.banner = "Usage: #{EXECUTABLE_NAME} [word] [options...]"

    opts.on('-f', '--file [FILE_PATH]', 'Read words from a file') do |file_path|
      options.file_path = file_path
    end

    opts.on('--target-language [LANGUAGE_CODE]',
            'If you want to translate the word to a specific language, specify the language. e.g: Spanish') do |target_language|
      options.target_language = target_language
    end

    opts.on("#{OPENAI_API_KEY_COMMAND} [key]", 'Set the OpenAI API key') do |key|
      store_open_a_i_api_key(key)

      exit
    end

    opts.on("#{OPENAI_ORG_ID_COMMAND} [key]", 'Set the OpenAI Org ID') do |key|
      store_open_a_i_org_id(key)

      exit
    end

    opts.on('--no-cache', 'Translate word without using cache') do
      options.no_cache = true
    end

    opts.on_tail('-h', '--help', 'Show help') do
      print_help(opts)

      exit
    end

    opts.on_tail('-v', '--version', 'Show version') do
      print_version

      exit
    end
  end

  parser.parse!(args_clone)

  input_text = args_clone.join(' ').chomp

  if !input_text.empty? && !options.file_path.nil?
    raise BadPermutationOfArgumentsError, 'Both word and file path cannot be provided'
  end

  raise ArgumentError, 'No word or file path provided' if input_text.empty? && options.file_path.nil?

  translation_options = {
    no_cache: options.no_cache,
    target_language: options.target_language
  }

  unless options.file_path.nil?
    raise ArgumentError, "File not found: #{options.file_path}" unless File.exist?(options.file_path)

    File.readlines(T.must(options.file_path)).each_with_index do |line, index|
      puts Rainbow('-' * 60).yellow.bright unless index.zero?

      Translation.run(line, translation_options)
    end

    return
  end

  Translation.run(input_text, translation_options)
end