537 lines
14 KiB
Ruby
Executable file
537 lines
14 KiB
Ruby
Executable file
#!/usr/bin/env ruby
|
|
# -*- encoding : utf-8 -*-
|
|
|
|
require 'irb-pager'
|
|
require 'shellwords'
|
|
require 'getoptlong'
|
|
|
|
class GetoptLong
|
|
def argv=( v) @argv = v end
|
|
def argv() @argv end
|
|
def ARGV=( v) @argv = v end
|
|
def ARGV() @argv end
|
|
end
|
|
|
|
class Commands < Hash
|
|
class CommandError < Exception
|
|
end
|
|
class ExpectingCommandError < CommandError
|
|
def initialize *args
|
|
args = ['Command expected'] if args.empty?
|
|
super *args
|
|
end
|
|
end
|
|
class UnknownCommandError < CommandError
|
|
def initialize *args
|
|
args = ['This Command i do not know'] if args.empty?
|
|
super *args
|
|
end
|
|
end
|
|
|
|
attr_accessor :exe, :prefix, :fallback_cmd
|
|
|
|
def self.arg_unshift arg, args
|
|
arg = arg.is_a?(Array) ? arg : [arg]
|
|
i = 1+args.index {|x|/^[^-]/=~x}
|
|
args[0...i] + arg + args[i..-1]
|
|
end
|
|
|
|
def self.new prefix, exe
|
|
r = super()
|
|
r.exe = exe
|
|
r.prefix = prefix
|
|
r.on {|cmd, *argv| raise UnknownCommandError, 'Unknown Command: %s' % cmd }
|
|
r
|
|
end
|
|
|
|
def sym_name name
|
|
name.to_s.to_sym
|
|
end
|
|
|
|
def on *names, &run
|
|
options = names.last.is_a?(Hash) ? names.pop.dup : {}
|
|
if names.empty?
|
|
@fallback_cmd = run
|
|
else
|
|
names.each {|name| self[sym_name name] = run }
|
|
end
|
|
end
|
|
|
|
def cmd argv
|
|
if @prefix == @exe
|
|
raise ExpectingCommandError if argv.empty?
|
|
[argv[0].to_sym, *argv[1..-1]]
|
|
else
|
|
@exe =~ /^(?:#{Regexp.escape @prefix}-)?(.*)$/
|
|
[$1.to_sym, *argv]
|
|
end
|
|
end
|
|
|
|
def each all=nil, &block
|
|
if not block_given?
|
|
Enumerator.new self, :each, all
|
|
elsif all
|
|
super(&block)
|
|
else
|
|
super() {|k,v| yield k,v unless /^-/ =~ k.to_s }
|
|
end
|
|
end
|
|
|
|
def run *argv
|
|
c, *argv = self.cmd( argv)
|
|
(self[c] || @fallback_cmd).call c, *argv
|
|
rescue CommandError
|
|
STDERR.puts $!.message, $!.backtrace
|
|
exit 1
|
|
end
|
|
alias call run
|
|
|
|
def to_proc
|
|
method(:call).to_proc
|
|
end
|
|
end
|
|
|
|
# RunCave
|
|
# =======
|
|
#
|
|
# Prepare cave-commands.
|
|
|
|
class RunCave
|
|
class CommandExpected <Exception
|
|
end
|
|
class ResumeFileExpected <Exception
|
|
end
|
|
|
|
attr_accessor :preargs, :cmd, :args, :log_level
|
|
attr_reader :dummy, :resumable
|
|
attr_writer :resume_file
|
|
def initialize preargs = nil, cmd = nil, args = nil
|
|
@resume_file, @preargs, @cmd, @args = nil, preargs || [], cmd || [], args || []
|
|
@colored = @dummy = @resumable = nil
|
|
end
|
|
|
|
def can_be_dummy
|
|
@dummy = true unless false == @dummy
|
|
self
|
|
end
|
|
def dummy?() @dummy end
|
|
def dummy!() @dummy = true; self end
|
|
def dummy=(v) @dummy = !!v; self end
|
|
|
|
def can_be_resumable
|
|
@resumable = true unless false == @resumable
|
|
self
|
|
end
|
|
def resumable?() @resumable end
|
|
def resumable!() @resumable = true; self end
|
|
def resumable=(v) @resumable = !!v; self end
|
|
|
|
def can_be_colored
|
|
@colored = true unless false == @colored
|
|
self
|
|
end
|
|
def colored?() @colored end
|
|
def colored!() @colored = true; self end
|
|
def colored=(v) @colored = !!v; self end
|
|
|
|
def prepare_resume_file
|
|
resumable? ? ['--resume-file', @resume_file || raise(ResumeFileExpected)] : []
|
|
end
|
|
|
|
def prepare_colored
|
|
colored? ? ['--colour', 'yes'] : []
|
|
end
|
|
|
|
def prepare_log_level
|
|
@log_level ? ['--log-level', @log_level] : []
|
|
end
|
|
|
|
def prepare
|
|
raise CommandExpected, "Set #{self}.cmd = yourcommand." if @cmd.nil? or @cmd.empty?
|
|
[
|
|
:cave, prepare_colored, prepare_log_level, @preargs,
|
|
@cmd, prepare_resume_file, *@args
|
|
].flatten.select{|x|x}.map {|x| x.to_s }
|
|
end
|
|
|
|
def run
|
|
a = prepare
|
|
if dummy?
|
|
puts a.shelljoin
|
|
0
|
|
else
|
|
Kernel.system *a
|
|
$? && $?.exitstatus
|
|
end
|
|
end
|
|
|
|
def this cmd, *args
|
|
@cmd, @args = cmd, args
|
|
self
|
|
end
|
|
alias method_missing this
|
|
|
|
def resume_file f
|
|
if f.nil?
|
|
@resume_file
|
|
else
|
|
@resume_file = f
|
|
self
|
|
end
|
|
end
|
|
|
|
def run_exit
|
|
exit run || 130
|
|
end
|
|
alias call run_exit
|
|
end
|
|
|
|
class Opts < Hash
|
|
class UnknownArgument < Exception
|
|
def initialize arg
|
|
super "Unknown argument: #{arg}"
|
|
end
|
|
end
|
|
class ArgumentExpected < Exception
|
|
def initialize arg
|
|
super "Argument expected for: #{arg}"
|
|
end
|
|
end
|
|
|
|
def opt *names, &exe
|
|
names.each do |name|
|
|
self[name.to_s.to_sym] = [exe, false]
|
|
end
|
|
end
|
|
|
|
def opt_arg *names, &exe
|
|
names.each do |name|
|
|
self[name.to_s.to_sym] = [exe, true]
|
|
end
|
|
end
|
|
|
|
def parse *argv
|
|
get_arg = lambda {|e| argv.shift; e.call argv[0] }
|
|
argv = argv.dup
|
|
until argv.empty?
|
|
opt = argv[0]
|
|
case opt
|
|
when /^(?:(-[^-])=?|(--[^=]+)=)(.*)$/
|
|
opt, arg = $1||$2, $3
|
|
exe, need_arg = (self[opt] or return( argv))
|
|
need_arg ? exe( opt, arg) : raise( ArgumentExpected, opt)
|
|
when /^(?:-[^-]|--[^=]+)$/
|
|
exe, need_arg = (self[opt] or return( argv))
|
|
need_arg ? exe( opt, get_arg.()) : exe
|
|
else
|
|
return argv
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
# Truckle
|
|
# =======
|
|
#
|
|
# cave-wrapper
|
|
|
|
class Truckle
|
|
class ExecutionError < Exception
|
|
end
|
|
|
|
# Calls exe while IRB::Pager redirect output to your PAGER.
|
|
def pager *args, &exe
|
|
if @nopager
|
|
exe.call
|
|
else
|
|
IRB::Pager::pager *args, &exe
|
|
end
|
|
end
|
|
|
|
# Restarts, if not @nosudo and not root yet, your Truckle as root
|
|
def sudo *args, &exe
|
|
if @nosudo or 0 == Process.egid
|
|
exe.call
|
|
else
|
|
exepath = File.join File.dirname( @argv0), @cmds.prefix
|
|
args = [:sudo, exepath, @params, *args].flatten.select{|x|x}.map {|x| x.to_s }
|
|
Kernel.exec *args
|
|
raise ExecutionError, "Can't exec #{args.shelljoin}"
|
|
end
|
|
end
|
|
|
|
# Your command will be called - if it will be called - with sudo.
|
|
def sudod exe = nil, &block
|
|
exe ||= block
|
|
lambda {|*args| sudo( *args) { exe.call *args } }
|
|
end
|
|
|
|
# Yout command will be called - if it will be called - with pager.
|
|
def pagered exe = nil, &block
|
|
exe ||= block
|
|
lambda {|*args| pager { exe.call *args } }
|
|
end
|
|
|
|
# Yout command will be called - if it will be called - with sudo first and second pager.
|
|
#
|
|
# cmds.on :hamster, &sudo_pagered {|cmd, *args| puts "Your hamster said: \"#{args.join ' '}\"" }
|
|
#
|
|
# It is shorter than:
|
|
#
|
|
# cmds.on( :hamster) {|cmd, *args| sudo( cmd, *args) { pager { puts "Your hamster said: \"#{args.join ' '}\"" } } }
|
|
def sudo_pagered exe = nil, &block
|
|
exe ||= block
|
|
lambda {|*args| sudo( *args) { pager { exe.call *args } } }
|
|
end
|
|
|
|
def markdown_format t, colored = nil
|
|
t = t.gsub( /^\t+/) {|indent| ' '*indent.length}
|
|
if colored
|
|
t.gsub! /^([^\n]+)\n===+/m, "\n«««««« \033[1;4;33m\\1\033[0m »»»»»»"
|
|
t.gsub! /^([^\n]+)\n---+/m, "\n««« \033[1;33m\\1\033[0m »»»"
|
|
t.gsub! /^ (.*?)( *#.*)$/, " \033[1;44m\\1\033[0m\\2"
|
|
t.gsub! /`([^`]+)`/, "\033[1;44m \\1 \033[0m"
|
|
t.gsub! /\*([^*]+)\*/, "\033[1m\\1\033[0m"
|
|
end
|
|
t = t[1..-1] while t.start_with? "\n"
|
|
t
|
|
end
|
|
|
|
def initialize argv0
|
|
ENV['LESS'] = "-FR #{ENV['LESS']}"
|
|
|
|
@argv0 = argv0
|
|
@exename = File.basename argv0
|
|
|
|
# initialize our program.
|
|
@cave = RunCave.new
|
|
@cmds = Commands.new 'truckle', @exename
|
|
|
|
prepare_commands
|
|
end
|
|
|
|
def helptext
|
|
cmd = @cmds.prefix
|
|
markdown_format <<EOF, @cave.colored?
|
|
Usage
|
|
=====
|
|
|
|
#{cmd} *PREARGS Command *ARGS
|
|
|
|
Arguments
|
|
=========
|
|
|
|
Precede the command, it's possible to set some arguments.
|
|
These Arguments really must precede the command.
|
|
|
|
- `-C|--list-commands` will list all possible commands and exit.
|
|
- `-h|--help` will print this help and exit.
|
|
- `-n|--dummy` will print the shellcode, which will be executed, if not --dummy.
|
|
- `-s|--sudo on|off|auto` will use (or not) sudo if you are not root.
|
|
- `-c|--color|--colour on|off|auto` will control the colorfull output of `cave`.
|
|
- `-L|--log-level LOGLEVEL` will control the log-level of `cave`.
|
|
- `-p|--pager PAGER` will change the pager to display.
|
|
|
|
Instead of on|off you can use 0|true or 1|false too. Default is everytime auto.
|
|
|
|
Environment
|
|
===========
|
|
|
|
- `DUMMY=1` will print the shellcode, which will be executed, like `--dummy`.
|
|
- `NOSUDO=1` will prevent of using sudo, if you are not root, like `--sudo off`.
|
|
- `PAGER=more` will change the pager to more, instead of less, like `--pager more`.
|
|
|
|
Commands
|
|
========
|
|
|
|
Most commands are like by cave.
|
|
|
|
- `search` is pagered.
|
|
- `show` is pagered.
|
|
- `resolve` is pagered and resumable. Do *not* use `-x`! Use `resume`.
|
|
- `install` is resumable and like `cave resolve -x`.
|
|
- `upgrade` is pagered and resumable and like `cave resolve -c world`. Do *not* use `-x`! Use `resume`.
|
|
- `remove` is pagered, resumable and like `cave uninstall`. Do *not* use `-x`! Use `resume`.
|
|
- `uninstall` is resumable and like `cave uninstall -x`.
|
|
- `fix-linkage` is pagered and resumable.
|
|
- `do` and `resume` are resumable and will resume or execute the last command.
|
|
|
|
Resumable
|
|
=========
|
|
|
|
You do not need to set a resume-file. #{cmd} will determine it automaticaly. First, you can give a first argument for tagging. Tag must be numerical!
|
|
|
|
#{cmd} 321 resolve netcat6
|
|
#{cmd} 321 do
|
|
|
|
If you do not give a tag, #{cmd} will use the actual terminal-device-number. If it isn't possible to determine terminal, the parent-pid will be used.
|
|
|
|
Like cave but different
|
|
=======================
|
|
|
|
Some commands will be displayed by a pager, so you can scroll up and down like
|
|
|
|
truckle resolve WHAT # cave -cy resolve WHAT | less -R
|
|
truckle remove WHAT # cave -cy uninstall WHAT | less -R
|
|
|
|
Some commands are not displayed by a pager, but will execute:
|
|
|
|
truckle install WHAT # cave -cy resolve -x WHAT
|
|
truckle uninstall WHAT # cave -cy uninstall -x WHAT
|
|
|
|
«do» and «resume» are special, to execute the last command:
|
|
|
|
truckle resume # | do # cave resume
|
|
trdo # | tresume # shortcuts
|
|
EOF
|
|
end
|
|
|
|
def prepare_commands
|
|
cmds, cave = @cmds, @cave
|
|
|
|
# default: simple use cave
|
|
cmds.on &sudod {|*args| cave.this(*args).() }
|
|
|
|
cmds.on :help, '-h', '--help', &pagered { STDOUT.puts helptext }
|
|
cmds.on :sync, &sudod { cave.sync.() }
|
|
cmds.on :search, :show, &sudo_pagered {|*args| cave.this(*args).() }
|
|
cmds.on :resolve, &sudo_pagered {|*args| cave.resumable!.this(*args).() }
|
|
cmds.on 'fix-linkage', &sudo_pagered {|*args|
|
|
cave.resumable!.this *args
|
|
cave.args.push '--', cave.prepare_resume_file
|
|
cave.resumable = false
|
|
cave.()
|
|
}
|
|
cmds.on :remove, &sudo_pagered {|cmd, *args| cave.resumable!.uninstall(*args).()}
|
|
cmds.on :upgrade, &sudo_pagered {|cmd, *args| cave.resumable!.resolve( '-c', :world, *args).() }
|
|
cmds.on :install, &sudod {|cmd, *argv| cave.resumable!.resolve( '-x', *argv).() }
|
|
cmds.on :uninstall, &sudod {|cmd, *argv| cave.resumable!.uninstall( '-x', *argv).() }
|
|
|
|
cmds.on :do, :resume, &sudod {|cmd, *args| cave.resumable!.resume( *args).() }
|
|
|
|
cmds.on '--list-commands', &pagered { puts cmds.map {|k,v| k } }
|
|
end
|
|
|
|
def setup_params options
|
|
on_off_auto = lambda do |arg|
|
|
case arg
|
|
when 'on', '1', 'true', 't' then true
|
|
when 'off', '0', 'false', 'f' then false
|
|
end
|
|
end
|
|
opts = GetoptLong.new(
|
|
[ '-r', '--resume-file', GetoptLong::REQUIRED_ARGUMENT ],
|
|
[ '-h', '--help', GetoptLong::NO_ARGUMENT ],
|
|
[ '-C', '--list-commands', GetoptLong::NO_ARGUMENT ],
|
|
[ '-n', '--dummy', GetoptLong::NO_ARGUMENT ],
|
|
[ '-t', '--tag', GetoptLong::REQUIRED_ARGUMENT ],
|
|
[ '-p', '--pager', GetoptLong::REQUIRED_ARGUMENT ],
|
|
[ '-c', '--color', '--colour', GetoptLong::REQUIRED_ARGUMENT ],
|
|
[ '-L', '--log-level', GetoptLong::REQUIRED_ARGUMENT ],
|
|
[ '-s', '--sudo', GetoptLong::REQUIRED_ARGUMENT ]
|
|
)
|
|
opts.ordering = GetoptLong::REQUIRE_ORDER
|
|
|
|
opts.each do |opt, arg|
|
|
case opt
|
|
when '-C' then options[:cmd] = '--list-commands'
|
|
when '-r' then options[:resume_file] = arg
|
|
when '-h' then options[:cmd] = 'help'
|
|
when '-n' then options[:dummy] = true
|
|
when '-t' then options[:tag] = arg
|
|
when '-p' then options[:pager] = on_off_auto[arg]
|
|
when '-c' then options[:color] = on_off_auto[arg]
|
|
when '-L' then options[:log_level] = arg
|
|
when '-s' then options[:sudo] = on_off_auto[arg]
|
|
else opts.terminate
|
|
end
|
|
''
|
|
end
|
|
options
|
|
end
|
|
|
|
def setup_env options
|
|
options[:dummy] = true if %w[1 true yes].include?( ENV['DUMMY'].to_s.downcase)
|
|
options[:sudo] = false if %w[1 true yes].include?( ENV['NOSUDO'].to_s.downcase)
|
|
options[:tty] = true if STDOUT.tty?
|
|
end
|
|
|
|
def setup_run options
|
|
on_off_auto = lambda {|x| nil == x ? true : x }
|
|
ARGV.unshift options[:cmd] if options[:cmd]
|
|
@cave.dummy! if options[:dummy]
|
|
@cave.log_level if options[:log_level]
|
|
@cave.can_be_colored if on_off_auto.( options[:color]) and options[:tty]
|
|
@nopager = true unless on_off_auto.( options[:pager]) or options[:tty]
|
|
@nosudo = true unless on_off_auto.( options[:sudo])
|
|
|
|
resumefilesuffix = if options[:resume_file]
|
|
options[:resume_file]
|
|
elsif options[:tag]
|
|
"tag-#{options[:tag]}"
|
|
elsif STDOUT.tty? and STDIN.tty? and STDOUT.stat.rdev == STDIN.stat.rdev
|
|
"dev-#{STDOUT.stat.rdev}"
|
|
else
|
|
"ppd-#{Process.ppid}"
|
|
end
|
|
@cave.resume_file = options[:resume_file] || "/tmp/truckle-resume-#{resumefilesuffix}"
|
|
end
|
|
|
|
def setup_recall options
|
|
on_off_auto = lambda {|n,x| case x when true then [n, 'on'] when false then [n, 'off'] end }
|
|
param = lambda {|n,x| n if x }
|
|
|
|
@params = [
|
|
param.( '--dummy', options[:dummy]),
|
|
param.( ['--resume-file', options[:resume_file]], options[:resume_file]),
|
|
param.( ['--tag', options[:tag]], options[:tag]),
|
|
param.( ['--log-level', options[:log_level]], options[:log_level]),
|
|
on_off_auto.( '--sudo', options[:sudo]),
|
|
on_off_auto.( '--color', options[:color]),
|
|
on_off_auto.( '--pager', options[:pager])
|
|
].flatten.select{|x|x}.map(&:to_s)
|
|
end
|
|
|
|
def run
|
|
options = {}
|
|
setup_env options
|
|
setup_params options
|
|
setup_recall options
|
|
setup_run options
|
|
|
|
@cmds.run *ARGV
|
|
end
|
|
|
|
def self.run argv0
|
|
self.new( argv0).run
|
|
end
|
|
end
|
|
|
|
class Shortcut
|
|
attr_reader :argv0
|
|
def initialize argv0
|
|
@argv0 = argv0
|
|
end
|
|
|
|
def exec exe, *args
|
|
exe = File.join File.dirname( @argv0), exe.to_s
|
|
Kernel.exec exe, *args.flatten.select{|x|x}.map(&:to_s)
|
|
end
|
|
|
|
def run
|
|
exe = File.basename @argv0
|
|
case exe.to_sym
|
|
when :trdo then exec :truckle, :do, *ARGV
|
|
when :tresume then exec :truckle, :resume, *ARGV
|
|
end
|
|
end
|
|
alias call run
|
|
|
|
def self.run argv0
|
|
self.new( argv0).run
|
|
end
|
|
end
|
|
|
|
Shortcut.run $0
|
|
Truckle.run $0
|