Class: WebTranslateIt::CommandLine

Inherits:
Object
  • Object
show all
Defined in:
lib/web_translate_it/command_line.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, command_options, global_options, parameters, project_path) ⇒ CommandLine



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/web_translate_it/command_line.rb', line 8

def initialize(command, command_options, global_options, parameters, project_path)
  self.command_options = command_options
  self.parameters = parameters
  unless command == 'init'
    case command
    when 'pull'
      message = "Pulling files"
    when 'push'
      message = "Pushing files"
    when 'add'
      message = "Creating master files"
    when 'rm'
      message = "Deleting files"
    when 'addlocale'
      message = "Adding locale"
    when 'rmlocale'
      message = "Deleting locale"
    else
      message = "Gathering information"
    end
    throb { print "  #{message}"; self.configuration = WebTranslateIt::Configuration.new(project_path, configuration_file_path); print " #{message} on #{self.configuration.project_name}"; }
  end
  self.send(command)
end

Instance Attribute Details

#command_optionsObject

Returns the value of attribute command_options.



6
7
8
# File 'lib/web_translate_it/command_line.rb', line 6

def command_options
  @command_options
end

#configurationObject

Returns the value of attribute configuration.



6
7
8
# File 'lib/web_translate_it/command_line.rb', line 6

def configuration
  @configuration
end

#global_optionsObject

Returns the value of attribute global_options.



6
7
8
# File 'lib/web_translate_it/command_line.rb', line 6

def global_options
  @global_options
end

#parametersObject

Returns the value of attribute parameters.



6
7
8
# File 'lib/web_translate_it/command_line.rb', line 6

def parameters
  @parameters
end

Instance Method Details

#addObject



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/web_translate_it/command_line.rb', line 88

def add
  STDOUT.sync = true
  if parameters == []
    puts StringUtil.failure("Error: You must provide the path to the master file to add.")
    puts "Usage: wti add path/to/master_file_1 path/to/master_file_2 ..."
    exit
  end
  WebTranslateIt::Connection.new(configuration.api_key) do |http|
   added = configuration.files.find_all{ |file| file.locale == configuration.source_locale}.collect {|file| File.expand_path(file.file_path) }.to_set
    to_add = parameters.reject{ |param| added.include?(File.expand_path(param))}
    if to_add.any?
      to_add.each do |param|
        file = TranslationFile.new(nil, param, nil, configuration.api_key)
        file.create(http, command_options.low_priority)
      end
    else
      puts "No new master file to add."
    end
  end
end

#addlocaleObject



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/web_translate_it/command_line.rb', line 133

def addlocale
  STDOUT.sync = true
  if parameters == []
    puts StringUtil.failure("Locale code missing.")
    puts "Usage: wti addlocale fr es ..."
    exit
  end
  parameters.each do |param|
    print StringUtil.success("Adding locale #{param.upcase}... ")
    WebTranslateIt::Connection.new(configuration.api_key) do
      puts WebTranslateIt::Project.create_locale(param)
    end
    puts "Done."
  end
end

#configuration_file_pathObject



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/web_translate_it/command_line.rb', line 265

def configuration_file_path
  if self.command_options.config
    return self.command_options.config
  else
    if File.exists?('config/translation.yml')
      puts "Warning: `config/translation.yml` is deprecated in favour of a `.wti` file."
      if Util.ask_yes_no("Would you like to migrate your configuration now?", true)
        require 'fileutils'
        if FileUtils.mv('config/translation.yml', '.wti')
          return '.wti'
        else
          puts "Couldn’t move `config/translation.yml`."
          return false
        end
      else
        return 'config/translation.yml'
      end
    else
      return '.wti'
    end
  end
end

#fetch_locales_to_pullObject



238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/web_translate_it/command_line.rb', line 238

def fetch_locales_to_pull
  if command_options.locale
    command_options.locale.split.each do |locale|
      puts "Locale #{locale} doesn't exist -- `wti addlocale #{locale}` to add it." unless configuration.target_locales.include?(locale)
    end
    locales = command_options.locale.split
  else
    locales = configuration.target_locales
    configuration.ignore_locales.each{ |locale_to_delete| locales.delete(locale_to_delete) }
  end
  locales.push(configuration.source_locale) if command_options.all
  return locales.uniq
end

#fetch_locales_to_push(configuration) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/web_translate_it/command_line.rb', line 252

