Sha256: 3cb807c21d527697eaa54ad93ae6b417bd5a91ebb189a93525d1b7d443a8eb36

Contents?: true

Size: 1.96 KB

Versions: 5

Compression:

Stored size: 1.96 KB

Contents

require 'fileutils'

class KuberKit::Shell::LocalShell < KuberKit::Shell::AbstractShell
  include KuberKit::Import[
    "tools.logger",
    "shell.command_counter",
    "shell.rsync_commands",
  ]

  def exec!(command, log_command: true)
    command_number = command_counter.get_number.to_s.rjust(2, "0")
    
    if log_command
      logger.info("Execute: [#{command_number}]: #{command.to_s.cyan}")
    end

    result = nil
    IO.popen(command, err: [:child, :out]) do |io|
      result = io.read.chomp.strip
    end

    if result && result != "" && log_command
      logger.info("Finished [#{command_number}] with result: \n#{result.grey}")
    end

    if $?.exitstatus != 0
      raise ShellError, "Shell command failed: #{command}\r\n#{result}"
    end

    result
  end

  def sync(local_path, remote_path, exclude: nil)
    rsync_commands.rsync(self, local_path, remote_path, exclude: exclude)
  end

  def read(file_path)
    File.read(file_path)
  end

  def write(file_path, content)
    ensure_directory_exists(file_path)

    File.write(file_path, content)

    logger.info("Created file #{file_path.to_s.cyan}\r\n#{content.grey}")

    true
  end

  def delete(file_path)
    exec!("rm #{file_path}")
  end

  def file_exists?(file_path)
    exec!("test -f #{file_path} && echo 'true' || echo 'false'", log_command: false) == 'true'
  end

  def dir_exists?(dir_path)
    exec!("test -d #{dir_path} && echo 'true' || echo 'false'", log_command: false) == 'true'
  end

  def recursive_list_files(path, name: nil)
    command = %Q{find -L #{path}  -type f}
    command += " -name #{name}" if name
    exec!(command).split(/[\r\n]+/)
  rescue => e
    if e.message.include?("No such file or directory")
      raise DirNotFoundError.new("Dir not found: #{path}")
    else
      raise e
    end
  end

  private
    def ensure_directory_exists(file_path)
      dir_path = File.dirname(file_path)

      unless Dir.exists?(dir_path)
        FileUtils.mkdir_p(dir_path)
      end
    end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
kuber_kit-0.2.3 lib/kuber_kit/shell/local_shell.rb
kuber_kit-0.2.2 lib/kuber_kit/shell/local_shell.rb
kuber_kit-0.2.1 lib/kuber_kit/shell/local_shell.rb
kuber_kit-0.2.0 lib/kuber_kit/shell/local_shell.rb
kuber_kit-0.1.9 lib/kuber_kit/shell/local_shell.rb