Project

General

Profile

Download (3.15 KB) Statistics
| Branch: | Tag: | Revision:
#--
# CyborgHood, a distributed system management software.
# Copyright (c) 2009-2010 Marc Dequènes (Duck) <Duck@DuckCorp.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#++

require 'shellwords'


module CyborgHood
class Command
attr_reader :cmdline, :cmdsplit, :parsing_errors

def initialize(cmdline, cmdsplit, parsing_errors = [])
@cmdline = cmdline
@cmdsplit = cmdsplit
@parsing_errors = parsing_errors
end

def valid?
@parsing_errors.empty?
end
end

class CommandParameter < String
attr_reader :content_type

def initialize(content, content_type = nil)
super(content)
@content_type = content_type
end

def content
to_s
end
end

class CommandParameterRef
attr_reader :reference

def initialize(reference)
@reference = reference
end
end

class Order
include I18nTranslation
attr_reader :error, :user, :commands, :shared_parameters

def initialize(params = {})
@error = params[:error]
@user = params[:user]
@commands = params[:commands]
@shared_parameters = params[:shared_parameters]
end

def valid?
@error.nil? and @user and not @commands.empty?
end
end

class OrderParser
include I18nTranslation

def initialize(user)
@user = user

@commands = []
@shared_parameters = {}
@used_refs = []
end

def parse(command_lines)
logger.debug "Parsing Order"
command_lines.each do |line|
line.strip!
# skip empty lines and comments
next if line == "" or line[0, 1] == "#"

errors = []
begin
raw_cmd_parts = line.shellsplit
rescue
errors << _("Syntax error in command.")
raw_cmd_parts = []
end
cmd_parts = raw_cmd_parts.collect do |word|
yield word, errors
end

@commands << Command.new(line, cmd_parts, errors)
end

# remove references to unused parameters
@shared_parameters.delete_if{|ref, param| not @used_refs.include?(ref) }

logger.debug "Order is OK"
Order.new(:user => @user, :commands => @commands, :shared_parameters => @shared_parameters)
end

def deref_param(param, old_ref = nil)
if param.is_a? CommandParameterRef
return deref_param(@shared_parameters[param.reference], param.reference)
elsif param.is_a? CommandParameter
return old_ref, param
elsif param.is_a? String or param.is_a? Fixnum
return deref_param(@shared_parameters[param], param)
else
nil
end
end
end
end
(8-8/8)