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.files.working_directory || Dir.pwd end def dir_path=(value) begin @dir = Eco::Data::Files::Directory.new(value) @dir_path = @dir.create rescue logger.error("could not create or make any sense of directory '#{value}'") end end def logger @enviro&.logger || ::Logger.new(IO::NULL) end ##### FILE ##### def file(filename, should_exist: false) dir.file(filename, should_exist: should_exit) end def newest(filename) dir.newest_file(file: filename) end def file_content(filename) file = dir.file(filename, should_exist: true) if !file logger.error("Can't read from file '#{filename}' because it does not exist.") return nil end logger.debug("Reading from file '#{file}'") File.read(file) end def load_json(filename) content = file_content(filename) return content && JSON.parse(content) end def touch(filename, modifier = :no_stamp, mode: :string) save("", filename, modifier, mode: mode) end def save(content, filename, modifier = :no_stamp, mode: :string) file = dir.file(filename) file = FileManager.timestamp_file(file) if modifier == :timestamp mode = (mode == :binary) ? 'wb' : 'w' FileManager.create_directory(FileManager.file_fullpath(file)) logger.debug("Writting to file '#{file}'") File.open(file, mode) { |fd| fd << content } return file end def save_json(data, filename, modifier = :no_stamp) return save(data.to_json, filename, modifier) end # if the file does not exist, it creates it def append(content, filename, mode: :string) file = dir.file(filename) mode = (mode == :binary) ? 'ab' : 'a' logger.debug("Appending to file '#{file}'") File.open(file, mode) { |fd| fd << content + "\n" } # '\n' won't add line return file end end end end end end