Sha256: 50e90bc3d8e0532b3619647a62166a6545075f487defefb48354d99f65b6bf45

Contents?: true

Size: 1.41 KB

Versions: 4

Compression:

Stored size: 1.41 KB

Contents

require "time"
require "fileutils"

class ChecksummerFile
  attr_accessor :modified_at, :size, :type, :path, :original_path
  
  def initialize(attributes = {})
    attributes.each do |key, value|
      self.send :"#{key}=", value if self.respond_to?(:"#{key}=")
    end
  end
  
  def path=(new_path)
    @path = new_path
    @md5 = nil
  end
  
  def md5
    @md5 ||= md5_module.file(path).to_s
  end
  
  def md5_module
    if RUBY_VERSION.match(/^1\.9/)
      require "digest/md5"
      Digest::MD5
    else
      require "md5"
      MD5
    end
  end
  
  def self.from_line(line)
    modified_at, size, type, path, original_path = line.chomp.split("\t")
    ChecksummerFile.new(:modified_at => Time.parse(modified_at), :size => size.to_i, :type => type, :path => File.expand_path(path), 
      :original_path => original_path ? File.expand_path(original_path) : nil
    )
  end
  
  def checksum_to!(checksum_dir)
    if !File.symlink?(path)
      new_path = md5_path(checksum_dir)
      status = if !File.exists?(new_path)
        FileUtils.mkdir_p(File.dirname(new_path))
        FileUtils.cp(path, new_path)
        :copied
      else
        :symlinked
      end
      mtime = File.mtime(path)
      FileUtils.ln_sf(new_path, path)
      FileUtils.touch(path, :mtime => mtime)
      status
    else
      :was_symlink
    end
  end
  
  def md5_path(checksum_dir)
    "#{checksum_dir}/#{md5.split("")[0,4].join("/")}/#{md5}"
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
checksummer-0.1.7 lib/checksummer_file.rb
checksummer-0.1.6 lib/checksummer_file.rb
checksummer-0.1.5 lib/checksummer_file.rb
checksummer-0.1.4 lib/checksummer_file.rb