module Eco module API module Common module Session class FileManager include Eco::Data::Files attr_reader :dir, :dir_path attr_accessor :timestamp_pattern def initialize(init = {}, enviro: nil) @enviro = enviro init = @enviro.config if @enviro && init.empty? @timestamp_pattern = init.files.timestamp_pattern || DEFAULT_TIMESTAMP_PATTERN self.dir_path = init.working_directory || Dir.pwd end def dir_path=(value) @dir = Eco::Data::Files::Directory.new(value) @dir_path = @dir.create rescue StandardError => err logger.error("could not create or make any sense of directory '#{value}': #{err}") end def logger @enviro&.logger || ::Logger.new(IO::NULL) end ##### FILE ##### def file(filename, should_exist: false) dir.file(filename, should_exist: should_exist) end def newest(filename) dir.newest_file(file: filename) end def file_content(filename, mode: nil) file = dir.file(filename, should_exist: true) unless file logger.error("Can't read from file '#{filename}' because it does not exist.") return nil end logger.debug("Reading from file '#{file}'") mode ? File.read(file, mode: mode) : File.read(file) end def load_json(filename) file = dir.file(filename, should_exist: true) unless file logger.error("Can't read from file '#{filename}' because it does not exist.") return nil end fd = File.open(file) JSON.load fd # rubocop:disable Security/JSONLoad rescue JSON::ParserError => e pp "Parsing error on file #{file}" raise e ensure fd&.close end def touch(filename, modifier = :no_stamp, mode: :string) save("", filename, modifier, mode: mode) end def save_json(data, filename, modifier = :no_stamp) return save(data.to_json, filename, modifier) unless data.is_a?(Array) file = filename_for(filename, modifier) FileManager.create_directory( FileManager.file_fullpath(file) ) logger.debug("Writting to file '#{file}'") mode = mode == :binary ? 'wb' : 'w' File.open(file, mode) do |fd| first = true fd << '[' data.each do |elem| fd << "," unless first first = false fd << elem.to_json end fd << ']' end file end def save(content, filename, modifier = :no_stamp, mode: :string) file = filename_for(filename, modifier) FileManager.create_directory( FileManager.file_fullpath(file) ) logger.debug("Writting to file '#{file}'") mode = mode == :binary ? 'wb' : 'w' File.open(file, mode) { |fd| fd << content } file end # if the file does not exist, it creates it def append(content, filename, mode: :string) file = dir.file(filename) logger.debug("Appending to file '#{file}'") mode = mode == :binary ? 'ab' : 'a' File.open(file, mode) { |fd| fd << "#{content}\n" } file end def filename_for(filename, modifier = :no_stamp) file = dir.file(filename) file = FileManager.timestamp_file(file) if modifier == :timestamp file end end end end end end