Sha256: 92a488adae9c07e864b0f19877a2df595f988d8ec7c750793118ee1cc83ddb6e

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 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}.tmp")
        FileUtils.mv("#{new_path}.tmp", 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

1 entries across 1 versions & 1 rubygems

Version Path
checksummer-0.1.8 lib/checksummer_file.rb