From 6e0b36fd21ba9eec7e4efd380ff4fd516f4fc247 Mon Sep 17 00:00:00 2001 From: Sami Samhuri Date: Sun, 16 Jan 2022 14:46:11 -0800 Subject: [PATCH] Move built-ins to a separate class --- ruby/builtins.rb | 54 +++++++++++++++++++++++++------------------- ruby/main.rb | 5 ++-- ruby/shell_logger.rb | 4 ---- 3 files changed, 34 insertions(+), 29 deletions(-) diff --git a/ruby/builtins.rb b/ruby/builtins.rb index 0881e39..56a0ded 100644 --- a/ruby/builtins.rb +++ b/ruby/builtins.rb @@ -1,31 +1,39 @@ class Shell - def exec_builtin(name, args) - send(:"builtin_#{name}", args) - end + class Builtins + attr_reader :logger - def builtin?(name) - respond_to?(:"builtin_#{name}") - end + def initialize(logger) + @logger = logger + end - ################# - ### Built-ins ### - ################# + def exec(name, args) + send(:"builtin_#{name}", args) + end - def builtin_cd(args) - Dir.chdir args.first - end + def builtin?(name) + respond_to?(:"builtin_#{name}") + end - def builtin_export(args) - # only supports one variable and doesn't support quoting - name, *value_parts = args.first.strip.split('=') - if name.nil? || name.empty? - logger.warn "#{RED}[ERROR]#{CLEAR} Invalid export command" - else - ENV[name] = value_parts.join('=').gsub(/\$\w+/) { |m| ENV[m[1..]] || '' } + ################# + ### Built-ins ### + ################# + + def builtin_cd(args) + Dir.chdir args.first + end + + def builtin_export(args) + # only supports one variable and doesn't support quoting + name, *value_parts = args.first.strip.split('=') + if name.nil? || name.empty? + logger.warn "#{RED}[ERROR]#{CLEAR} Invalid export command" + else + ENV[name] = value_parts.join('=').gsub(/\$\w+/) { |m| ENV[m[1..]] || '' } + end + end + + def bulitin_pwd(_args) + puts Dir.pwd end end - - def bulitin_pwd(_args) - puts Dir.pwd - end end diff --git a/ruby/main.rb b/ruby/main.rb index 28e3e96..10696af 100755 --- a/ruby/main.rb +++ b/ruby/main.rb @@ -15,6 +15,7 @@ class Shell @logger = ShellLogger.new @options = parse_options(args) @jobs_by_pid = {} + @builtins = Builtins.new(@logger) logger.verbose "options: #{options.inspect}" end @@ -95,9 +96,9 @@ class Shell exit 0 when '' # noop - when builtin?(argv0) + when @builtins.builtin?(argv0) args.shift - exec_builtin(argv0, args) + @builtins.exec(argv0, args) else status = exec_command(cmd) print "#{RED}-#{status}-#{CLEAR} " unless status.zero? diff --git a/ruby/shell_logger.rb b/ruby/shell_logger.rb index 84ef5b8..73bd32c 100644 --- a/ruby/shell_logger.rb +++ b/ruby/shell_logger.rb @@ -5,10 +5,6 @@ class ShellLogger attr_reader :logs - def self.instance - @instance ||= new - end - def initialize clear end