# encoding: UTF-8 require 'yaml' module Clausewitz module Localisation class UnparseableFileError < StandardError attr_reader :errors def initialize(errors) @errors = errors end def message @errors.join("\n") end end class LangConfig attr_reader :name, :base, :dialects, :default_dialect def initialize(name, base, dialects, default_dialect = nil) @name = name @base = base @dialects = dialects @default_dialect = default_dialect @selected_dialect = @default_dialect end def clausewitz_name "l_#{@name}" end def select_dialect(dialect) if @dialects.include?(dialect.downcase) @selected_dialect = dialect else fail("Unknown dialect override '#{dialect}'!") end end def full_name @selected_dialect ? "#{@base}_#{@selected_dialect.upcase}" : @base end end LANG_MAP = { 'l_english' => LangConfig.new( 'english', 'en', %w[gb us ca], 'gb' ), 'l_french' => LangConfig.new( 'french', 'fr', %w[fr ca], 'fr' ), 'l_german' => LangConfig.new( 'german', 'de', %w[de], 'de' ), 'l_polish' => LangConfig.new( 'polish', 'pl', %w[pl], 'pl' ), 'l_braz_por' => LangConfig.new( 'braz_por', 'pt', %w[br], 'br' ), #'l_portuguese' => LangConfig.new( # 'portuguese', # 'pt', %w[br pt], 'pt' #), 'l_spanish' => LangConfig.new( 'spanish', 'es', %w[mx es], 'es' ), 'l_russian' => LangConfig.new( 'russian', 'ru', %w[ru], 'ru' ) } def self.parse(text) self.pre_validate(text) contents = {} current_lang = nil text.lines.each do |line| line.strip! next if line.empty? || line =~ /^#/ lang_match = LANG_MAP.keys.find { |lang| line == "#{lang}:" } if lang_match current_lang = lang_match next end unless current_lang errors = ["Cannot parse loc key without a langauge being set!"] fail(UnparseableFileError, errors) end key, value = line.split(/\s/, 2) key.gsub!(/:(\d+)?$/, '') value.gsub!(/(^"|"$)/, '') contents[current_lang] ||= {} contents[current_lang][key] = value end return contents end def self.pre_validate(text) errors = [] text.lines[1..-1].each_with_index do |line, index| lineno = index + 2 if line =~ /^\s*([\w\d.'-])+\:([0-9]+)?\"/ errors << "Line ##{lineno} is missing a space between the key and value." end if line.count('"').odd? errors << "Unmatched double quote on line ##{lineno}." end end fail(UnparseableFileError, errors) unless errors.empty? end def self.parse_file(filepath) contents = nil File.open(filepath, 'r:bom|UTF-8') do |f| contents = f.read end self.parse(contents) end def self.validate_localisation!(contents) fail("Unknown language keys!") unless contents.keys.all? do |lang| self.valid_lang?(lang) end end VALID_LANG_REGEX = /(#{LANG_MAP.keys.join('|')})/ def self.valid_lang?(lang) lang =~ VALID_LANG_REGEX end end end