Module: S3Rotate::FileUtils

Defined in:
lib/s3_rotate/utils/file_utils.rb

Class Method Summary collapse

Class Method Details

.date_from_filename(filename, date_regex = /\d{4}-\d{2}-\d{2}/, date_format = "%Y-%m-%d") ⇒ Object

Parse the date in a filename Date can be any format recognize by Date.parse, or be a timestamp

Parameters:

  • filename

    String containing the filename to be parsed.

  • date_regex (defaults to: /\d{4}-\d{2}-\d{2}/)

    Regex returning the date contained in the filename

  • date_format (defaults to: "%Y-%m-%d")

    Format to be used by DateTime.strptime to parse the extracted date

Returns:

  • Date instance, representing the parsed date



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/s3_rotate/utils/file_utils.rb', line 17

def FileUtils.date_from_filename(filename, date_regex=/\d{4}-\d{2}-\d{2}/, date_format="%Y-%m-%d")
  # match the date in the filename
  match = filename.match(date_regex)

  if not match
    date_str = nil
  elsif not match.captures
    date_str = match.to_s
  else
    date_str = match.captures.first || match.to_s
  end

  # if nothing could be match, immediately fail
  raise "Invalid date_regex or filename format" if not date_str

  # regular date
  begin
    DateTime.strptime(date_str, date_format).to_date
  rescue
    raise "Invalid date_format"
  end
end

.extension_from_filename(filename) ⇒ Object

Parse the extension in a filename

Parameters:

  • filename

    String containing the filename to be parsed

Returns:

  • String containing the extension of the filename if relevant, None otherwise



47
48
49
50
51
# File 'lib/s3_rotate/utils/file_utils.rb', line 47

def FileUtils.extension_from_filename(filename)
  if filename.include?('.')
    '.' + filename.split('/').last.split('.')[1..-1].join('.')
  end
end

.files_in_directory(directory) ⇒ Object

Get the list of files in the specified directory

Parameters:

  • directory

    String containing the path to the directory

Returns:

  • array of filenames, in ascending date order



60
61
62
63
64
# File 'lib/s3_rotate/utils/file_utils.rb', line 60

def FileUtils.files_in_directory(directory)
  Dir.entries(directory).select { |f| !File.directory? f }.sort
rescue
  raise "Invalid directory #{directory}"
end