
# api: fpm
# title: Lowercase filenames
# description: Changes filenames and directories to lowercase in the packaging process
# type: rewrite
# category: filter
# version: 0.2
# license: MITL
#
# Lowercase input filenames and directories. Filenames according to
# specified extension list, or all files per `=*` parameter.
#
# Usage:
#  -u lcase=c:php:rb
#  -u lcase=*
#
# This filter name relates to SQL, not VBasic ;)
#


require "fpm/package"
require "fpm/util"
require "fileutils"


# rename uppercase filenames and directories
class FPM::Package::Filter_lcase < FPM::Package

  # rewrite filenames
  def update(opts)
    # prepare file search pattern
    if opts.empty?
      exts = /^\.$/
    elsif opts.include? "*"
      exts = //
    else
      exts = /^ .+ \. (?: #{opts.join('|')} ) $/ix
    end
    # traverse directory tree
    walk(staging_path, exts)
  end # def update

    # Level-wise trough directories, so no further need to care about already lowercased dirnames
  def walk(dir, exts)
    ::Dir.chdir(dir) do
      ::Dir.glob("*").each do
        |fn|
        if File.directory?(fn)
          walk(lcase(fn), exts)
        elsif File.file?(fn)
          lcase(fn) if fn =~ exts
        end
      end
    end
  end # walk

  # Only rename to lowercase if filename isn't already
  def lcase(fn)
    down = fn.downcase
    unless fn == down
      FileUtils.mv(fn, down)
    end
    return down
  end # lcase

end # class