def fetch_locales_to_push(configuration)
  if command_options.locale
    command_options.locale.split.each do |locale|
      puts "Locale #{locale} doesn't exist -- `wti addlocale #{locale}` to add it." unless configuration.target_locales.include?(locale)
    end
    locales = command_options.locale.split
  else
    locales = [configuration.source_locale]
  end
  locales += configuration.target_locales if command_options.all
  return locales.uniq
end

#generate_configuration(api_key, project_info) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/web_translate_it/command_line.rb', line 288

def generate_configuration(api_key, project_info)
  file = "api_key: \#{api_key}\n\n# Optional: locales not to sync with Web Translate It.\n# Takes a string, a symbol, or an array of string or symbol.\n# More information here: https://github.com/AtelierConvivialite/webtranslateit/wiki\n# ignore_locales: '\#{project_info[\"source_locale\"][\"code\"]}'\n\n# Optional\n# before_pull: \"echo 'some unix command'\"   # Command executed before pulling files\n# after_pull:  \"touch tmp/restart.txt\"      # Command executed after pulling files\n#\n# before_push: \"echo 'some unix command'\"   # Command executed before pushing files\n# after_push:  \"touch tmp/restart.txt\"      # Command executed after pushing files\n\n"
  return file
end

#initObject



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/web_translate_it/command_line.rb', line 167

def init
  puts "# Initializing project"
  if parameters.any?
    api_key = parameters[0]
    path = '.wti'
  else
    api_key = Util.ask(" Project API Key:")
    path = Util.ask(" Path to configuration file:", '.wti')
  end
  FileUtils.mkpath(path.split('/')[0..path.split('/').size-2].join('/')) unless path.split('/').size == 1
  project = YAML.load WebTranslateIt::Project.fetch_info(api_key)
  project_info = project['project']
  if File.exists?(path) && !File.writable?(path)
    puts StringUtil.failure("Error: `#{path}` file is not writable.")
    exit
  end
  File.open(path, 'w'){ |file| file << generate_configuration(api_key, project_info) }
  puts ""
  puts " The project #{project_info['name']} was successfully initialized."
  puts ""
  if project_info["source_locale"]["code"].nil? || project_info["target_locales"].size <= 1 || project_info["project_files"].none?
    puts ""
    puts " There are a few more things to set up:"
    puts ""
  end
  if project_info["source_locale"]["code"].nil?
    puts " *) You don't have a source locale setup."
    puts "    Add the source locale with: `wti addlocale <locale_code>`"
    puts ""
  end
  if project_info["target_locales"].size <= 1
    puts " *) You don't have a target locale setup."
    puts "    Add the first target locale with: `wti addlocale <locale_code>`"
    puts ""
  end
  if project_info["project_files"].none?
    puts " *) You don't have linguistic files setup."
    puts "    Add a master file with: `wti add <path/to/file.xml>`"
    puts ""
  end
  puts "You can now use `wti` to push and pull your language files."
  puts "Check `wti --help` for help."
end

#matchObject



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/web_translate_it/command_line.rb', line 211

def match
  configuration.files.find_all{ |mf| mf.locale == configuration.source_locale }.each do |master_file|
    if !File.exists?(master_file.file_path)
      puts StringUtil.failure(master_file.file_path) + " (#{master_file.locale})"
    else
      puts StringUtil.important(master_file.file_path) + " (#{master_file.locale})"
    end
    configuration.files.find_all{ |f| f.master_id == master_file.id }.each do |file|
      if !File.exists?(file.file_path)
        puts StringUtil.failure("- #{file.file_path}") + " (#{file.locale})"
      else
        puts "- #{file.file_path}" + " (#{file.locale})"
      end
    end
  end
end

#pullObject



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
# File 'lib/web_translate_it/command_line.rb', line 33

