Class: UsefulDB::CLI
- Inherits:
-
Object
- Object
- UsefulDB::CLI
- Defined in:
- lib/usefuldb/cli.rb
Constant Summary collapse
- COMMANDS =
%w[search list add remove rm show count export import help].freeze
- ImportExport =
UsefulDB::ImportExport
Class Method Summary collapse
- .command?(name) ⇒ Boolean
- .configure_logger(log, global) ⇒ Object
- .load_db!(log, global) ⇒ Object
- .load_options(global) ⇒ Object
- .parse_global_options(argv) ⇒ Object
- .partition_argv(argv, value_flags: []) ⇒ Object
- .prepare_db_for_import!(log, global, replace:) ⇒ Object
- .print_entries(entries, format:, ids: false) ⇒ Object
- .print_help(command = nil) ⇒ Object
- .run(argv, log:) ⇒ Object
- .run_add(argv, global, log) ⇒ Object
- .run_count(global, log) ⇒ Object
- .run_export(argv, global, log) ⇒ Object
- .run_import(argv, global, log) ⇒ Object
- .run_list(argv, global, log) ⇒ Object
- .run_remove(argv, global, log) ⇒ Object
- .run_search(argv, global, log) ⇒ Object
- .run_show(argv, global, log) ⇒ Object
Class Method Details
.command?(name) ⇒ Boolean
59 60 61 |
# File 'lib/usefuldb/cli.rb', line 59 def self.command?(name) COMMANDS.include?(name) end |
.configure_logger(log, global) ⇒ Object
101 102 103 104 105 106 107 108 109 |
# File 'lib/usefuldb/cli.rb', line 101 def self.configure_logger(log, global) if global[:quiet] log.level = Logger::ERROR elsif global[:verbose] log.level = Logger::DEBUG else log.level = Logger::ERROR end end |
.load_db!(log, global) ⇒ Object
148 149 150 151 |
# File 'lib/usefuldb/cli.rb', line 148 def self.load_db!(log, global) UsefulDB.setup(log) unless global[:db] UsefulDB.dbLoad(log, (global)) end |
.load_options(global) ⇒ Object
142 143 144 145 146 |
# File 'lib/usefuldb/cli.rb', line 142 def self.(global) = {} [:db] = global[:db] if global[:db] end |
.parse_global_options(argv) ⇒ Object
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 |
# File 'lib/usefuldb/cli.rb', line 63 def self.(argv) global = { db: nil, quiet: false, verbose: false } remaining = argv.dup while (arg = remaining.first) case arg when "--db" remaining.shift global[:db] = remaining.shift or raise OptionParser::ParseError, "missing argument: --db" when "-q", "--quiet" remaining.shift global[:quiet] = true when "-v", "--verbose" remaining.shift global[:verbose] = true when "--version" remaining.shift puts UsefulDB::Version.to_s exit 0 when "-h", "--help" remaining.shift print_help exit 0 when "--" remaining.shift break else break end end [global, remaining] end |
.partition_argv(argv, value_flags: []) ⇒ Object
111 112 113 114 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 |
# File 'lib/usefuldb/cli.rb', line 111 def self.partition_argv(argv, value_flags: []) = [] positional = [] index = 0 while index < argv.length token = argv[index] if token == "--" positional.concat(argv[(index + 1)..]) break elsif token == "-" positional << token index += 1 elsif token.start_with?("-") << token index += 1 if value_flags.include?(token) && index < argv.length && !argv[index].start_with?("-") << argv[index] index += 1 end else positional << token index += 1 end end [, positional] end |
.prepare_db_for_import!(log, global, replace:) ⇒ Object
421 422 423 424 425 426 427 428 429 430 431 432 |
# File 'lib/usefuldb/cli.rb', line 421 def self.prepare_db_for_import!(log, global, replace:) = (global) if global[:db] UsefulDB::Utils.ensure_db!(log, ) elsif replace && !File.exist?(UsefulDB::Utils.db_path()) UsefulDB::Utils.ensure_db!(log, ) else UsefulDB.setup(log) unless global[:db] UsefulDB.dbLoad(log, ) end end |
.print_entries(entries, format:, ids: false) ⇒ Object
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/usefuldb/cli.rb', line 434 def self.print_entries(entries, format:, ids: false) case format when :json puts UsefulDB::JSONEncoder.generate(entries) when :value_only entries.each { |entry| puts entry["value"] } else if entries.empty? puts "No matching entries." return end entries.each do |entry| prefix = ids ? "[#{entry['id']}] " : "" puts "#{prefix}#{entry['value']}" puts " tags: #{entry['tag'].join(', ')}" puts " #{entry['description']}" unless entry['description'].to_s.empty? puts end end end |
.print_help(command = nil) ⇒ Object
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 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 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/usefuldb/cli.rb', line 456 def self.print_help(command = nil) case command when "search" puts <<~HELP Usage: usefuldb search [options] [tags...] Options: --any Match entries with any tag (OR) --json Print results as JSON --value-only Print only entry values --ids Include entry ids in human output -h, --help Show this help HELP when "list" puts <<~HELP Usage: usefuldb list [options] Options: --json Print results as JSON --tags-only Print unique tags -h, --help Show this help HELP when "add" puts <<~HELP Usage: usefuldb add [options] Options: --tags TAGS Comma-separated search tags --value VALUE Stored command, URL, or text --description TEXT Entry description -h, --help Show this help HELP when "remove", "rm" puts <<~HELP Usage: usefuldb remove <id> [options] Options: --tags TAGS Match entry tags when removing by value --value VALUE Match entry value when removing by attributes -h, --help Show this help HELP when "show" puts <<~HELP Usage: usefuldb show <id> [options] Options: --json Print entry as JSON -h, --help Show this help HELP when "export" puts <<~HELP Usage: usefuldb export [options] [file] Options: -o, --output FILE Write export to FILE (- for stdout) --format FORMAT Export format: yaml or json -h, --help Show this help HELP when "import" puts <<~HELP Usage: usefuldb import [options] [file] Options: -i, --input FILE Read import from FILE (- for stdin) --format FORMAT Import format: yaml or json --merge Merge entries into the current database (default) --replace Replace the current database with the import -h, --help Show this help HELP else puts <<~HELP Usage: usefuldb [global options] <command> [arguments] A simple command and URL database searchable by tag. Commands: search [tags...] Find entries by tag list List all entries add Add an entry remove <id> Remove an entry by id show <id> Show a single entry count Print entry count export [file] Export the database to YAML or JSON import [file] Import a database export help [command] Show help Global options: --db PATH Database file (default: ~/.usefuldb/db.yaml) -q, --quiet Suppress non-essential output -v, --verbose Enable debug logging --version Print version -h, --help Show this help Examples: usefuldb search git push usefuldb search git commit --value-only usefuldb add --tags git,commit --value "git commit -m 'msg'" --description "Commit changes" usefuldb list --json usefuldb show 42 usefuldb remove 42 usefuldb export backup.yaml usefuldb import backup.yaml --merge usefuldb export -o - --format json | jq '.db | length' HELP end end |
.run(argv, log:) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 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 |
# File 'lib/usefuldb/cli.rb', line 12 def self.run(argv, log:) global, remaining = (argv) configure_logger(log, global) if remaining.empty? print_help return 0 end if command?(remaining.first) command = remaining.shift case command when "help" print_help(remaining.first) when "search" run_search(remaining, global, log) when "list" run_list(remaining, global, log) when "add" run_add(remaining, global, log) when "remove", "rm" run_remove(remaining, global, log) when "show" run_show(remaining, global, log) when "count" run_count(global, log) when "export" run_export(remaining, global, log) when "import" run_import(remaining, global, log) end else unknown = remaining.first raise OptionParser::ParseError, "Unknown command: #{unknown}. Use `usefuldb search` to find entries." end 0 rescue EntryInDB, EmptyDB, KeyOutOfBounds, EntryNotFound, ImportError => e warn e. unless global[:quiet] 1 rescue OptionParser::ParseError => e warn e. unless global[:quiet] warn "Run `usefuldb help` for usage." unless global[:quiet] 1 end |
.run_add(argv, global, log) ⇒ Object
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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/usefuldb/cli.rb', line 213 def self.run_add(argv, global, log) = { tags: nil, value: nil, description: nil } parser = OptionParser.new do |opts| opts. = "Usage: usefuldb add [options]" opts.on("--tags TAGS", "Comma-separated search tags") { |value| [:tags] = value } opts.on("--value VALUE", "Stored command, URL, or text") { |value| [:value] = value } opts.on("--description TEXT", "Entry description") { |value| [:description] = value } opts.on("-h", "--help", "Show this help") do puts opts exit 0 end end parser.order!(argv) load_db!(log, global) = [:tags] value = [:value] description = [:description] if .nil? $stdout.print "Tags (comma-separated): " = $stdin.gets.to_s.strip end if value.nil? $stdout.print "Value: " value = $stdin.gets.to_s.strip end if description.nil? && $stdin.tty? $stdout.print "Description (optional): " description = $stdin.gets.to_s.strip end = UsefulDB::Utils.() raise OptionParser::ParseError, "At least one tag is required" if .empty? raise OptionParser::ParseError, "Value is required" if value.to_s.strip.empty? entry = { "tag" => , "value" => value.strip, "description" => description.to_s } UsefulDB.add(entry, log) UsefulDB.dbSave(log, (global)) new_id = UsefulDB::Utils.count(log) - 1 puts "Added entry [#{new_id}]." unless global[:quiet] end |
.run_count(global, log) ⇒ Object
337 338 339 340 |
# File 'lib/usefuldb/cli.rb', line 337 def self.run_count(global, log) load_db!(log, global) puts UsefulDB::Utils.count(log) end |
.run_export(argv, global, log) ⇒ Object
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
# File 'lib/usefuldb/cli.rb', line 342 def self.run_export(argv, global, log) = { output: nil, format: nil } parser = OptionParser.new do |opts| opts. = "Usage: usefuldb export [options] [file]" opts.on("-o", "--output FILE", "Write export to FILE (- for stdout)") { |value| [:output] = value } opts.on("--format FORMAT", ImportExport::FORMATS.map(&:to_s), "Export format (yaml or json)") do |value| [:format] = value.to_sym end opts.on("-h", "--help", "Show this help") do puts opts exit 0 end end option_argv, positional = partition_argv(argv, value_flags: ["-o", "--output", "--format"]) parser.parse!(option_argv) output = [:output] || positional.first raise OptionParser::ParseError, "Output file is required (use - for stdout)" if output.nil? format = [:format] format ||= UsefulDB::ImportExport.detect_format(output) if output != "-" format ||= :yaml load_db!(log, global) content = UsefulDB::ImportExport.export_content(UsefulDB::Utils.export_data, format: format) UsefulDB::ImportExport.write_export(output, content) unless global[:quiet] || output == "-" puts "Exported #{UsefulDB::Utils.count(log)} entries to #{output}." end end |
.run_import(argv, global, log) ⇒ Object
379 380 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 |
# File 'lib/usefuldb/cli.rb', line 379 def self.run_import(argv, global, log) = { input: nil, format: nil, mode: :merge } parser = OptionParser.new do |opts| opts. = "Usage: usefuldb import [options] [file]" opts.on("-i", "--input FILE", "Read import from FILE (- for stdin)") { |value| [:input] = value } opts.on("--format FORMAT", ImportExport::FORMATS.map(&:to_s), "Import format (yaml or json)") do |value| [:format] = value.to_sym end opts.on("--merge", "Merge entries into the current database (default)") { [:mode] = :merge } opts.on("--replace", "Replace the current database with the import") { [:mode] = :replace } opts.on("-h", "--help", "Show this help") do puts opts exit 0 end end option_argv, positional = partition_argv(argv, value_flags: ["-i", "--input", "--format"]) parser.parse!(option_argv) input = [:input] || positional.first raise OptionParser::ParseError, "Input file is required (use - for stdin)" if input.nil? prepare_db_for_import!(log, global, replace: [:mode] == :replace) imported = UsefulDB::ImportExport.parse_file(input, format: [:format]) result = UsefulDB::ImportExport.import!(imported, mode: [:mode], log: log) UsefulDB.dbSave(log, (global)) return if global[:quiet] if result[:mode] == :replace puts "Replaced database with #{result[:total]} entries." else puts "Imported #{result[:added]} entries (#{result[:skipped]} skipped as duplicates). Database now has #{result[:total]} entries." end end |
.run_list(argv, global, log) ⇒ Object
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 |
# File 'lib/usefuldb/cli.rb', line 180 def self.run_list(argv, global, log) = { format: :human, tags_only: false } parser = OptionParser.new do |opts| opts. = "Usage: usefuldb list [options]" opts.on("--json", "Print results as JSON") { [:format] = :json } opts.on("--tags-only", "Print unique tags") { [:tags_only] = true } opts.on("-h", "--help", "Show this help") do puts opts exit 0 end end parser.order!(argv) load_db!(log, global) if [:tags_only] = UsefulDB::Utils. if [:format] == :json puts UsefulDB::JSONEncoder.generate() else .each { |tag| puts tag } end return end print_entries(UsefulDB::Utils.entries, format: [:format], ids: true) end |
.run_remove(argv, global, log) ⇒ Object
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
# File 'lib/usefuldb/cli.rb', line 271 def self.run_remove(argv, global, log) = { tags: nil, value: nil } id = nil parser = OptionParser.new do |opts| opts. = "Usage: usefuldb remove <id> [options]" opts.on("--tags TAGS", "Match entry tags when removing by value") { |value| [:tags] = value } opts.on("--value VALUE", "Match entry value when removing by attributes") { |value| [:value] = value } opts.on("-h", "--help", "Show this help") do puts opts exit 0 end end option_argv, positional = partition_argv(argv, value_flags: ["--tags", "--value"]) parser.parse!(option_argv) id = positional.first.to_i if positional.first&.match?(/\A\d+\z/) load_db!(log, global) if id.nil? raise OptionParser::ParseError, "Entry id is required" if [:value].nil? = UsefulDB::Utils.([:tags] || []) id = UsefulDB::Utils.find_entry_id(tags: , value: [:value]) raise EntryNotFound, "No entry matched the given tags and value" if id.nil? end removed = UsefulDB::Utils.get_entry(id) UsefulDB.remove(id, log) UsefulDB.dbSave(log, (global)) puts "Removed entry [#{id}]: #{removed['value']}" unless global[:quiet] end |
.run_search(argv, global, log) ⇒ Object
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 |
# File 'lib/usefuldb/cli.rb', line 153 def self.run_search(argv, global, log) = { match: :all, format: :human, ids: false } parser = OptionParser.new do |opts| opts. = "Usage: usefuldb search [options] [tags...]" opts.on("--any", "Match entries with any tag (OR)") { [:match] = :any } opts.on("--json", "Print results as JSON") { [:format] = :json } opts.on("--value-only", "Print only entry values") { [:format] = :value_only } opts.on("--ids", "Include entry ids in human output") { [:ids] = true } opts.on("-h", "--help", "Show this help") do puts opts exit 0 end end option_argv, = partition_argv(argv) parser.parse!(option_argv) load_db!(log, global) results = UsefulDB::Utils.search_entries(, match: [:match]) print_entries(results, format: [:format], ids: [:ids]) end |
.run_show(argv, global, log) ⇒ Object
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# File 'lib/usefuldb/cli.rb', line 309 def self.run_show(argv, global, log) json = false parser = OptionParser.new do |opts| opts. = "Usage: usefuldb show <id> [options]" opts.on("--json", "Print entry as JSON") { json = true } opts.on("-h", "--help", "Show this help") do puts opts exit 0 end end option_argv, positional = partition_argv(argv) parser.parse!(option_argv) id = positional.first raise OptionParser::ParseError, "Entry id is required" if id.nil? load_db!(log, global) entry = UsefulDB::Utils.get_entry(id.to_i) if json puts UsefulDB::JSONEncoder.generate(entry) else print_entries([entry], format: :human, ids: true) end end |