Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/ruby
- Version = 'ports v.0.1'
- require 'optparse'
- require 'open3'
- # --- Just the ARGV parser -----------------------------------
- options = {}
- parser = OptionParser.new do |opts|
- opts.banner = "usage: rd ports [options]"
- opts.on('-i', '--index PORT', Integer, 'Returns port-path for given index') do |index|
- options[:index] = index
- end
- opts.on('-c', '--check PATH', 'Prints ports list-index if PATH is valid port path') do |path|
- options[:check] = path
- # TODO !!
- end
- opts.on('-v', '--version', 'Show script version') do
- puts Version
- exit
- end
- opts.on('-h', '--help', 'Show help screen') do
- puts opts
- exit
- end
- end
- begin
- parser.parse!
- rescue OptionParser::InvalidOption, OptionParser::MissingArgument, OptionParser::InvalidArgument
- puts $!.to_s
- exit
- end
- # ----------END OPTIONS PARSER ------------- ARGV
- # Scan ports
- ports = []
- stdout, stderr, status = Open3.capture3("ls /dev/*usb*")
- if (status.success?)
- ports += stdout.split("\n")
- end
- # No ports available? => terminate w/error
- if ports.empty?
- STDERR.puts "No USB devices/ports detected"
- exit 1
- end
- # checks port-path against available ports,
- # returns ports list index if path is valid
- # TODO:
- if (options.has_key?(:check))
- puts 'port PATH has been triggered'
- exit
- end
- # returns port path for option[:index]
- if (options.has_key?(:index))
- if (options[:index] < ports.length) #<= index must be within range
- puts ports[options[:index]]
- exit
- else
- STDERR.puts "invalid port list index: #{options[:index]}"
- exit 1
- end
- end
- # default action: returns ports list
- puts "....................................."
- ports.each_index {|i| puts "[#{i}]: #{ports[i]}"}
- puts "....................................."
- exit
Add Comment
Please, Sign In to add comment