mercoledì 6 agosto 2008

Ruby: file sieve [ENG]

I use this rough but simple script to organize the files from a folder into a tree of folders according to the file name. Whene I create a file I add some "tags" to its name. The script moves a file with this name:

[tag1-tag2-tag3] file.ext
to this directory:
tag1/tag2/tag3/file.ext
buildind the tree as it goes.

"Moves the 'tagged' files to the appropriate dir"
def sieve_files(source_dir, dest_dir)
  # default source dir is current dir
  if (source_dir == nil) 
    source_dir = "."
  end
  # default destination dir is "./file_sieve"
  if (dest_dir == nil)
    dest_dir = "/file_sieve"
  end
  pattern = Regexp.new("\\[.*\\].*") # picks file with a "[tag]"
  Dir.foreach(source_dir) do |filename|
    if pattern.match(filename)
      tag = filename[1, filename.index(']')-1] # gets the "[tag]"
      clean_filename = filename[filename.index(']')+2, filename.length].strip() # gets the file name
      dir_structure = tag.split('-') # use tag to determine folder structure
      old_name = source_dir + "/" + filename # builds the directory tree
      new_name = implode(dest_dir, dir_structure) + clean_filename # builds the full path to the file
      create_dir(dest_dir, dir_structure) # creates the directory tree
      File.rename(old_name, new_name) # moves the file
    end
  end
end

"Create path string concatenating the path components" 
"(and stripping them of white spaces)"
def implode(base_dir, dirlist)
  res = base_dir + "/"
  dirlist.each { |item| res += item.strip() + "/"}
  res
end

"Create a directory tree"
def create_dir(base_dir, dirlist)
  dir_to_create = base_dir + "/"
  Dir.mkdir(dir_to_create) unless (File.exist?(dir_to_create))
  dirlist.each do |item|
    dir_to_create += item.strip() + "/"
    Dir.mkdir(dir_to_create) unless (File.exist?(dir_to_create))
  end
end

source_dir = ARGV.shift
dest_dir = ARGV.shift 
sieve_files(source_dir, dest_dir)

Nessun commento: