Sha256: 6fa261ac24586517540c94923300c0c1979dba1e77a7ad60eea638147ac71dbb

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

require "time"
require "fileutils"
require "pathname"
require "digest/md5"

class ChecksummerFile
  attr_accessor :modified_at, :size, :type, :path, :original_path, :original_line
  
  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 ||= Digest::MD5.file(path).to_s
  end
  
  def self.from_line(line)
    if path = line.chomp.split("\t").first
      ChecksummerFile.new(:original_line => line.chomp, :path => File.expand_path(path))
    else
      ChecksummerFile.new
    end
  end
  
  def self.from_paths(stream)
    stream.map { |path| self.new(:path => path.chomp.split("\t").first) }
  end
  
  def checksum_to!(checksum_dir)
    status = { :original_line => original_line, :original_path => path }
    if path.to_s.strip.length == 0 || !File.exists?(path)
      status[:status] = :not_found
    elsif !File.symlink?(path)
      new_path = File.expand_path(md5_path(checksum_dir))
      status[: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
      status[:checksummed_path] = new_path
      status[:checksum] = File.basename(new_path)
      mtime = File.mtime(path)
      FileUtils.ln_sf(new_path, path)
      FileUtils.touch(path, :mtime => mtime)
    else
      status[:status] = :was_symlink
      status[:realpath] = Pathname.new(path).realpath
      status[:checksum] = File.basename(status[:realpath]) if valid_checksum?(File.basename(status[:realpath]))
    end
    status
  end
  
  def valid_checksum?(checksum)
    !checksum.to_s.match(/^[0-9a-f]{32}$/).nil?
  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.2.5 lib/checksummer_file.rb