Move built-ins to a separate class

This commit is contained in:
Sami Samhuri 2022-01-16 14:46:11 -08:00
parent b141d95b44
commit 6e0b36fd21
No known key found for this signature in database
GPG key ID: 4B4195422742FC16
3 changed files with 34 additions and 29 deletions

View file

@ -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

View file

@ -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?

View file

@ -5,10 +5,6 @@ class ShellLogger
attr_reader :logs
def self.instance
@instance ||= new
end
def initialize
clear
end