Class: NHKore::App
- Inherits:
-
Object
- Object
- NHKore::App
- Includes:
- CLI::FXCmd, CLI::GetCmd, CLI::NewsCmd, CLI::SearchCmd, CLI::SiftCmd
- Defined in:
- lib/nhkore/app.rb
Overview
Constant Summary collapse
- NAME =
'nhkore'- DEFAULT_SLEEP_TIME =
So that sites don’t ban us (i.e., think we are human)
0.1
- COLOR_OPTS =
i[c color].freeze
- NO_COLOR_OPTS =
i[C no-color].freeze
- SPINNER_MSG =
'[:spinner] :title:detail...'- CLASSIC_SPINNER =
TTY::Spinner.new(SPINNER_MSG,format: :classic)
- DEFAULT_SPINNER =
TTY::Spinner.new(SPINNER_MSG,interval: 5, frames: ['〜〜〜','日〜〜','日本〜','日本語'])
- NO_SPINNER_MSG =
'%{title}%{detail}...'
Constants included from CLI::SiftCmd
CLI::SiftCmd::DEFAULT_SIFT_EXT, CLI::SiftCmd::DEFAULT_SIFT_FUTSUU_FILE, CLI::SiftCmd::DEFAULT_SIFT_YASASHII_FILE, CLI::SiftCmd::SIFT_EXTS
Constants included from CLI::NewsCmd
CLI::NewsCmd::DEFAULT_NEWS_SCRAPE
Constants included from CLI::GetCmd
CLI::GetCmd::DEFAULT_GET_CHUNK_SIZE, CLI::GetCmd::DEFAULT_GET_URL_LENGTH, CLI::GetCmd::GET_URL, CLI::GetCmd::GET_URL_FILENAME
Instance Attribute Summary collapse
- #cmd ⇒ Object readonly
- #cmd_args ⇒ Object readonly
- #cmd_opts ⇒ Object readonly
- #progress_bar ⇒ Object
- #scraper_kargs ⇒ Object
- #sleep_time ⇒ Object
- #spinner ⇒ Object
Attributes included from CLI::SiftCmd
#sift_datetime_text, #sift_search_criteria
Instance Method Summary collapse
- #autodetect_color ⇒ Object
- #build_app_cmd ⇒ Object
- #build_dir(opt_key, default_dir: '.') ⇒ Object
- #build_file(opt_key, default_dir: '.', default_filename: '') ⇒ Object
- #build_in_dir(opt_key, **kargs) ⇒ Object
- #build_in_file(opt_key, **kargs) ⇒ Object
- #build_out_dir(opt_key, **kargs) ⇒ Object
- #build_out_file(opt_key, **kargs) ⇒ Object
- #build_progress_bar(title, download: false, total: 100, type: @progress_bar, width: 33, **kargs) ⇒ Object
- #build_version_cmd ⇒ Object
- #check_empty_opt(key, value) ⇒ Object
- #check_in_file(opt_key, empty_ok: false) ⇒ Object
- #check_out_dir(opt_key) ⇒ Object
- #check_out_file(opt_key) ⇒ Object
- #color(str) ⇒ Object
- #color_alias(str) ⇒ Object
- #enable_color(enabled) ⇒ Object
-
#initialize(args = ARGV) ⇒ App
constructor
A new instance of App.
- #opts_to_set(ary) ⇒ Object
- #refresh_cmd(opts, args, cmd) ⇒ Object
- #run ⇒ Object
- #show_version ⇒ Object
- #sleep_scraper ⇒ Object
- #start_spin(title, detail: '') ⇒ Object
- #stop_spin ⇒ Object
- #update_spin_detail(detail) ⇒ Object
Methods included from CLI::SiftCmd
#build_sift_cmd, #build_sift_filename, #run_sift_cmd
Methods included from CLI::SearchCmd
#build_search_cmd, #run_search_cmd, #run_search_help, #show_search_urls
Methods included from CLI::NewsCmd
#build_news_cmd, #run_news_cmd, #scrape_news_article, #scraped_news_article?
Methods included from CLI::GetCmd
Methods included from CLI::FXCmd
#build_fx_cmd, #run_fx_cmd, #test_fx_progress_bar, #test_fx_spinner
Constructor Details
#initialize(args = ARGV) ⇒ App
Returns a new instance of App.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/nhkore/app.rb', line 87 def initialize(args=ARGV) super() @args = args @cmd = nil @cmd_args = nil @cmd_opts = nil @high = HighLine.new @rainbow = Rainbow.new = :default # [:default, :classic, :no] @scraper_kargs = {} @sleep_time = DEFAULT_SLEEP_TIME @spinner = DEFAULT_SPINNER autodetect_color build_app_cmd build_fx_cmd build_get_cmd build_news_cmd build_search_cmd build_sift_cmd build_version_cmd @app_cmd.add_command Cri::Command.new_basic_help end |
Instance Attribute Details
#cmd ⇒ Object (readonly)
79 80 81 |
# File 'lib/nhkore/app.rb', line 79 def cmd @cmd end |
#cmd_args ⇒ Object (readonly)
80 81 82 |
# File 'lib/nhkore/app.rb', line 80 def cmd_args @cmd_args end |
#cmd_opts ⇒ Object (readonly)
81 82 83 |
# File 'lib/nhkore/app.rb', line 81 def cmd_opts @cmd_opts end |
#progress_bar ⇒ Object
82 83 84 |
# File 'lib/nhkore/app.rb', line 82 def end |
#scraper_kargs ⇒ Object
83 84 85 |
# File 'lib/nhkore/app.rb', line 83 def scraper_kargs @scraper_kargs end |
#sleep_time ⇒ Object
84 85 86 |
# File 'lib/nhkore/app.rb', line 84 def sleep_time @sleep_time end |
#spinner ⇒ Object
85 86 87 |
# File 'lib/nhkore/app.rb', line 85 def spinner @spinner end |
Instance Method Details
#autodetect_color ⇒ Object
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
# File 'lib/nhkore/app.rb', line 115 def autodetect_color Cri::Platform.singleton_class.prepend(CriColorExt) color = nil # Must be nil, not true/false if !@args.empty? # Kind of hacky, but necessary for Rainbow. color_opts = opts_to_set(COLOR_OPTS) no_color_opts = opts_to_set(NO_COLOR_OPTS) @args.each do |arg| if color_opts.include?(arg) color = true break end if no_color_opts.include?(arg) color = false break end break if arg == '--' end end if color.nil? # - https://no-color.org/ color = ($stdout.tty? && ENV['TERM'] != 'dumb' && !ENV.key?('NO_COLOR')) end enable_color(color) end |
#build_app_cmd ⇒ Object
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
# File 'lib/nhkore/app.rb', line 149 def build_app_cmd app = self @app_cmd = Cri::Command.define do name NAME usage "#{NAME} [OPTIONS] [COMMAND]..." summary 'NHK News Web (Easy) scraper for Japanese language learners.' description " Scrapes NHK News Web (Easy) to create a list of each word and its\n frequency (how many times it was used) for Japanese language learners.\n\n This is similar to a core word/vocabulary list.\n DESC\n\n flag :s,:'classic-fx',<<-DESC do |value,cmd|\n use classic spinner/progress special effects (in case of no Unicode support) when running long tasks\n DESC\n app.progress_bar = :classic\n app.spinner = CLASSIC_SPINNER\n end\n flag COLOR_OPTS[0],COLOR_OPTS[1],\"force color output (for commands like '| less -R')\" do |value,cmd|\n app.enable_color(true)\n end\n flag :n,:'dry-run',<<-DESC\n do a dry run without making changes; do not write to files, create directories, etc.\n DESC\n # Big F because dangerous.\n flag :F,:force,\"force overwriting files, creating directories, etc. (don't prompt); dangerous!\"\n flag :h,:help,'show this help' do |value,cmd|\n puts cmd.help\n exit\n end\n option :m,:'max-retry',<<-DESC,argument: :required,default: 3 do |value,cmd|\n maximum number of times to retry URLs (-1 or integer >= 0)\n DESC\n value = value.to_i\n value = nil if value < 0\n\n app.scraper_kargs[:max_retries] = value\n end\n flag NO_COLOR_OPTS[0],NO_COLOR_OPTS[1],'disable color output' do |value,cmd|\n app.enable_color(false)\n end\n flag :X,:'no-fx','disable spinner/progress special effects when running long tasks' do |value,cmd|\n app.progress_bar = :no\n app.spinner = {} # Still outputs status & stores tokens\n end\n option :o,:'open-timeout',<<-DESC,argument: :required do |value,cmd|\n seconds for URL open timeouts (-1 or decimal >= 0)\n DESC\n value = value.to_f\n value = nil if value < 0.0\n\n app.scraper_kargs[:open_timeout] = value\n end\n option :r,:'read-timeout',<<-DESC,argument: :required do |value,cmd|\n seconds for URL read timeouts (-1 or decimal >= 0)\n DESC\n value = value.to_f\n value = nil if value < 0.0\n\n app.scraper_kargs[:read_timeout] = value\n end\n option :z,:sleep,<<-DESC,argument: :required,default: DEFAULT_SLEEP_TIME do |value,cmd|\n seconds to sleep per scrape (i.e., per page/article) so don't get banned (i.e., fake being human)\n DESC\n app.sleep_time = value.to_f\n app.sleep_time = 0.0 if app.sleep_time < 0.0\n end\n option :t,:timeout,<<-DESC,argument: :required do |value,cmd|\n seconds for all URL timeouts: [open, read] (-1 or decimal >= 0)\n DESC\n value = value.to_f\n value = nil if value < 0.0\n\n app.scraper_kargs[:open_timeout] = value\n app.scraper_kargs[:read_timeout] = value\n end\n option :u,:'user-agent',<<-DESC,argument: :required do |value,cmd|\n HTTP header field 'User-Agent' to use instead of a random one\n DESC\n value = app.check_empty_opt(:'user-agent',value)\n\n app.scraper_kargs[:header] ||= {}\n app.scraper_kargs[:header]['user-agent'] = value\n end\n flag :v,:version,'show the version and exit' do |value,cmd|\n app.show_version\n exit\n end\n\n run do |opts,args,cmd|\n puts cmd.help\n end\n end\nend\n" |
#build_dir(opt_key, default_dir: '.') ⇒ Object
247 248 249 250 251 252 253 254 255 256 257 258 |
# File 'lib/nhkore/app.rb', line 247 def build_dir(opt_key,default_dir: '.') # Protect against fat-fingering. default_dir = Util.strip_web_str(default_dir) dir = Util.strip_web_str(@cmd_opts[opt_key].to_s) dir = default_dir if dir.empty? # '~' will expand to home, etc. dir = File.(dir) unless dir.nil? return (@cmd_opts[opt_key] = dir) end |
#build_file(opt_key, default_dir: '.', default_filename: '') ⇒ Object
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
# File 'lib/nhkore/app.rb', line 260 def build_file(opt_key,default_dir: '.',default_filename: '') # Protect against fat-fingering. default_dir = Util.strip_web_str(default_dir) default_filename = Util.strip_web_str(default_filename) file = Util.strip_web_str(@cmd_opts[opt_key].to_s) if file.empty? # Do not check default_dir.empty?(). if default_filename.empty? file = nil # nil is very important for BingScraper.init()! else file = File.join(default_dir,default_filename) end else # Directory? if File.directory?(file) || Util.dir_str?(file) file = File.join(file,default_filename) # File name only? (no directory) elsif Util.filename_str?(file) file = File.join(default_dir,file) end # Else, passed in both: 'directory/file' end # '~' will expand to home, etc. file = File.(file) unless file.nil? return (@cmd_opts[opt_key] = file) end |
#build_in_dir(opt_key, **kargs) ⇒ Object
290 291 292 |
# File 'lib/nhkore/app.rb', line 290 def build_in_dir(opt_key,**kargs) return build_dir(opt_key,**kargs) end |
#build_in_file(opt_key, **kargs) ⇒ Object
294 295 296 |
# File 'lib/nhkore/app.rb', line 294 def build_in_file(opt_key,**kargs) return build_file(opt_key,**kargs) end |
#build_out_dir(opt_key, **kargs) ⇒ Object
298 299 300 |
# File 'lib/nhkore/app.rb', line 298 def build_out_dir(opt_key,**kargs) return build_dir(opt_key,**kargs) end |
#build_out_file(opt_key, **kargs) ⇒ Object
302 303 304 |
# File 'lib/nhkore/app.rb', line 302 def build_out_file(opt_key,**kargs) return build_file(opt_key,**kargs) end |
#build_progress_bar(title, download: false, total: 100, type: @progress_bar, width: 33, **kargs) ⇒ Object
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/nhkore/app.rb', line 306 def (title,download: false,total: 100,type: ,width: 33,**kargs) case type when :default,:classic require 'tty-progressbar' msg = "#{title} [:bar] :percent :eta".dup msg << ' :byte_rate/s' if download return TTY::ProgressBar.new(msg,total: total,width: width,**kargs) do |config| if type == :default config.incomplete = '.' config.complete = '/' config.head = 'o' end #config.frequency = 5 # For a big download, set this config.interval = 1 if download end end # :no return NoProgressBar.new(title,total: total,**kargs) end |
#build_version_cmd ⇒ Object
330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
# File 'lib/nhkore/app.rb', line 330 def build_version_cmd app = self @version_cmd = @app_cmd.define_command do name 'version' usage 'version [OPTIONS] [COMMAND]...' aliases :v summary "Show the version and exit (aliases: #{app.color_alias('v')})" run do |opts,args,cmd| app.show_version end end end |
#check_empty_opt(key, value) ⇒ Object
345 346 347 348 349 350 351 352 353 |
# File 'lib/nhkore/app.rb', line 345 def check_empty_opt(key,value) value = Util.strip_web_str(value) unless value.nil? if value.nil? || value.empty? raise CLIError,"option[#{key}] cannot be empty[#{value}]" end return value end |
#check_in_file(opt_key, empty_ok: false) ⇒ Object
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
# File 'lib/nhkore/app.rb', line 355 def check_in_file(opt_key,empty_ok: false) in_file = @cmd_opts[opt_key] if Util.empty_web_str?(in_file) if !empty_ok raise CLIError,"empty input path name[#{in_file}] in option[#{opt_key}]" end @cmd_opts[opt_key] = nil # nil is very important for BingScraper.init()! return true end in_file = Util.strip_web_str(in_file) if !File.exist?(in_file) raise CLIError,"input file[#{in_file}] does not exist for option[#{opt_key}]" end if File.directory?(in_file) raise CLIError,"input file[#{in_file}] cannot be a directory for option[#{opt_key}]" end return true end |
#check_out_dir(opt_key) ⇒ Object
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
# File 'lib/nhkore/app.rb', line 381 def check_out_dir(opt_key) out_dir = @cmd_opts[opt_key] if Util.empty_web_str?(out_dir) raise CLIError,"empty output directory[#{out_dir}] in option[#{opt_key}]" end out_dir = Util.strip_web_str(out_dir) if File.file?(out_dir) raise CLIError,"output directory[#{out_dir}] cannot be a file for option[#{opt_key}]" end if @cmd_opts[:dry_run] puts 'No changes written (dry run).' puts "> #{out_dir}" puts return true end force = @cmd_opts[:force] if !force && Dir.exist?(out_dir) && !Dir.empty?(out_dir) puts 'Warning: output directory already exists with files!' puts ' : Files inside of this directory may be overwritten!' puts "> '#{out_dir}'" return false unless @high.agree('Is this okay (yes/no)? ') puts end if !Dir.exist?(out_dir) if !force puts 'Output directory does not exist.' puts "> '#{out_dir}'" return false unless @high.agree('Create this directory (yes/no)? ') end FileUtils.mkdir_p(out_dir,verbose: true) puts end return true end |
#check_out_file(opt_key) ⇒ Object
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
# File 'lib/nhkore/app.rb', line 428 def check_out_file(opt_key) out_file = @cmd_opts[opt_key] if Util.empty_web_str?(out_file) raise CLIError,"empty output path name[#{out_file}] in option[#{opt_key}]" end out_file = Util.strip_web_str(out_file) if File.directory?(out_file) raise CLIError,"output file[#{out_file}] cannot be a directory for option[#{opt_key}]" end if @cmd_opts[:dry_run] puts 'No changes written (dry run).' puts "> #{out_file}" puts return true end force = @cmd_opts[:force] out_dir = File.dirname(out_file) if !force && File.exist?(out_file) puts 'Warning: output file already exists!' puts "> '#{out_file}'" return false unless @high.agree('Overwrite this file (yes/no)? ') puts end if !Dir.exist?(out_dir) if !force puts 'Output directory does not exist.' puts "> '#{out_dir}'" return false unless @high.agree('Create this directory (yes/no)? ') end FileUtils.mkdir_p(out_dir,verbose: true) puts end return true end |
#color(str) ⇒ Object
475 476 477 |
# File 'lib/nhkore/app.rb', line 475 def color(str) return @rainbow.wrap(str) end |
#color_alias(str) ⇒ Object
479 480 481 |
# File 'lib/nhkore/app.rb', line 479 def color_alias(str) return color(str).green end |
#enable_color(enabled) ⇒ Object
483 484 485 486 |
# File 'lib/nhkore/app.rb', line 483 def enable_color(enabled) Cri::Platform.color = enabled @rainbow.enabled = enabled end |
#opts_to_set(ary) ⇒ Object
488 489 490 491 492 493 494 495 |
# File 'lib/nhkore/app.rb', line 488 def opts_to_set(ary) set = Set.new set.add("-#{ary[0]}") unless ary[0].nil? set.add("--#{ary[1]}") unless ary[1].nil? return set end |
#refresh_cmd(opts, args, cmd) ⇒ Object
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 |
# File 'lib/nhkore/app.rb', line 497 def refresh_cmd(opts,args,cmd) new_opts = {} # Change symbols with dashes to underscores, # so don't have to type @cmd_opts[:'dry-run'] all the time. opts.each do |key,value| # %s(max-retry) => :max_retry key = key.to_s.gsub('-','_').to_sym new_opts[key] = value end # For now don't set the default proc, as the original code # did not have this in mind. # Specifically, SiftCmd.build_sift_filename() is affected by # this due to relying on @cmd_opts[:ext] to be nil. # It's easy to change this one instance, but I'm not sure # at the moment where else might be affected ## Cri has a default proc for default values ## that doesn't store the keys. #new_opts.default_proc = proc do |hash,key| # # :max_retry => %s(max-retry) # key = key.to_s.gsub('_','-').to_sym # # opts.default_proc.call(hash,key) #end @cmd = cmd @cmd_args = args @cmd_opts = new_opts return self end |
#run ⇒ Object
531 532 533 |
# File 'lib/nhkore/app.rb', line 531 def run @app_cmd.run(@args) end |
#show_version ⇒ Object
535 536 537 |
# File 'lib/nhkore/app.rb', line 535 def show_version puts "#{NAME} v#{VERSION}" end |
#sleep_scraper ⇒ Object
539 540 541 |
# File 'lib/nhkore/app.rb', line 539 def sleep_scraper sleep(@sleep_time) end |
#start_spin(title, detail: '') ⇒ Object
543 544 545 546 547 548 549 550 551 552 553 |
# File 'lib/nhkore/app.rb', line 543 def start_spin(title,detail: '') if @spinner.is_a?(Hash) @spinner[:detail] = detail @spinner[:title] = title puts(NO_SPINNER_MSG % @spinner) else @spinner.update(title: title,detail: detail) @spinner.auto_spin end end |
#stop_spin ⇒ Object
555 556 557 558 559 560 561 562 |
# File 'lib/nhkore/app.rb', line 555 def stop_spin if @spinner.is_a?(Hash) puts (NO_SPINNER_MSG % @spinner) + ' done!' else @spinner.reset @spinner.stop('done!') end end |
#update_spin_detail(detail) ⇒ Object
564 565 566 567 568 569 570 571 572 |
# File 'lib/nhkore/app.rb', line 564 def update_spin_detail(detail) if @spinner.is_a?(Hash) @spinner[:detail] = detail puts(NO_SPINNER_MSG % @spinner) else @spinner.tokens[:detail] = detail end end |