def pull
  STDOUT.sync = true
  `#{configuration.before_pull}` if configuration.before_pull
  # Selecting files to pull
  files = []
  fetch_locales_to_pull.each do |locale|
    files.concat configuration.files.find_all{ |file| file.locale == locale }
  end
  if files.size == 0
    puts "No files to pull."
  else
    # Now actually pulling files
    time = Time.now
    threads = []
    n_threads = (files.size.to_f/3).ceil >= 10 ? 10 : (files.size.to_f/3).ceil
    ArrayUtil.chunk(files, n_threads).each do |file_array|
      unless file_array.empty?
        threads << Thread.new(file_array) do |file_array|
          WebTranslateIt::Connection.new(configuration.api_key) do |http|
            file_array.each do |file|
              file.fetch(http, command_options.force)
            end
          end
        end
      end
    end
    threads.each { |thread| thread.join }
    time = Time.now - time
    puts "Pulled #{files.size} files at #{(files.size/time).round} files/sec, using #{n_threads} threads."
    `#{configuration.after_pull}` if configuration.after_pull
  end
end

#pushObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/web_translate_it/command_line.rb', line 66

def push
  STDOUT.sync = true
  `#{configuration.before_push}` if configuration.before_push
  WebTranslateIt::Connection.new(configuration.api_key) do |http|
    fetch_locales_to_push(configuration).each do |locale|
      if parameters.any?
        files = configuration.files.find_all{ |file| parameters.include?(file.file_path) }.sort{|a,b| a.file_path <=> b.file_path}
      else
        files = configuration.files.find_all{ |file| file.locale == locale }.sort{|a,b| a.file_path <=> b.file_path}
      end
      if files.size == 0
        puts "No files to push."
      else
        files.each do |file|
          file.upload(http, command_options[:merge], command_options.ignore_missing, command_options.label, command_options.low_priority, command_options[:minor], command_options.force)
        end
      end
    end
  end
  `#{configuration.after_push}` if configuration.after_push
end

#rmObject



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/web_translate_it/command_line.rb', line 109

def rm
  STDOUT.sync = true
  if parameters == []
    puts StringUtil.failure("Error: You must provide the path to the master file to remove.")
    puts "Usage: wti path/to/rm master_file_1 path/to/master_file_2 ..."
    exit
  end
  WebTranslateIt::Connection.new(configuration.api_key) do |http|
    parameters.each do |param|
      if Util.ask_yes_no("Are you sure you want to delete the master file #{param}?\nThis will also delete its target files and translations.", false)
        configuration.files.find_all{ |file| file.file_path == param }.each do |master_file|
          master_file.delete(http)
          # delete files
          File.delete(master_file.file_path) if File.exists?(master_file.file_path)
          configuration.files.find_all{ |file| file.master_id == master_file.id }.each do |target_file|
            File.delete(target_file.file_path) if File.exists?(target_file.file_path)
          end
        end
      end
    end
  end
  puts StringUtil.success("Master file deleted.")
end

#rmlocaleObject



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/web_translate_it/command_line.rb', line 149

def rmlocale
  STDOUT.sync = true
  if parameters == []
    puts StringUtil.failure("Error: You must provide the locale code to remove.")
    puts "Usage: wti rmlocale fr es ..."
    exit
  end
  parameters.each do |param|
    if Util.ask_yes_no("Are you certain you want to delete the locale #{param.upcase}?\nThis will also delete its files and translations.", false)
      print StringUtil.success("Deleting locale #{param.upcase}... ")
      WebTranslateIt::Connection.new(configuration.api_key) do |http|
        puts WebTranslateIt::Project.delete_locale(param)
      end
      puts "Done."
    end
  end
end

#statusObject



228
229
230
231
232
233
234
235
236
# File 'lib/web_translate_it/command_line.rb', line 228

def status
  stats = YAML.load(Project.fetch_stats(configuration.api_key))
  stale = false
  stats.each do |locale, values|
    percent_translated = Util.calculate_percentage(values['count_strings_to_proofread'].to_i + values['count_strings_done'].to_i + values['count_strings_to_verify'].to_i, values['count_strings'].to_i)
    percent_completed  = Util.calculate_percentage(values['count_strings_done'].to_i, values['count_strings'].to_i)
    puts "#{locale}: #{percent_translated}% translated, #{percent_completed}% completed."
  end
end

#throbObject



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/web_translate_it/command_line.rb', line 308

def throb
throb = %w(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
throb.reverse! if rand > 0.5
i = rand throb.length

thread = Thread.new do
  dot = lambda do
    print "\r#{throb[i]}\e[?25l"
    i = (i + 1) % throb.length
    sleep 0.1 and dot.call
  end
  dot.call
end
yield
ensure
  if thread
    thread.kill
    puts "\r\e[0G#\e[?25h"
  end
end