require_relative '../objects/rcm_file' require_relative '../rcm_utils' require 'fileutils' module RCM class FileManager def get_id_to_name_mapping(file) id_to_name = {} ::File.open(file, 'r').each do |l| matches = /(?\w+):.+:(?\d+):.*\s/.match(l) id_to_name[matches[:id]] = matches[:name] end id_to_name end def apply_attributes(file) raise 'apply_attributes only works with ::RCM::File' unless file.is_a?(::RCM::File) @logger.debug("Setting owner as #{file.owner}:#{file.group} and mode as #{file.mode} on #{file.path}") # Will throw exception if something poopy happens ::FileUtils.chown(file.owner, file.group, file.path) ::FileUtils.chmod(file.mode, file.path) file.changed = true file end def copy(file) dir = ::File.dirname(file.path) @logger.debug("Ensuring #{dir} exsits.") ::FileUtils.mkdir_p(dir) @logger.debug("Copying #{file.src_path} to #{file.path}.") ::FileUtils.copy(file.src_path, file.path, remove_destination: true) file.changed = true file end def remove(file) return unless ::File.file?(file.path) @logger.debug("Removing #{file.path}.") ::FileUtils.rm(file.path) file.changed = true file end def initialize(logger) @logger = logger end def get_current_state(wanted_files) got = {} uids = get_id_to_name_mapping('/etc/passwd') gids = get_id_to_name_mapping('/etc/group') wanted_files.each do |path, p| f = ::RCM::File.new('', '', '', '', '') # Put in an empty object if file does not exist unless ::File.exist?(path) got[path] = f next end f_stat = ::File.stat(path) f.path = path f.owner = uids[f_stat.uid.to_s] f.group = gids[f_stat.gid.to_s] f.mode = f_stat.mode.to_s(8)[-4, 4] got[path] = f end got end end end