#!/usr/bin/env ruby require 'utils' require 'tins/go' include Tins::GO require 'tins/xt/string' require 'term/ansicolor' def path_shifter(string, separator: ?/, n: nil) n or return string n, path = n.to_i, string.split(separator) if n < 0 path = path.slice(n..-1) else path.slice!(0...n) end path * separator end def underscore(string) string = path_shifter(string, n: $opts[?n], separator: '::') string = Tins::StringUnderscore.instance_method(:underscore).bind(string).() $opts[?s] and string.sub!(/(\.rb)?\z/, '.rb') string end def parameterize(string, separator) underscore(string).gsub(?/, separator) # quick and dirty end def camelize(string) string = path_shifter(string, n: $opts[?n]) string = string.gsub(/#{Regexp.quote(File.extname(string))}\Z/, '') string.camelize end def camelcase?(string) string[0, 1] =~ /[A-Z]/ end def compute_shift(config, string) string = underscore(string) result = config.classify.shift_path_by_default for prefix in config.classify.shift_path_for_prefix if string.start_with? prefix return prefix.count(?/) + 1 end end result end def usage puts <<~EOT Usage: #{File.basename($0)} [OPTS] Classifies pathes like foo/bar_baz into Foo::BarBaz if necessary. Options are -d declassifies Foo::BarBaz into foo/bar_baz if necessary -t toogle Foo::BarBaz into foo/bar_baz and vice versa -n NUMBER the number of module namespaces to skip from the left -b return right most module namespace -s adds .rb suffix to foo/bar_baz.rb if necessary -p SEPARATOR used for declassification -h display this help EOT exit 0 end $opts = go 'dtn:bsp:h' $opts[?h] and usage string = ARGV.shift or fail "need a class/filepath/filename" string = Term::ANSIColor.uncolor string config = Utils::ConfigFile.new config.configure_from_paths if $opts[?b] $opts[?n] = '-1' else $opts[?n] ||= compute_shift(config, string) end print( case when $opts[?t] if camelcase?(string) if separator = $opts[?p] parameterize string, separator else underscore string end else camelize string end when $opts[?d] if separator = $opts[?p] parameterize string, separator else underscore string end else camelize string end )