mirror of
https://github.com/samsonjs/csc360-a1-shell.git
synced 2026-03-25 08:45:52 +00:00
Move built-ins to a separate class
This commit is contained in:
parent
b141d95b44
commit
6e0b36fd21
3 changed files with 34 additions and 29 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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?
|
||||
|
|
|
|||
|
|
@ -5,10 +5,6 @@ class ShellLogger
|
|||
|
||||
attr_reader :logs
|
||||
|
||||
def self.instance
|
||||
@instance ||= new
|
||||
end
|
||||
|
||||
def initialize
|
||||
clear
|
||||
end
|
||||
|
|
|
|||
Loading…
Reference in a new issue