Add names_to_numbers script
[cmccabe-bin] / names_to_numbers.rb
1 #!/usr/bin/ruby -w
2
3 #
4 # names_to_numbers.rb
5 #
6 # Renames all the files in a directory with the given file extension.
7 # The renamed files will just have numbers.
8 #
9 # Colin Mccabe
10 #
11
12 require 'fileutils'
13 require 'optparse'
14 require 'ostruct'
15
16 class MyOptions
17   def self.parse(args)
18     opts = OpenStruct.new
19     opts.dry_run = false
20     opts.num_digits = 2
21     opts.extension = nil
22     $fu_args = { :verbose => true }
23
24     # Fill in $opts values
25     parser = OptionParser.new do |myparser|
26       myparser.banner = "Usage: #{ File.basename($0) } [opts]"
27       myparser.separator("Specific options:")
28       myparser.on("--num-digits DIGITS", "-D",
29               "Set the number of digits in the numbering scheme.") do |d|
30         opts.num_digits = d.to_i
31       end
32       myparser.on("--dry-run", "-d",
33               "Show what would be done, without doing it.") do |d|
34         $fu_args = { :verbose => true, :noop => true }
35         opts.dry_run = true
36       end
37       myparser.on("--file-extension EXTENSION", "-e",
38               "The file extension for the files to rename.") do |e|
39         opts.extension = e
40       end
41     end
42
43     parser.parse!(args)
44     raise "invalid num_digits: #{opts.num_digits}" unless
45       opts.num_digits > 0
46     raise "must give an extension" unless opts.extension != nil
47     return opts
48   end
49 end
50
51 def pow(x, y)
52   ret = 1
53   (0...y).each do |z|
54     ret = ret * x
55   end
56   return ret
57 end
58 #.#{$opts.extension}").sort.each do |f|
59 def file_iter
60   Dir.glob("*.#{$opts.extension}").sort.each do |f| 
61     yield f
62   end
63 end
64
65 def count_files(file)
66   $total_files = $total_files + 1
67 end
68
69 def get_file_name(num)
70   return sprintf("%0#{$opts.num_digits}d.#{$opts.extension}", num)
71 end
72
73 def rename_files(file)
74   FileUtils.mv(file, get_file_name(1 + $total_files), $fu_args)
75   $total_files = $total_files + 1
76 end
77
78 # MAIN
79 begin
80   $opts = MyOptions.parse(ARGV)
81 rescue Exception => msg
82   $stderr.print("#{msg}.\nType --help to see usage information.\n")
83   exit 1
84 end
85
86 # make sure there aren't too many files
87 $total_files = 0
88 max_total_files = pow(10, $opts.num_digits) - 1
89 file_iter { |f| count_files(f) }
90 if ($total_files > max_total_files) then
91   raise "With #{$opts.num_digits} digit(s), we can only have at most \
92 #{max_total_files} files-- but there are #{$total_files} files in the \
93 #directory. Try setting a higher value for num_digits, using -D."
94 end
95
96 # rename files
97 $total_files = 0
98 file_iter { |f| rename_files(f) }
99
100 exit 0