|
| 1 | +require 'completely/commands/base' |
| 2 | + |
| 3 | +module Completely |
| 4 | + module Commands |
| 5 | + class Install < Base |
| 6 | + help 'Install a bash completion script' |
| 7 | + |
| 8 | + usage 'completely install PROGRAM [SCRIPT_PATH --force]' |
| 9 | + usage 'completely install (-h|--help)' |
| 10 | + |
| 11 | + option '-f --force', 'Overwrite target file if it exists' |
| 12 | + |
| 13 | + param 'PROGRAM', 'Name of the program the completions are for.' |
| 14 | + param 'SCRIPT_PATH', 'Path to the source bash script [default: completely.bash].' |
| 15 | + |
| 16 | + def run |
| 17 | + bounce |
| 18 | + success = system(*command) |
| 19 | + raise "Failed running command:\nnb`#{command.join ' '}`" unless success |
| 20 | + |
| 21 | + say "Saved m`#{target_path}`" |
| 22 | + end |
| 23 | + |
| 24 | + private |
| 25 | + |
| 26 | + def bounce |
| 27 | + unless completions_path |
| 28 | + raise 'Cannot determine system completions directory' |
| 29 | + end |
| 30 | + |
| 31 | + unless File.exist? script_path |
| 32 | + raise "Cannot find script: m`#{script_path}`" |
| 33 | + end |
| 34 | + |
| 35 | + if File.exist?(target_path) && !args['--force'] |
| 36 | + raise "File exists: m`#{target_path}`\nUse nb`--force` to overwrite" |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + def command |
| 41 | + result = root? ? [] : %w[sudo] |
| 42 | + result + %W[cp #{script_path} #{target_path}] |
| 43 | + end |
| 44 | + |
| 45 | + def script_path |
| 46 | + args['SCRIPT_PATH'] || 'completely.bash' |
| 47 | + end |
| 48 | + |
| 49 | + def target_path |
| 50 | + "#{completions_path}/#{args['PROGRAM']}" |
| 51 | + end |
| 52 | + |
| 53 | + def root? |
| 54 | + Process.uid.zero? |
| 55 | + end |
| 56 | + |
| 57 | + def completions_path |
| 58 | + @completions_path ||= completions_path! |
| 59 | + end |
| 60 | + |
| 61 | + def completions_path! |
| 62 | + candidates = %w[ |
| 63 | + /usr/share/bash-completion/completions |
| 64 | + /usr/local/etc/bash_completion.d |
| 65 | + ] |
| 66 | + |
| 67 | + candidates.each do |candidate| |
| 68 | + return candidate if Dir.exist? candidate |
| 69 | + end |
| 70 | + |
| 71 | + nil |
| 72 | + end |
| 73 | + end |
| 74 | + end |
| 75 | +end |
0 commit comments