Files
gtav-src/tools_ng/lib/util/sort.rb
T
2025-09-29 00:52:08 +02:00

117 lines
2.9 KiB
Ruby
Executable File

#
# sort.rb
# Sorts an input text file and writes output to a file or stdout.
#
# Author:: David Muir <david.muir@rockstarnorth.com>
# Date:: 11 March 2008
#
# == Example Usage
#
# From a command line:
#
# sort.rb -a file1.txt file2.txt
#
#-----------------------------------------------------------------------------
# Uses
#-----------------------------------------------------------------------------
require 'pipeline/os/getopt'
require 'pipeline/os/path'
include Pipeline
#-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
SORT_VERSION = '0.9.0'
OPTIONS = [
[ '--version', '-v', Getopt::BOOLEAN, 'show version information.' ],
[ '--help', '-h', Getopt::BOOLEAN, 'show this help information.' ],
[ '--output', '-o', Getopt::REQUIRED, 'write sorted output to file.' ],
[ '--ascending', '-a', Getopt::BOOLEAN, 'sort in ascending order.' ],
[ '--descending', '-d', Getopt::BOOLEAN, 'sort in descending order.' ]
]
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
def print_usage
usage_message = OS::Getopt::usage( OPTIONS,
{ 'files' => 'List of files to sort.' } )
puts usage_message
end
def print_version
puts "\nsort.rb Version #{SORT_VERSION}"
end
def process_sort( opts, files )
# Read all files into an unsorted array ...
unsorted_input = Array.new
files.each do |filename|
File.open( filename ) do |fp|
begin
unsorted_input += fp.readlines
ensure
fp.close
end
end
end
sorted_output = nil
if ( opts['descending'] or opts['d'] ) then
sorted_output = unsorted_input.sort do |x,y| y <=> x; end
else
sorted_output = unsorted_input.sort
end
write_sorted_output( sorted_output, opts['output'] ) if opts['output']
sorted_output.each do |item|
puts item
end unless opts['output']
end
def write_sorted_output( output, filename )
File.open( filename, 'w' ) do |out|
output.each do |value|
out.write( "#{value}\n" )
end
end
end
#-----------------------------------------------------------------------------
# Entry
#-----------------------------------------------------------------------------
begin
opts, targs = OS::Getopt.getopts( OPTIONS )
if ( opts['version'] or opts['help'] )
print_version() if opts['version']
print_usage() if opts['help']
elsif targs.size > 0
process_sort( opts, targs )
else
print_usage() if opts['help']
end
rescue OS::Getopt::Error => ex
puts "Error parsing command line arguments: #{ex.message}"
print_usage()
rescue Exception => ex
puts "Unhandled exception: #{ex.message}"
puts "\tStacktrace: #{ex.backtrace.join('\n\r')}"
end
# End of sort.rb