|
| 1 | +# |
| 2 | +# Author:: Adam Jacob (<adam@opscode.com>) |
| 3 | +# Author:: Daniel DeLeo (<dan@kallistec.com>) |
| 4 | +# Copyright:: Copyright (c) 2009 Opscode, Inc. |
| 5 | +# Copyright:: Copyright (c) 2009 Daniel DeLeo |
| 6 | +# License:: Apache License, Version 2.0 |
| 7 | +# |
| 8 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 9 | +# you may not use this file except in compliance with the License. |
| 10 | +# You may obtain a copy of the License at |
| 11 | +# |
| 12 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | +# |
| 14 | +# Unless required by applicable law or agreed to in writing, software |
| 15 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 16 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | +# See the License for the specific language governing permissions and |
| 18 | +# limitations under the License. |
| 19 | +# |
| 20 | + |
| 21 | +require 'chef/cache' |
| 22 | + |
| 23 | +class Chef |
| 24 | + class Cache |
| 25 | + class Checksum < Chef::Cache |
| 26 | + |
| 27 | + def self.checksum_for_file(*args) |
| 28 | + instance.checksum_for_file(*args) |
| 29 | + end |
| 30 | + |
| 31 | + def checksum_for_file(file) |
| 32 | + key, fstat = filename_to_key(file), File.stat(file) |
| 33 | + lookup_checksum(key, fstat) || generate_checksum(key, file, fstat) |
| 34 | + end |
| 35 | + |
| 36 | + def lookup_checksum(key, fstat) |
| 37 | + cached = @moneta.fetch(key) |
| 38 | + if cached && file_unchanged?(cached, fstat) |
| 39 | + cached["checksum"] |
| 40 | + else |
| 41 | + nil |
| 42 | + end |
| 43 | + end |
| 44 | + |
| 45 | + def generate_checksum(key, file, fstat) |
| 46 | + checksum = checksum_file(file) |
| 47 | + moneta.store(key, {"mtime" => fstat.mtime.to_f, "checksum" => checksum}) |
| 48 | + checksum |
| 49 | + end |
| 50 | + |
| 51 | + private |
| 52 | + |
| 53 | + def file_unchanged?(cached, fstat) |
| 54 | + cached["mtime"].to_f == fstat.mtime.to_f |
| 55 | + end |
| 56 | + |
| 57 | + def checksum_file(file) |
| 58 | + digest = Digest::SHA256.new |
| 59 | + IO.foreach(file) {|line| digest.update(line) } |
| 60 | + digest.hexdigest |
| 61 | + end |
| 62 | + |
| 63 | + def filename_to_key(file) |
| 64 | + "chef-file-#{file.gsub(/(#{File::SEPARATOR}|\.)/, '-')}" |
| 65 | + end |
| 66 | + |
| 67 | + end |
| 68 | + end |
| 69 | +end |
| 70 | + |
0 commit comments