|
| 1 | +require 'completely/commands/base' |
| 2 | + |
| 3 | +module Completely |
| 4 | + module Commands |
| 5 | + class Install < Base |
| 6 | + TARGETS = %W[ |
| 7 | + /usr/share/bash-completion/completions |
| 8 | + /usr/local/etc/bash_completion.d |
| 9 | + #{Dir.home}/.bash_completion.d |
| 10 | + ] |
| 11 | + |
| 12 | + summary 'Install a bash completion script' |
| 13 | + |
| 14 | + help <<~HELP |
| 15 | + This command will copy the specified file to one of the following directories: |
| 16 | +
|
| 17 | + #{TARGETS.map { |c| " - #{c}" }.join "\n"} |
| 18 | +
|
| 19 | + The target filename will be the program name, and sudo will be used if necessary. |
| 20 | + HELP |
| 21 | + |
| 22 | + usage 'completely install PROGRAM [SCRIPT_PATH --force --dry]' |
| 23 | + usage 'completely install (-h|--help)' |
| 24 | + |
| 25 | + option '-f --force', 'Overwrite target file if it exists' |
| 26 | + option '-d --dry', 'Show the installation command but do not run it' |
| 27 | + |
| 28 | + param 'PROGRAM', 'Name of the program the completions are for.' |
| 29 | + param 'SCRIPT_PATH', 'Path to the source bash script [default: completely.bash].' |
| 30 | + |
| 31 | + def run |
| 32 | + bounce |
| 33 | + |
| 34 | + if args['--dry'] |
| 35 | + puts command.join ' ' |
| 36 | + return |
| 37 | + end |
| 38 | + |
| 39 | + success = system(*command) |
| 40 | + raise "Failed running command:\nnb`#{command.join ' '}`" unless success |
| 41 | + |
| 42 | + say "Saved m`#{target_path}`" |
| 43 | + say 'You may need to restart your session to test it' |
| 44 | + end |
| 45 | + |
| 46 | + private |
| 47 | + |
| 48 | + def bounce |
| 49 | + unless completions_path |
| 50 | + raise 'Cannot determine system completions directory' |
| 51 | + end |
| 52 | + |
| 53 | + unless File.exist? script_path |
| 54 | + raise "Cannot find script: m`#{script_path}`" |
| 55 | + end |
| 56 | + |
| 57 | + if target_exist? && !args['--force'] |
| 58 | + raise "File exists: m`#{target_path}`\nUse nb`--force` to overwrite" |
| 59 | + end |
| 60 | + end |
| 61 | + |
| 62 | + def target_exist? |
| 63 | + File.exist? target_path |
| 64 | + end |
| 65 | + |
| 66 | + def command |
| 67 | + result = root? ? [] : %w[sudo] |
| 68 | + result + %W[cp #{script_path} #{target_path}] |
| 69 | + end |
| 70 | + |
| 71 | + def script_path |
| 72 | + args['SCRIPT_PATH'] || 'completely.bash' |
| 73 | + end |
| 74 | + |
| 75 | + def target_path |
| 76 | + "#{completions_path}/#{args['PROGRAM']}" |
| 77 | + end |
| 78 | + |
| 79 | + def root? |
| 80 | + Process.uid.zero? |
| 81 | + end |
| 82 | + |
| 83 | + def completions_path |
| 84 | + @completions_path ||= completions_path! |
| 85 | + end |
| 86 | + |
| 87 | + def completions_path! |
| 88 | + TARGETS.each do |tarnet| |
| 89 | + return tarnet if Dir.exist? tarnet |
| 90 | + end |
| 91 | + |
| 92 | + nil |
| 93 | + end |
| 94 | + end |
| 95 | + end |
| 96 | +end |
0 commit comments