repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
klimkin/fig
spec/parser_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'fig/application_configuration' require 'fig/not_yet_parsed_package' require 'fig/package_descriptor' require 'fig/package_parse_error' require 'fig/parser' describe 'Parser' do def new_configuration application_configuration = Fig::ApplicationConfiguration.new application_configuration.base_whitelisted_url = 'http://example/' application_configuration.remote_repository_url = 'http://example/' return application_configuration end def test_no_parse_exception(fig_input) application_configuration = new_configuration unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = Fig::PackageDescriptor.new('package_name', '0.1.1', nil) unparsed_package.working_directory = unparsed_package.include_file_base_directory = 'foo_directory' unparsed_package.source_description = 'source description' unparsed_package.unparsed_text = fig_input package = Fig::Parser.new(application_configuration, false).parse_package( unparsed_package ) # Got no exception. return package end def test_error(fig_input, error_class, message_pattern) application_configuration = new_configuration unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = Fig::PackageDescriptor.new('package_name', '0.1.1', nil) unparsed_package.working_directory = unparsed_package.include_file_base_directory = 'foo_directory' unparsed_package.source_description = 'source description' unparsed_package.unparsed_text = fig_input expect { Fig::Parser.new(application_configuration, false).parse_package( unparsed_package ) }.to raise_error(error_class, message_pattern) return end def test_user_input_error(fig_input, message_pattern) test_error(fig_input, Fig::UserInputError, message_pattern) return end def test_package_parse_error( fig_input, message_pattern = /source description/ ) test_error(fig_input, Fig::PackageParseError, message_pattern) return end describe 'base syntax' do it 'throws the correct exception on syntax error' do application_configuration = new_configuration unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = Fig::PackageDescriptor.new('package_name', '0.1.1', nil) unparsed_package.working_directory = unparsed_package.include_file_base_directory = 'foo_directory' unparsed_package.source_description = 'source description' unparsed_package.unparsed_text = <<-END this is invalid syntax END expect { Fig::Parser.new(application_configuration, false).parse_package( unparsed_package ) }.to raise_error( Fig::PackageParseError ) end it 'assigns the correct line and column number to Statement objects.' do fig_package=<<-FIG_PACKAGE # Blank line above to ensure that we can handle starting whitespace. resource http://example/is/awesome.tgz # Indentation in here is weird to test we get things right. # Also, we need a comment in here to make sure that cleaning them out # does not affect values for statements. archive http://svpsvn/my/repo/is/cool.jar config default include package/some-version set VARIABLE=VALUE end FIG_PACKAGE unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = Fig::PackageDescriptor.new('package_name', '0.1.1', nil) unparsed_package.working_directory = unparsed_package.include_file_base_directory = 'foo_directory' unparsed_package.source_description = 'source description' unparsed_package.unparsed_text = fig_package application_configuration = new_configuration package = Fig::Parser.new(application_configuration, false).parse_package( unparsed_package ) package.walk_statements do |statement| case statement when Fig::Statement::Resource statement.line.should == 3 statement.column.should == 9 when Fig::Statement::Archive statement.line.should == 10 statement.column.should == 10 when Fig::Statement::Configuration statement.line.should == 12 statement.column.should == 9 when Fig::Statement::Include statement.line.should == 13 statement.column.should == 17 when Fig::Statement::Set statement.line.should == 15 statement.column.should == 12 end end end end describe 'validating URLs' do it 'passes valid, whitelisted ones' do fig_package=<<-FIG_PACKAGE resource http://example/is/awesome.tgz archive http://svpsvn/my/repo/is/cool.jar FIG_PACKAGE application_configuration = new_configuration application_configuration.push_dataset( { 'url whitelist' => 'http://svpsvn/' } ) unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = Fig::PackageDescriptor.new('package_name', '0.1.1', nil) unparsed_package.working_directory = unparsed_package.include_file_base_directory = 'foo_directory' unparsed_package.source_description = 'source description' unparsed_package.unparsed_text = fig_package package = Fig::Parser.new(application_configuration, false).parse_package( unparsed_package ) package.should_not == nil end it 'rejects non-whitelisted ones' do fig_package=<<-FIG_PACKAGE resource http://evil_url/is/bad.tgz archive http://evil_repo/my/repo/is/bad.jar FIG_PACKAGE application_configuration = new_configuration application_configuration.push_dataset( { 'url whitelist' => 'http://svpsvn/' } ) unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = Fig::PackageDescriptor.new('package_name', '0.1.1', nil) unparsed_package.working_directory = unparsed_package.include_file_base_directory = 'foo_directory' unparsed_package.source_description = 'source description' unparsed_package.unparsed_text = fig_package exception = nil begin package = Fig::Parser.new(application_configuration, false).parse_package( unparsed_package ) rescue Fig::URLAccessDisallowedError => exception end exception.should_not == nil exception.urls.should =~ %w<http://evil_url/is/bad.tgz http://evil_repo/my/repo/is/bad.jar> exception.descriptor.name.should == 'package_name' exception.descriptor.version.should == '0.1.1' end end describe 'command statements' do %w< 0 1 >.each do |version| command_terminator = version.to_i == 0 ? '' : ' end' describe %Q<in the v#{version} grammar> do it 'reject multiple commands in config file' do input = <<-"END_PACKAGE" grammar v#{version} config default command "echo foo"#{command_terminator} command "echo bar"#{command_terminator} end END_PACKAGE test_user_input_error( input, /found a second "command" statement within a "config" block/i ) end it 'accept multiple configs, each with a single command' do test_no_parse_exception(<<-"END_PACKAGE") grammar v#{version} config default command "echo foo"#{command_terminator} end config another command "echo bar"#{command_terminator} end END_PACKAGE end it 'reject multiple configs where one has multiple commands' do input = <<-"END_PACKAGE" grammar v#{version} config default command "echo foo"#{command_terminator} end config another command "echo bar"#{command_terminator} command "echo baz"#{command_terminator} end END_PACKAGE test_user_input_error( input, /found a second "command" statement within a "config" block/i ) end end end end describe 'path statements' do { ';' => ';', ':' => ':', '"' => '"', '<' => '<', '>' => '>', '|' => '|', ' ' => ' ', '\t' => "\t", '\r' => "\r", '\n' => "\n" }.each do |display, character| it %Q<reject "#{display}" in a PATH component in the v0 grammar> do input = <<-"END_PACKAGE" grammar v0 config default append PATH_VARIABLE=#{character} end END_PACKAGE test_user_input_error( input, /(?i:invalid append statement).*\bPATH_VARIABLE\b/ ) end it %Q<accept "#{display}" in a PATH component in the v1 grammar> do right_hand_side = nil if character == '"' or character =~ /\s/ right_hand_side = %Q<'#{character}'> else right_hand_side = character end test_no_parse_exception(<<-"END_PACKAGE") grammar v1 config default append PATH_VARIABLE=#{right_hand_side} end END_PACKAGE end end end %w< archive resource >.each do |asset_type| describe "#{asset_type} statements" do %w< ' " >.each do |character| %w< 0 1 >.each do |version| it %Q<produce a parse error with unescaped «#{character}» in a URL in the v#{version} grammar> do input = <<-"END_PACKAGE" grammar v#{version} #{asset_type} #{character} END_PACKAGE test_package_parse_error(input) end end end %w[ @ < > | ].each do |character| it %Q<produce a parse error with «#{character}» in a URL in the v0 grammar> do input = <<-"END_PACKAGE" #{asset_type} #{character} END_PACKAGE test_package_parse_error(input) end %w< 1 >.each do |version| it %Q<handles «#{character}» in a URL in the v#{version} grammar> do package = test_no_parse_exception(<<-"END_PACKAGE") grammar v#{version} #{asset_type} foo#{character}bar config default end END_PACKAGE url = [package.archive_locations, package.resource_locations].flatten[0] url.should == "foo#{character}bar" end end end it %q<handles octothorpes in a URL in the v1 grammar> do package = test_no_parse_exception(<<-"END_PACKAGE") grammar v1 #{asset_type} 'foo#bar' config default end END_PACKAGE url = [package.archive_locations, package.resource_locations].flatten[0] url.should == 'foo#bar' end describe %Q<handles plus signs in the path (e.g. for C++ libraries)> do %w< 0 1 >.each do |version| it %Q<in the v#{version} grammar> do test_no_parse_exception(<<-"END_PACKAGE") grammar v#{version} #{asset_type} testlib++.whatever config default append LIBPATH=@/testlib++ end END_PACKAGE end end end end end end # vim: set fileencoding=utf8 :
klimkin/fig
lib/fig.rb
# coding: utf-8 module Fig VERSION = '1.25.0' end
klimkin/fig
lib/fig/command/action/role/has_sub_action.rb
<gh_stars>10-100 # coding: utf-8 module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::HasSubAction attr_accessor :sub_action def sub_action?() true end def check_sub_action_presence() return if sub_action raise 'Bug in code. Sub-action missing.' end def descriptor_requirement() check_sub_action_presence() return sub_action.descriptor_requirement() end def modifies_repository?() check_sub_action_presence() return sub_action.modifies_repository? end def load_base_package?() check_sub_action_presence() return sub_action.load_base_package? end def register_base_package?() check_sub_action_presence() return sub_action.register_base_package? end def apply_config?() check_sub_action_presence() return sub_action.apply_config? end def apply_base_config?() check_sub_action_presence() return sub_action.apply_base_config? end def configure(options) check_sub_action_presence() return sub_action.configure(options) end def execution_context=(context) check_sub_action_presence() sub_action.execution_context = context end def execute() check_sub_action_presence() return sub_action.execute() end end
klimkin/fig
lib/fig/protocol/file.rb
<reponame>klimkin/fig # coding: utf-8 require 'cgi' require 'fileutils' require 'find' require 'fig/file_not_found_error' require 'fig/logging' require 'fig/protocol' module Fig; end module Fig::Protocol; end # File transfers for the local filesystem. class Fig::Protocol::File include Fig::Protocol def download_list(uri) packages = [] unescaped_path = CGI.unescape uri.path return packages if ! ::File.exist?(unescaped_path) ls = '' Find.find(unescaped_path) { |file| if FileTest.directory? file ls << file.to_s ls << "\n" end } strip_paths_for_list(ls, packages, unescaped_path) return packages end # Determine whether we need to update something. Returns nil to indicate # "don't know". def path_up_to_date?(uri, path, prompt_for_login) begin unescaped_path = CGI.unescape uri.path if ::File.size(unescaped_path) != ::File.size(path) return false end if ::File.mtime(unescaped_path) <= ::File.mtime(path) return true end return false rescue Errno::ENOENT => error raise Fig::FileNotFoundError.new error.message, uri end end # Returns whether the file was not downloaded because the file already # exists and is already up-to-date. def download(uri, path, prompt_for_login) begin unescaped_path = CGI.unescape uri.path FileUtils.cp(unescaped_path, path) return true rescue Errno::ENOENT => error raise Fig::FileNotFoundError.new error.message, uri end end def upload(local_file, uri) unescaped_path = CGI.unescape uri.path FileUtils.mkdir_p(::File.dirname(unescaped_path)) FileUtils.cp(local_file, unescaped_path) return end end
klimkin/fig
lib/fig/command/action/list_variables/json_all_configs.rb
# coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/list_all_configs' require 'fig/command/action/role/list_as_json' require 'fig/command/action/role/list_from_data_structure' require 'fig/command/action/role/list_variables_from_data_structure' require 'fig/command/action/role/list_walking_dependency_tree' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListVariables; end class Fig::Command::Action::ListVariables::JSONAllConfigs include Fig::Command::Action include Fig::Command::Action::Role::ListAllConfigs include Fig::Command::Action::Role::ListAsJSON include Fig::Command::Action::Role::ListFromDataStructure include Fig::Command::Action::Role::ListVariablesFromDataStructure include Fig::Command::Action::Role::ListWalkingDependencyTree def options() return %w<--list-variables --json --list-all-configs> end end
klimkin/fig
spec/figrc_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'stringio' require 'tempfile' require 'fig/figrc' require 'fig/operating_system' require 'fig/repository' require 'fig/working_directory_maintainer' describe 'FigRC' do def create_override_file(foo, bar = nil) tempfile = Tempfile.new('some_json_tempfile') tempfile << %Q< { "foo" : "#{foo}" > if not bar.nil? tempfile << %Q< , "bar" : "#{bar}" > end tempfile << %Q< } > tempfile.close return tempfile end def create_override_file_with_repository_url() tempfile = Tempfile.new('some_json_tempfile') tempfile << %Q< { "default FIG_REMOTE_URL" : "#{FIG_REMOTE_URL}" } > tempfile.close return tempfile end def create_remote_config(foo, bar = nil) FileUtils.mkdir_p( File.join(FIG_REMOTE_DIR, Fig::Repository::METADATA_SUBDIRECTORY) ) figrc_path = File.join(FIG_REMOTE_DIR, Fig::FigRC::REPOSITORY_CONFIGURATION) file_handle = File.new(figrc_path,'w') file_handle.write( %Q< { "foo" : "#{foo}" > ) if not bar.nil? file_handle.write( %Q< , "bar" : "#{bar}" > ) end file_handle.write( %Q< } > ) file_handle.close return end def invoke_find(override_path, repository_url) return Fig::FigRC.find( override_path, repository_url, Fig::OperatingSystem.new(false), FIG_HOME, true ) end before(:all) do set_up_test_environment end after(:each) do clean_up_test_environment end it 'handles override path with a remote repository' do tempfile = create_override_file('loaded as override') create_remote_config("loaded from repository (shouldn't be)") configuration = invoke_find tempfile.path, FIG_REMOTE_URL tempfile.unlink configuration['foo'].should == 'loaded as override' end it 'handles no override, no repository (full stop)' do configuration = invoke_find nil, nil configuration['foo'].should == nil end it 'handles no override, repository specified as the empty string' do configuration = invoke_find nil, '' configuration['foo'].should == nil end it 'handles no override, repository specified as whitespace' do configuration = invoke_find nil, " \n\t" configuration['foo'].should == nil end it 'handles no repository config and no override specified, and config does NOT exist on server' do configuration = invoke_find nil, 'file:///does_not_exist/' configuration['foo'].should == nil end it 'retrieves configuration from repository with no override' do create_remote_config('loaded from repository') configuration = invoke_find nil, FIG_REMOTE_URL configuration['foo'].should == 'loaded from repository' end it 'has a remote config but gets its config from the override file provided' do create_remote_config('loaded from remote repository') tempfile = create_override_file('loaded as override to override remote config') configuration = invoke_find tempfile.path, FIG_REMOTE_URL configuration['foo'].should == 'loaded as override to override remote config' end it 'merges override file config over remote config' do create_remote_config('loaded from remote repository', 'should not be overwritten') tempfile = create_override_file('loaded as override to override remote config') configuration = invoke_find tempfile.path, FIG_REMOTE_URL configuration['foo'].should == 'loaded as override to override remote config' configuration['bar'].should == 'should not be overwritten' end it 'retrieves configuration from repository specified by override file' do tempfile = create_override_file_with_repository_url create_remote_config('loaded from repository') configuration = invoke_find tempfile.path, nil configuration['foo'].should == 'loaded from repository' end end
klimkin/fig
lib/fig/non_repository_packages.rb
# coding: utf-8 require 'fig/not_yet_parsed_package' require 'fig/package_descriptor' module Fig; end class Fig::NonRepositoryPackages def initialize(parser) @parser = parser reset_cached_data return end def reset_cached_data @packages_by_path = {} return end def [](file_path) file_path = File.expand_path file_path if package = @packages_by_path[file_path] return package end if ! File.exist? file_path return end load_package file_path return @packages_by_path[file_path] end private def load_package(file_path) content = File.read file_path descriptor = Fig::PackageDescriptor.new(nil, nil, nil, :file_path => file_path) unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = descriptor unparsed_package.working_directory = unparsed_package.include_file_base_directory = File.dirname(file_path) unparsed_package.source_description = file_path unparsed_package.unparsed_text = content package = @parser.parse_package unparsed_package @packages_by_path[file_path] = package return end end
klimkin/fig
lib/fig/string_tokenizer.rb
# coding: utf-8 require 'fig/tokenized_string' require 'fig/tokenized_string/plain_segment' module Fig; end class Fig::StringTokenizer # subexpression_matchers is an array of hashes. Each hash is expected to # contain two keys: :pattern and :action. # # The :pattern value needs to be a regular expression for the substring that # needs special handling. # # The :action value needs to be a block that takes two parameters. # # The first parameter is the text that was matched and the second is the # error block passed to #tokenize(). # # On success the block returns either a String containing replacement text or # a Fig::TokenizedString::Token representing the special handling of the # consumed text. If there was a problem, then the error block should have # been invoked and the block should return nil. # # # metacharacters is a regular expression character class for characters that # need to be escaped when un-single quoting a string. def initialize(subexpression_matchers = [], metacharacters = '') @subexpression_matchers = subexpression_matchers @metacharacters = metacharacters return end # Takes a block that is invoked when there is an error. Block receives a # single parameter of an error message that is the end of a statement # describing the problem, with no leading space character. For example, # given «'foo», the block will receive a message like 'has unbalanced single # quotes.'. # # Returns the TokenizedString; if there was a parse error, then the return # value will be nil (and the block will have been invoked). def tokenize(string, &error_block) @string = string.dup @error_block = error_block @single_quoted = nil @segments = [] strip_quotes_and_process_escapes return if @segments.empty? return Fig::TokenizedString.new(@segments, @single_quoted, @metacharacters) end private def strip_quotes_and_process_escapes() if @string.length == 0 @single_quoted = false @segments << Fig::TokenizedString::PlainSegment.new('') return end @single_quoted = strip_single_quotes_and_process_escapes return if @single_quoted.nil? if @single_quoted @segments << Fig::TokenizedString::PlainSegment.new(@string.clone) return end strip_double_quotes_and_process_escapes return end def strip_single_quotes_and_process_escapes() return false if @string[0..0] != %q<'> && @string[-1..-1] != %q<'> return false if @string =~ %r< # «\'» is legal \A ( [^\\']* (?: \\{2} )* \\ ' )* \z >x if ( @string.length == 1 || @string[0..0] != %q<'> || @string[-1..-1] != %q<'> || @string =~ %r< [^\\] (?: \\{2} )* (?: \\ | ' .* ) ' \z >x ) @error_block.call 'has unbalanced single quotes.' return end if @string =~ %r< [^\\] (?: \\{2} )*? \\ ([^\\']) >x @error_block.call( "contains a bad escape sequence (\\#{$1}) inside single quotes." ) return end @string.sub!( %r< \A ' (.*) ' \z >xm, '\1') return true end def strip_double_quotes_and_process_escapes() was_quoted = check_and_strip_double_quotes return if was_quoted.nil? if @string == %q<\\'> @segments << Fig::TokenizedString::PlainSegment.new(%q<'>) return end generate_segments was_quoted return end def check_and_strip_double_quotes() # We accept any unquoted single character at this point. Later validation # will catch bad characters. return false if @string =~ %r< \A \\ . \z >xm if @string[0..0] == %q<"> if @string.length == 1 || @string[-1..-1] != %q<"> @error_block.call 'has unbalanced double quotes.' return end if @string =~ %r< [^\\] (?: \\{2} )*? \\ " \z >xm @error_block.call \ 'has unbalanced double quotes; the trailing double quote is escaped.' return end @string.sub!( %r< \A " (.*) " \z >xm, '\1' ) return true elsif @string =~ %r< (?: \A | [^\\] ) (?: \\{2} )* " \z >xm @error_block.call \ %q<has unbalanced double quotes; it ends in a double quote when it didn't start with one.> return end return false end def generate_segments(was_quoted) plain_string = nil while ! @string.empty? if @string =~ %r< \A (\\+) ([^\\] .*)? \z >xm slashes, remainder = $1, $2 if slashes.length % 2 == 1 if remainder.nil? @error_block.call 'ends in an incomplete escape.' return end subexpression_matched = subexpression_match(remainder) return if subexpression_matched.nil? if ( subexpression_matched || remainder[0..0] == %q<"> || ! was_quoted && remainder[0..0] == %q<'> ) plain_string ||= '' plain_string << slashes plain_string << remainder[0..0] @string = remainder[1..-1] || '' else @error_block.call \ "contains a bad escape sequence (\\#{remainder[0..0]})." return end else plain_string ||= '' plain_string << slashes @string = remainder end else replacement, remainder = subexpression_match @string return if replacement.nil? if replacement if replacement.is_a? String plain_string << replacement else if ! plain_string.nil? @segments << Fig::TokenizedString::PlainSegment.new(plain_string) plain_string = nil end @segments << replacement end @string = remainder elsif @string =~ %r< \A " >xm @error_block.call 'contains an unescaped double quote.' return elsif ! was_quoted && @string =~ %r< \A ' >xm @error_block.call 'contains an unescaped single quote.' return else plain_string ||= '' plain_string << @string[0..0] @string = @string[1..-1] || '' end end end if plain_string @segments << Fig::TokenizedString::PlainSegment.new(plain_string) end return end def subexpression_match(sub_string) @subexpression_matchers.each do |matcher| pattern = matcher[:pattern] if sub_string =~ %r< \A ( #{pattern} ) >x subexpression, remainder = $1, $' replacement = matcher[:action].call subexpression, @error_block return if ! replacement return [replacement, remainder] end end return false end end
klimkin/fig
lib/fig/package_descriptor_parse_error.rb
<reponame>klimkin/fig<gh_stars>10-100 # coding: utf-8 require 'fig/user_input_error' module Fig # Could not turn a string into a PackageDescriptor. class PackageDescriptorParseError < UserInputError attr_reader :original_string def initialize(message, original_string) super(message) @file = original_string return end end end
klimkin/fig
lib/fig/environment_variables.rb
# coding: utf-8 module Fig; end; # Abstract manager of a set of environment variables. module Fig::EnvironmentVariables def initialize(variables_override = nil) @variables = variables_override || get_system_environment_variables end def empty? return @variables.empty? end def keys return @variables.keys end def with_environment original_environment = {} original_environment.merge!(ENV.to_hash) begin set_system_environment_variables(@variables) yield ensure ENV.clear set_system_environment_variables(original_environment) end return end private def get_system_environment_variables vars = {} ENV.each { |key,value| vars[key]=value } return vars end def set_system_environment_variables(variables) variables.each { |key, value| ENV[key] = value } end end
klimkin/fig
lib/fig/command/action/publish.rb
# coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' require 'fig/command/action/role/publish' require 'fig/logging' require 'fig/user_input_error' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::Publish include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction include Fig::Command::Action::Role::Publish def options() return %w<--publish> end def remote_operation_necessary?() return true end def execute() publish_preflight() Fig::Logging.info "Checking status of #{@descriptor.to_string()}..." package_description = Fig::PackageDescriptor.format(@descriptor.name, @descriptor.version, nil) if @execution_context.repository.list_remote_packages.include?( package_description ) Fig::Logging.info "#{@descriptor.to_string()} has already been published." if not @force raise Fig::UserInputError.new( 'Use the --force option if you really want to overwrite.' ) else Fig::Logging.info 'Overwriting...' end end Fig::Logging.info "Publishing #{@descriptor.to_string()}." @execution_context.repository.publish_package( @publish_statements, @descriptor, false, @execution_context.base_package, @force ) return EXIT_SUCCESS end end
klimkin/fig
lib/fig/parser_package_build_state.rb
<filename>lib/fig/parser_package_build_state.rb # coding: utf-8 require 'fig/package' require 'fig/package_parse_error' require 'fig/statement' require 'fig/statement/archive' require 'fig/statement/command' require 'fig/statement/configuration' require 'fig/statement/grammar_version' require 'fig/statement/include' require 'fig/statement/include_file' require 'fig/statement/override' require 'fig/statement/path' require 'fig/statement/resource' require 'fig/statement/retrieve' require 'fig/statement/set' module Fig; end # The state of a Package while it is being built by a Parser. class Fig::ParserPackageBuildState def initialize(grammar_version, descriptor, source_description) @grammar_version = grammar_version @descriptor = descriptor @source_description = source_description end def node_location(node) offset_from_start_of_file = node.interval.first input = node.input return [ input.line_of(offset_from_start_of_file), input.column_of(offset_from_start_of_file) ] end # This method is necessary due to ruby v1.8 not allowing array splat # notation, i.e. Fig::Statement.position_description(*node_location(node), # source_description) def node_location_description(node) location = node_location(node) return Fig::Statement.position_description( location[0], location[1], @source_description ) end def new_package_statement(unparsed_package, grammar_node, statement_nodes) grammar_statement = nil if grammar_node && ! grammar_node.empty? grammar_statement = grammar_node.to_package_statement(self) else grammar_statement = Fig::Statement::GrammarVersion.new( nil, %Q<[synthetic statement created in #{__FILE__} line #{__LINE__}]>, 0 # Grammar version ) end statement_objects = [grammar_statement] statement_nodes.elements.each do |node| statement_objects << node.to_package_statement(self) end package = Fig::Package.new( @descriptor.name, @descriptor.version, @descriptor.file_path, @descriptor.description, unparsed_package.working_directory, unparsed_package.include_file_base_directory, statement_objects, false, ) package.unparsed_text = unparsed_package.unparsed_text return package end def new_grammar_version_statement(keyword_node, version_node) return Fig::Statement::GrammarVersion.new( node_location(keyword_node), @source_description, version_node.text_value.to_i ) end def new_asset_statement(statement_class, keyword_node, location_node) raw_location = location_node.text_value tokenized_location = statement_class.validate_and_process_escapes_in_location(raw_location) do |error_description| raise_invalid_value_parse_error( keyword_node, location_node, 'URL/path', error_description ) end location = tokenized_location.to_expanded_string need_to_glob = ! tokenized_location.single_quoted? return statement_class.new( node_location(keyword_node), @source_description, location, need_to_glob ) end def new_retrieve_statement(keyword_node, variable_name_node, path_node) tokenized_path = Fig::Statement::Retrieve.tokenize_path(path_node.text_value) do |error_description| raise_invalid_value_parse_error( keyword_node, path_node, 'path', error_description ) end return Fig::Statement::Retrieve.new( node_location(keyword_node), @source_description, variable_name_node.text_value, tokenized_path ) end def new_configuration_statement(keyword_node, name_node, statements) statement_objects = statements.elements.map do |statement| statement.to_config_statement(self) end return Fig::Statement::Configuration.new( node_location(keyword_node), @source_description, name_node.text_value, statement_objects ) end def new_include_statement(keyword_node, descriptor_node) include_descriptor = Fig::Statement::Include.parse_descriptor( descriptor_node.text_value.strip, :source_description => node_location_description(descriptor_node), :validation_context => ' for an include statement' ) return Fig::Statement::Include.new( node_location(keyword_node), @source_description, include_descriptor, nil, @descriptor ) end def new_include_file_statement(keyword_node, path_node, config_name_node) path, config_name = Fig::Statement::IncludeFile.validate_and_process_raw_path_and_config_name( path_node.text_value, config_name_node.nil? ? nil : config_name_node.text_value, ) do |description| value_text = path_node.text_value if ! config_name_node.nil? value_text << ':' value_text << config_name_node.text_value end raise Fig::PackageParseError.new( %Q<Invalid include-file statement: "#{value_text}" #{description}#{node_location_description(path_node)}> ) end return Fig::Statement::IncludeFile.new( node_location(keyword_node), @source_description, path, config_name, @descriptor, ) end def new_override_statement(keyword_node, descriptor_node) override_descriptor = Fig::Statement::Override.parse_descriptor( descriptor_node.text_value.strip, :source_description => node_location_description(descriptor_node), :validation_context => ' for an override statement' ) return Fig::Statement::Override.new( node_location(keyword_node), @source_description, override_descriptor.name, override_descriptor.version ) end def new_environment_variable_statement( statement_class, keyword_node, value_node ) name = value = nil if @grammar_version == 0 name, value = statement_class.parse_v0_name_value(value_node.text_value) { |description| raise_invalid_statement_parse_error( keyword_node, value_node, description ) } else name, value = statement_class.parse_name_value(value_node.text_value) { |description| raise_invalid_statement_parse_error( keyword_node, value_node, description ) } end return statement_class.new( node_location(keyword_node), @source_description, name, value ) end def new_v0_command_statement(keyword_node, command_line_node) tokenized_command = Fig::Statement::Command.validate_and_process_escapes_in_argument( command_line_node.text_value ) { |description| raise_invalid_statement_parse_error( keyword_node, command_line_node, description ) } return Fig::Statement::Command.new( node_location(keyword_node), @source_description, [tokenized_command] ) end def new_v1_command_statement(keyword_node, command_line) return Fig::Statement::Command.new( node_location(keyword_node), @source_description, tokenize_v1_command_line(keyword_node, command_line) ) end private def raise_invalid_value_parse_error( keyword_node, value_node, value_name, description ) raise Fig::PackageParseError.new( %Q<Invalid #{value_name} for #{keyword_node.text_value} statement: "#{value_node.text_value}" #{description}#{node_location_description(value_node)}> ) end def raise_invalid_statement_parse_error(keyword_node, value_node, description) raise Fig::PackageParseError.new( %Q<Invalid #{keyword_node.text_value} statement: "#{value_node.text_value}" #{description}#{node_location_description(value_node)}> ) end def tokenize_v1_command_line(keyword_node, command_line) tokenized_command_line = [] command_line.each do |argument_node| unparsed = argument_node.text_value next if unparsed.empty? tokenized_command_line << Fig::Statement::Command.validate_and_process_escapes_in_argument( unparsed ) { |description| raise_invalid_statement_parse_error( keyword_node, argument_node, description ) } end return tokenized_command_line end end
klimkin/fig
lib/fig/tokenized_string/token.rb
<filename>lib/fig/tokenized_string/token.rb # coding: utf-8 module Fig; end class Fig::TokenizedString; end class Fig::TokenizedString::Token attr_reader :type attr_reader :raw_value def initialize(type, raw_value) @type = type @raw_value = raw_value return end def to_expanded_string(&block) return block.call self end def to_escaped_string() return raw_value end def to_double_quotable_string(metacharacters) return raw_value end def to_single_quoted_string() raise NotImplementedError.new 'Cannot single-quote a token.' end end
klimkin/fig
lib/fig/statement/archive.rb
# coding: utf-8 require 'fig/statement' require 'fig/statement/asset' module Fig; end class Fig::Statement; end # Specifies an archive file (possibly via a URL) that is part of a package. # # Differs from a Resource in that the contents will be extracted. class Fig::Statement::Archive < Fig::Statement include Fig::Statement::Asset def initialize(line_column, source_description, location, glob_if_not_url) super(line_column, source_description) @location = location @glob_if_not_url = glob_if_not_url end def statement_type() return 'archive' end def asset_name() return standard_asset_name() end def deparse_as_version(deparser) return deparser.archive(self) end end
klimkin/fig
lib/fig/command/action/role/list_dependencies_from_data_structure.rb
<filename>lib/fig/command/action/role/list_dependencies_from_data_structure.rb # coding: utf-8 module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListDependenciesFromDataStructure private def node_content(package, config_name) return new_package_config_hash package, config_name end end
klimkin/fig
lib/fig/command/action/dump_package_definition_parsed.rb
<filename>lib/fig/command/action/dump_package_definition_parsed.rb # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' require 'fig/package_definition_text_assembler' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::DumpPackageDefinitionParsed include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction def options() return %w<--dump-package-definition-parsed> end def descriptor_requirement() return nil end def modifies_repository?() return false end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config?() return nil # don't care end def execute() if @execution_context.synthetic_package_for_command_line # Purposely syntactically incorrect so that nothing attempts to round # trip this. puts "---- synthetic package for command-line ----\n" dump_package @execution_context.synthetic_package_for_command_line puts "\n---- base package ----\n" end dump_package @execution_context.base_package return EXIT_SUCCESS end private def dump_package(package) text_assembler = Fig::PackageDefinitionTextAssembler.new :emit_as_input text_assembler.add_output package.statements unparsed, * = text_assembler.assemble_package_definition print unparsed return end end
klimkin/fig
lib/fig/network_error.rb
<filename>lib/fig/network_error.rb # coding: utf-8 require 'fig/user_input_error' module Fig # A problem with file transfer over the network. class NetworkError < UserInputError end end
klimkin/fig
lib/fig/protocol/sftp.rb
# coding: utf-8 require 'net/sftp' require 'fig/logging' require 'fig/network_error' require 'fig/package_descriptor' require 'fig/protocol' require 'fig/protocol/netrc_enabled' module Fig; end module Fig::Protocol; end # File transfers via SFTP class Fig::Protocol::SFTP include Fig::Protocol include Fig::Protocol::NetRCEnabled def initialize() initialize_netrc end def download_list(uri) package_versions = [] sftp_run(uri, :prompt_for_login) do |connection| connection.dir.foreach uri.path do |package_directory| if package_directory.directory? package_name = package_directory.name if package_name =~ Fig::PackageDescriptor::COMPONENT_PATTERN connection.dir.foreach "#{uri.path}/#{package_name}" do |version_directory| if version_directory.directory? version_name = version_directory.name if version_name =~ Fig::PackageDescriptor::COMPONENT_PATTERN package_versions << "#{package_name}/#{version_name}" end end end end end end end return package_versions end # Determine whether we need to update something. Returns nil to indicate # "don't know". def path_up_to_date?(uri, path, prompt_for_login) sftp_run(uri, prompt_for_login) do |connection| stat_attributes = connection.stat!(uri.path) if stat_attributes.size != ::File.size(path) return false end return stat_attributes.mtime.to_f <= ::File.mtime(path).to_f end return nil end # See https://github.com/net-ssh/net-sftp/issues/27 NET_SFTP_ISSUE_27_SIZE = 4294049792 # Returns whether the file was not downloaded because the file already # exists and is already up-to-date. def download(uri, path, prompt_for_login) sftp_run(uri, prompt_for_login) do |connection| begin # *sigh* Always call #stat!(), even if the local file does not exist # because #download!() throws Strings and not proper exception objects # when the remote path does not exist. stat = connection.stat!(uri.path) if ::File.exist?(path) && stat.mtime.to_f <= ::File.mtime(path).to_f Fig::Logging.debug "#{path} is up to date." return false end if stat.size >= NET_SFTP_ISSUE_27_SIZE Fig::Logging.warn( "#{uri} is #{stat.size} bytes in size, which is likely to trigger a Net::SFTP bug (https://github.com/net-ssh/net-sftp/issues/27). Fig may hang. If so, you will need to kill the process and switch file transfer protocols or figure out a way to repackage with smaller files." ) end log_download uri, path connection.download! uri.path, path return true rescue Net::SFTP::StatusException => error if error.code == Net::SFTP::Constants::StatusCodes::FX_NO_SUCH_FILE raise Fig::FileNotFoundError.new(error.message, uri) end raise error end end return end def upload(local_file, uri) sftp_run(uri, :prompt_for_login) do |connection| ensure_directory_exists connection, ::File.dirname(uri.path) connection.upload! local_file, uri.path end return end private def sftp_run(uri, prompt_for_login, &block) host = uri.host authentication = get_authentication_for host, prompt_for_login if ! authentication raise Fig::NetworkError.new "No authentication information for #{host}." end begin options = {:password => <PASSWORD>} port = uri.port if port options[:port] = port end Net::SFTP.start(host, authentication.username, options, &block) rescue Net::SSH::Exception => error raise Fig::NetworkError.new error.message rescue Net::SFTP::Exception => error raise Fig::NetworkError.new error.message end return end def ensure_directory_exists(connection, path) begin connection.lstat!(path) return rescue Net::SFTP::StatusException => error if error.code != Net::SFTP::Constants::StatusCodes::FX_NO_SUCH_FILE raise Fig::NetworkError.new( "Could not stat #{path}: #{response.message} (#{response.code})" ) end end if path == '/' raise Fig::NetworkError.new 'Root path does not exist.' end ensure_directory_exists connection, ::File.dirname(path) connection.mkdir! path return end end
klimkin/fig
lib/fig/command/package_applier.rb
# coding: utf-8 require 'fig/package' require 'fig/package_descriptor' module Fig; end class Fig::Command; end class Fig::Command::PackageApplier attr_reader :synthetic_package_for_command_line def initialize( base_package, environment, options, descriptor, base_config, package_source_description ) @base_package = base_package @environment = environment @options = options @descriptor = descriptor @base_config = base_config @package_source_description = package_source_description end def activate_retrieves() @base_package.retrieves.each do |statement| @environment.add_retrieve(statement) end return end def register_package_with_environment() @environment.register_package(@base_package) return end def apply_config_to_environment(ignore_base_config) begin @synthetic_package_for_command_line = synthesize_package_for_command_line_options(ignore_base_config) @environment.apply_config( @synthetic_package_for_command_line, Fig::Package::DEFAULT_CONFIG, nil ) rescue Fig::NoSuchPackageConfigError => exception make_no_such_package_exception_descriptive(exception) end return end private def config_was_specified_by_user() return ! @options.config().nil? || @descriptor && ! @descriptor.config().nil? end def synthesize_package_for_command_line_options(ignore_base_config) configuration_statements = [] if not ignore_base_config configuration_statements << Fig::Statement::Include.new( nil, %Q<[synthetic statement created in #{__FILE__} line #{__LINE__}]>, Fig::PackageDescriptor.new( @base_package.name(), @base_package.version(), @base_config, :file_path => @base_package.file_path, :description => @base_package.description ), @base_package, nil ) end configuration_statements << @options.environment_statements() configuration_statement = Fig::Statement::Configuration.new( nil, %Q<[synthetic statement created in #{__FILE__} line #{__LINE__}]>, Fig::Package::DEFAULT_CONFIG, configuration_statements.flatten() ) return Fig::Package.new( nil, # Name nil, # Version nil, # File path 'command-line', '.', # Working '.', # Base [configuration_statement], :is_synthetic ) end def make_no_such_package_exception_descriptive(exception) if not @descriptor make_no_such_package_exception_descriptive_without_descriptor(exception) end check_no_such_package_exception_is_for_command_line_package(exception) source = derive_exception_source() message = %Q<There's no "#{@base_config}" config#{source}.> config_names = exception.package.config_names if config_names.empty? message += ' Actually, there are no configs.' else example_config = config_names.size == 1 ? config_names[0] : 'some_existing_config' message += %q< Specify one that does like this: "> message += Fig::PackageDescriptor.format( @descriptor.name, @descriptor.version, example_config, ) message += %q<".> if config_names.size > 1 message += %Q< The valid configs are "#{config_names.join('", "')}".> end end raise Fig::UserInputError.new(message) end def make_no_such_package_exception_descriptive_without_descriptor(exception) raise exception if config_was_specified_by_user() raise exception if not exception.descriptor.nil? source = derive_exception_source() message = %Q<No config was specified and there's no "#{Fig::Package::DEFAULT_CONFIG}" config#{source}.> append_config_names message, @base_package.config_names() raise Fig::UserInputError.new(message) end def append_config_names(message, config_names) if config_names.size > 1 message += %Q< The valid configs are "#{config_names.join('", "')}".> elsif config_names.size == 1 message += %Q< The only config is "#{config_names[0]}".> else message += ' Actually, there are no configs.' end return end def check_no_such_package_exception_is_for_command_line_package(exception) descriptor = exception.descriptor raise exception if descriptor.name && descriptor.name != @descriptor.name raise exception if descriptor.version && descriptor.version != @descriptor.version raise exception if descriptor.config != @base_config return end def derive_exception_source() source = @package_source_description return source ? %Q< in #{source}> : '' end end
klimkin/fig
spec/command/environment_variables_spec.rb
<reponame>klimkin/fig # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'Fig' do describe 'environment variables' do before(:each) do clean_up_test_environment set_up_test_environment # These shouldn't matter because the commands shouldn't look at the repositories. set_local_repository_format_to_future_version() set_remote_repository_format_to_future_version() end it 'sets variable from command line' do fig(%w<--set FOO=BAR --get FOO>)[0].should == 'BAR' fig(%w<--set NO_VALUE_WITH_EQUALS= --list-variables>)[0].should == 'NO_VALUE_WITH_EQUALS=' fig(%w<--set NO_VALUE_WITHOUT_EQUALS --list-variables>)[0].should == 'NO_VALUE_WITHOUT_EQUALS=' end it 'sets variable from fig file' do input = <<-END config default set FOO=BAR end END fig(%w<--get FOO>, input)[0].should == 'BAR' end it 'appends variable from command line with --add' do fig(%w<--add PATH=foo --get PATH>).should == ["foo#{File::PATH_SEPARATOR}#{ENV['PATH']}", '', 0] end it 'appends variable from command line with --append' do fig(%w<--append PATH=foo --get PATH>).should == ["foo#{File::PATH_SEPARATOR}#{ENV['PATH']}", '', 0] end it 'appends variable from fig file' do input = <<-END config default add PATH=foo end END fig(%w<--get PATH>, input).should == ["foo#{File::PATH_SEPARATOR}#{ENV['PATH']}", '', 0] end it 'appends empty variable' do fig(%w<--append XYZZY=foo --get XYZZY>).should == ['foo', '', 0] end it %q<doesn't expand variables without packages> do fig(%w<--set FOO=@bar --get FOO>)[0].should == '@bar' end end end
klimkin/fig
spec/command/dump_package_definition_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'Fig' do describe 'package definition dumping' do before(:each) do clean_up_test_environment set_up_test_environment end describe '--dump-package-definition-text' do it %q<dumps the contents of a published package> do input = <<-END config default set FOO=BAR end END fig(%w<--publish foo/1.2.3>, input, :fork => false) out, err = fig(%w<foo/1.2.3 --dump-package-definition-text>, :fork => false) # Content from the input. out.should =~ /set FOO=BAR/ # Content that is added by publishing. out.should =~ /publishing information for/i err.should == '' end it %q<dumps the contents an unpublished package> do input = <<-END config default set FOO=BAR end END out, err = fig(%w<--dump-package-definition-text>, input, :fork => false) out.should == input.strip err.should == '' end it %q<fails if there is no text> do out, err, exit_code = fig( %w<--dump-package-definition-text>, :no_raise_on_error => true, :fork => false ) err.should =~ /no text/ out.should == '' exit_code.should_not == 0 end end describe '--dump-package-definition-parsed' do it %q<dumps the contents of a published package> do input = <<-END config default set FOO=BAR end END fig(%w<--publish foo/1.2.3>, input, :fork => false, :fork => false) out, err = fig(%w<foo/1.2.3 --dump-package-definition-parsed>, :fork => false) # Content from the input. out.should =~ /set FOO=BAR/ err.should == '' end it %q<dumps the contents an unpublished package> do input = <<-END config default set FOO=BAR end END out, err = fig(%w<--dump-package-definition-parsed>, input, :fork => false) [input, out].each do |string| string.gsub!(/^[ ]+/, '') string.gsub!(/[ ]+/, ' ') string.strip! end out.should be_include input err.should == '' end it %q<emits the synthetic package if there is no text> do out, err = fig(%w<--dump-package-definition-parsed>, :fork => false) out.should =~ / ^ \s* config \s+ default \s+ end \s* \z /x err.should == '' end end end end
klimkin/fig
lib/fig/command/action/get.rb
<filename>lib/fig/command/action/get.rb<gh_stars>10-100 # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::Get include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction def options() return %w<--get> end def descriptor_requirement() return nil end def modifies_repository?() return false end def load_base_package?() return true end def register_base_package?() return true end def apply_config?() return true end def apply_base_config?() return true end def configure(options) @variable = options.variable_to_get end def execute() # Ruby v1.8 emits "nil" for nil, whereas ruby v1.9 emits the empty # string, so, for consistency, we need to ensure that we always emit the # empty string. puts @execution_context.environment[@variable] || '' return EXIT_SUCCESS end end
klimkin/fig
lib/fig/log4r_config_error.rb
# coding: utf-8 require 'fig/user_input_error' module Fig # A problem with configuring Log4r. class Log4rConfigError < UserInputError attr_reader :config_file, :original_exception def initialize(config_file, original_exception) super( %Q<Problem with #{config_file}: #{original_exception.message}> ) @config_file = config_file @original_exception = original_exception end end end
klimkin/fig
lib/fig/command/action/dump_package_definition_text.rb
# coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::DumpPackageDefinitionText include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction def options() return %w<--dump-package-definition-text> end def descriptor_requirement() return nil end def modifies_repository?() return false end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config?() return nil # don't care end def execute() text = @execution_context.base_package.unparsed_text if text puts text.strip # Ensure one and only one ending newline. return EXIT_SUCCESS end $stderr.puts %q<There's no text for the package.> return EXIT_FAILURE end end
klimkin/fig
lib/fig/repository_error.rb
# coding: utf-8 require 'fig/user_input_error' module Fig # A problem within/related to a repository. class RepositoryError < UserInputError end end
klimkin/fig
spec/deparser/v1_spec.rb
<reponame>klimkin/fig # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'fig/deparser/v1' require 'fig/statement/archive' require 'fig/statement/resource' describe Fig::Deparser::V1 do let(:deparser) { Fig::Deparser::V1.new :emit_as_input, '<indent>', 1 } describe 'deparses' do { Fig::Statement::Archive => 'archive', Fig::Statement::Resource => 'resource', }.each_pair do |statement_class, keyword| describe keyword do it %q<«chocolate*pizza» with globbing> do statement = statement_class.new(nil, nil, 'chocolate*pizza', :glob_if_not_url) deparser.deparse([statement]).should == %Q[<indent>#{keyword} "chocolate*pizza"\n] end it %q<«chocolate*pizza» without globbing> do statement = statement_class.new(nil, nil, 'chocolate*pizza', false) deparser.deparse([statement]).should == %Q[<indent>#{keyword} 'chocolate*pizza'\n] end it %q<«chocolate\\pizza» with globbing> do statement = statement_class.new(nil, nil, 'chocolate\\pizza', :glob_if_not_url) deparser.deparse([statement]).should == %Q[<indent>#{keyword} "chocolate\\\\pizza"\n] end it %q<«chocolate\\pizza» without globbing> do statement = statement_class.new(nil, nil, 'chocolate\\pizza', false) deparser.deparse([statement]).should == %Q[<indent>#{keyword} 'chocolate\\\\pizza'\n] end it %q<«chocolate'"pizza»> do statement = statement_class.new(nil, nil, %q<chocolate'"pizza>, false) deparser.deparse([statement]).should == %Q[<indent>#{keyword} 'chocolate\\'"pizza'\n] end end end end end # vim: set fileencoding=utf8 :
klimkin/fig
spec/command/listing_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'English' require 'fig/command/package_loader' def set_up_local_and_remote_repository cleanup_home_and_remote input = <<-END_INPUT config default set FOO=BAR end config nondefault set FOO=BAZ end END_INPUT fig(%w<--publish prerequisite/1.2.3>, input) input = <<-END_INPUT config default include prerequisite/1.2.3 set FOO=BAR end config nondefault include prerequisite/1.2.3 set FOO=BAZ end END_INPUT fig(%w<--publish remote-only/1.2.3>, input) fig(%w<--clean remote-only/1.2.3>) fig(%w<--publish both/1.2.3>, input) fig(%w<--publish-local local-only/1.2.3>, input) return end def set_up_local_and_remote_repository_with_depends_on_everything set_up_local_and_remote_repository input = <<-END_INPUT config default include :everything end config everything include prerequisite/1.2.3 include local-only/1.2.3 include remote-only/1.2.3 include both/1.2.3 end END_INPUT fig(%w<--publish depends-on-everything/1.2.3>, input) input = <<-END_INPUT config default end config indirectly-everything include depends-on-everything/1.2.3:everything end END_INPUT fig(%w<--publish depends-on-depends-on-everything/1.2.3>, input) fig( %w< --update-if-missing --include depends-on-depends-on-everything/1.2.3:indirectly-everything >, input ) return end def set_up_multiple_config_repository cleanup_home_and_remote # Note: make sure that configs within each package are NOT in sorted order. # Part of the output testing is ordering. input = <<-END_INPUT config default end END_INPUT fig(%w<--publish no-dependencies/1.2.3>, input) # Configs in "--publish"es below are required because there is no "default" # config in the packages. input = <<-END_INPUT config windows set OS=Windows end config ubuntu set OS=Linux end config redhat set OS=Linux end config unreferenced include this-should-not-show-up-in-any-output/45 end END_INPUT fig(%w<--publish operatingsystem/1.2.3:windows>, input) # Ensure we have a case where two different configs' dependencies conflict. fig(%w<--publish operatingsystem/3.4.5:redhat>, input) input = <<-END_INPUT config oracle include operatingsystem/1.2.3:redhat end config postgresql include operatingsystem/3.4.5:ubuntu end config sqlserver include operatingsystem/1.2.3:windows end config unreferenced include this-should-not-show-up-in-any-output/942.29024.2939.209.1 end config mysql include operatingsystem/1.2.3:ubuntu end END_INPUT fig(%w<--publish database/1.2.3:oracle>, input) input = <<-END_INPUT config apache include operatingsystem/1.2.3:redhat end config iis include operatingsystem/1.2.3:windows end config unreferenced include this-should-not-show-up-in-any-output/23.123.63.23 end config lighttpd include operatingsystem/3.4.5:ubuntu end END_INPUT fig(%w<--publish web/1.2.3:apache>, input) input = <<-END_INPUT config accounting include database/1.2.3:oracle include web/1.2.3:apache end config facilities include web/1.2.3:lighttpd include database/1.2.3:mysql end config marketing include database/1.2.3:postgresql include web/1.2.3:lighttpd end config legal include web/1.2.3:iis include database/1.2.3:sqlserver end END_INPUT fig(%w<--publish departments/1.2.3:accounting>, input) return end def create_package_dot_fig(package_name, config = nil) config = config ? config = ':' + config : '' File.open "#{CURRENT_DIRECTORY}/#{Fig::Command::PackageLoader::DEFAULT_PACKAGE_FILE}", 'w' do |handle| handle.print <<-END config default include #{package_name}/1.2.3#{config} end END end return end def create_package_dot_fig_with_single_dependency() create_package_dot_fig('prerequisite') end def create_package_dot_fig_with_all_dependencies() create_package_dot_fig( 'depends-on-everything', Fig::Package::DEFAULT_CONFIG ) end def set_up_list_variables_packages cleanup_home_and_remote input_a = <<-END_INPUT config default set A_BOTH_CONFIGS=default set A_DEFAULT=BAR set D_OVERRIDES_A=A set B_OVERRIDES_A_AND_C=A append A_PATH_DEFAULT=BAR append D_PATH_PREPENDS_A=A append B_PATH_PREPENDS_A_AND_C=A set A_SET_GETS_PREPENDED_WITH_B_AND_C=A # Note includes are not in alphabetical order in order to check that # sorting does or does not happen. include C/1.2.3 include B/1.2.3 set A_OVERRIDES_C_PREPENDING_B=A set A_OVERRIDES_B_AND_C=A set A_OVERRIDES_D=A append A_PATH_PREPENDS_B_AND_C=A append A_PATH_PREPENDS_D=A end config nondefault set A_BOTH_CONFIGS=nondefault set A_NONDEFAULT=BAZ include C/4.5.6:nondefault end END_INPUT input_b = <<-END_INPUT config default set B_DEFAULT=BAR set B_OVERRIDES_C=B set B_OVERRIDES_A_AND_C=B set A_OVERRIDES_B_AND_C=B append B_PATH_PREPENDS_A_AND_C=B append A_PATH_PREPENDS_B_AND_C=B append A_SET_GETS_PREPENDED_WITH_B_AND_C=B append A_OVERRIDES_C_PREPENDING_B=B # Note lack of version. That this works depends upon another include of # D to be encountered during parse to include the version. include D end config nondefault set B_NONDEFAULT=BAZ end config should_not_show_up_in_output set SHOULD_NOT_SHOW_UP_IN_OUTPUT_FROM_B=should_not_show_up end END_INPUT input_c123 = <<-END_INPUT config default set C_DEFAULT=BAR set B_OVERRIDES_C=C set B_OVERRIDES_A_AND_C=C set A_OVERRIDES_B_AND_C=C append B_PATH_PREPENDS_A_AND_C=C append A_PATH_PREPENDS_B_AND_C=C append A_SET_GETS_PREPENDED_WITH_B_AND_C=C append A_OVERRIDES_C_PREPENDING_B=C include D/1.2.3 end config nondefault set C_NONDEFAULT=BAZ end config should_not_show_up_in_output set SHOULD_NOT_SHOW_UP_IN_OUTPUT_FROM_C=should_not_show_up end END_INPUT input_c456 = <<-END_INPUT config default set C_DEFAULT=BAR set C_OVERRIDES_B=C set C_OVERRIDES_A_AND_B=C set A_OVERRIDES_B_AND_C=C append A_PATH_PREPENDS_B_AND_C=C append A_SET_GETS_PREPENDED_WITH_B_AND_C=C append A_OVERRIDES_C_PREPENDING_B=C include D/1.2.3 end config nondefault set C_ONLY_IN_C456=C end config should_not_show_up_in_output set SHOULD_NOT_SHOW_UP_IN_OUTPUT_FROM_C=should_not_show_up end END_INPUT input_d = <<-END_INPUT config default set D_DEFAULT=BAR set A_OVERRIDES_D=D set D_OVERRIDES_A=D append D_PATH_PREPENDS_A=D append A_PATH_PREPENDS_D=D include :addon_a include :addon_b include :addon_c end config addon_a set ADDON_A=ding end config addon_b set ADDON_B=dong include E/1.2.3 end config addon_c set ADDON_C=dang end config nondefault set D_NONDEFAULT=BAZ end config should_not_show_up_in_output set SHOULD_NOT_SHOW_UP_IN_OUTPUT_FROM_D=should_not_show_up end END_INPUT input_e = <<-END_INPUT config default end END_INPUT fig(%w<--publish E/1.2.3>, input_e) fig(%w<--publish D/1.2.3>, input_d) fig(%w<--publish C/1.2.3>, input_c123) fig(%w<--publish C/4.5.6>, input_c456) # Use non-default config to avoid issue with "include D" without a version. fig(%w<--publish B/1.2.3:nondefault>, input_b) fig(%w<--publish A/1.2.3>, input_a) end def set_up_packages_with_overrides cleanup_home_and_remote input_a = <<-END_INPUT config default include B/1.2.3 override C/4.5.6 override D/4.5.6 end END_INPUT input_b = <<-END_INPUT config default include C/1.2.3 include D/1.2.3 end END_INPUT input_c123 = <<-END_INPUT config default set C=1.2.3 include D/1.2.3 end END_INPUT input_c456 = <<-END_INPUT config default set C=4.5.6 include D/1.2.3 end END_INPUT input_d = <<-END_INPUT config default end END_INPUT fig(%w<--publish D/1.2.3>, input_d) fig(%w<--publish D/4.5.6>, input_d) fig(%w<--publish C/1.2.3>, input_c123) fig(%w<--publish C/4.5.6>, input_c456) fig(%w<--publish B/1.2.3>, input_b) fig(%w<--publish A/1.2.3>, input_a) end def remove_any_package_dot_fig FileUtils.rm_rf "#{CURRENT_DIRECTORY}/#{Fig::Command::PackageLoader::DEFAULT_PACKAGE_FILE}" return end def test_list_configs(package_name) set_up_local_and_remote_repository out, err = fig(['--list-configs', "#{package_name}/1.2.3"]) out.should == "default\nnondefault" err.should == '' return end # Allow for indenting in expected output given in heredocs. def clean_expected(expected) cleaned = expected.chomp indent_count = cleaned.scan(/ ^ [ ]+ /x).collect(&:length).min cleaned.gsub!(/ ^ [ ]{#{indent_count}} /x, '') return cleaned end describe 'Fig' do describe '--list-local' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<prints nothing with an empty repository> do out, err = fig(%w<--list-local>) out.should == '' err.should == '' end it %q<prints only local packages> do set_up_local_and_remote_repository out, err = fig(%w<--list-local>) out.should == "both/1.2.3\nlocal-only/1.2.3\nprerequisite/1.2.3" err.should == '' end it 'should complain if with a package descriptor' do out, err, exit_code = fig(%w<--list-local foo>, :no_raise_on_error => true) out.should be_empty err.should_not be_empty exit_code.should_not == 0 end it %q<should complain if local repository isn't in the expected format version> do set_local_repository_format_to_future_version() out, err, exit_code = fig(%w<--list-local>, :no_raise_on_error => true) err.should =~ /Local repository is in version \d+ format. This version of fig can only deal with repositories in version \d+ format\./ exit_code.should_not == 0 end end describe '--list-remote' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<prints nothing with an empty repository> do out, err = fig(%w<--list-remote>) out.should == '' err.should == '' end it %q<prints only remote packages> do set_up_local_and_remote_repository out, err = fig(%w<--list-remote>) out.should == "both/1.2.3\nprerequisite/1.2.3\nremote-only/1.2.3" err.should == '' end it 'should complain if with a package descriptor' do out, err, exit_code = fig(%w<--list-remote foo>, :no_raise_on_error => true) err.should_not be_empty exit_code.should_not == 0 end it %q<should complain if remote repository isn't in the expected format version> do set_remote_repository_format_to_future_version() out, err, exit_code = fig(%w<--list-remote>, :no_raise_on_error => true) err.should =~ /Remote repository is in version \d+ format. This version of fig can only deal with repositories in version \d+ format\./ exit_code.should_not == 0 end end describe '--list-configs' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<prints all the configurations for local-only> do test_list_configs('local-only') end it %q<prints all the configurations for both> do test_list_configs('both') end it %q<prints all the configurations for remote-only> do set_up_local_and_remote_repository out, err, exit_code = fig(%w<--list-configs remote-only/1.2.3>, :no_raise_on_error => true) exit_code.should_not == 0 err.should =~ /Fig file not found for package/ end end describe '--list-dependencies' do before(:each) do clean_up_test_environment set_up_test_environment cleanup_home_and_remote end describe 'no --list-tree' do describe 'no --list-all-configs' do it %q<lists nothing when there are no dependencies without a package.fig (and output is not a tty)> do set_up_local_and_remote_repository_with_depends_on_everything remove_any_package_dot_fig out, err = fig(%w<--list-dependencies prerequisite/1.2.3>) out.should == '' err.should == '' end it %q<lists only the single dependency and not all in the repository with a package.fig> do set_up_local_and_remote_repository_with_depends_on_everything create_package_dot_fig_with_single_dependency out, err = fig(%w<--list-dependencies>) out.should == 'prerequisite/1.2.3' err.should == '' end it %q<lists almost all packages in the repository without a package.fig> do set_up_local_and_remote_repository_with_depends_on_everything remove_any_package_dot_fig expected = clean_expected(<<-END_EXPECTED_OUTPUT) both/1.2.3 depends-on-everything/1.2.3 local-only/1.2.3 prerequisite/1.2.3 remote-only/1.2.3 END_EXPECTED_OUTPUT out, err = fig( %w< --list-dependencies depends-on-depends-on-everything/1.2.3:indirectly-everything > ) out.should == expected err.should == '' end it %q<lists all packages in the repository with a package.fig> do set_up_local_and_remote_repository_with_depends_on_everything create_package_dot_fig_with_all_dependencies expected = clean_expected(<<-END_EXPECTED_OUTPUT) both/1.2.3 depends-on-everything/1.2.3 local-only/1.2.3 prerequisite/1.2.3 remote-only/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies>) out.should == expected err.should == '' end end describe 'with --list-all-configs' do it %q<lists only the single configuration when there are no dependencies without a package.fig> do set_up_multiple_config_repository remove_any_package_dot_fig expected = clean_expected(<<-END_EXPECTED_OUTPUT) no-dependencies/1.2.3 END_EXPECTED_OUTPUT out, err = fig( %w<--list-dependencies --list-all-configs no-dependencies/1.2.3> ) out.should == expected err.should == '' end it %q<lists only the single dependency and not all in the repository with a package.fig> do set_up_multiple_config_repository create_package_dot_fig('no-dependencies') expected = clean_expected(<<-END_EXPECTED_OUTPUT) no-dependencies/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies --list-all-configs>) out.should == expected err.should == '' end it %q<lists all recursive configuration dependencies without a package.fig> do set_up_multiple_config_repository remove_any_package_dot_fig expected = clean_expected(<<-END_EXPECTED_OUTPUT) database/1.2.3:mysql database/1.2.3:oracle database/1.2.3:postgresql database/1.2.3:sqlserver departments/1.2.3:accounting departments/1.2.3:facilities departments/1.2.3:legal departments/1.2.3:marketing operatingsystem/1.2.3:redhat operatingsystem/1.2.3:ubuntu operatingsystem/1.2.3:windows operatingsystem/3.4.5:ubuntu web/1.2.3:apache web/1.2.3:iis web/1.2.3:lighttpd END_EXPECTED_OUTPUT out, err = fig( %w<--list-dependencies --list-all-configs departments/1.2.3:legal> ) out.should == expected err.should == '' end it %q<lists all packages in the repository with a package.fig> do set_up_local_and_remote_repository_with_depends_on_everything create_package_dot_fig_with_all_dependencies expected = clean_expected(<<-END_EXPECTED_OUTPUT) both/1.2.3 depends-on-everything/1.2.3 depends-on-everything/1.2.3:everything local-only/1.2.3 prerequisite/1.2.3 remote-only/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies --list-all-configs>) out.should == expected err.should == '' end end end describe 'with --list-tree' do describe 'no --list-all-configs' do it %q<lists the package when there are no dependencies without a package.fig (and output is not a tty)> do set_up_local_and_remote_repository_with_depends_on_everything remove_any_package_dot_fig out, err = fig(%w<--list-dependencies --list-tree prerequisite/1.2.3>) out.should == 'prerequisite/1.2.3' err.should == '' end it %q<lists only the package and the dependency and not all in the repository with a package.fig> do set_up_local_and_remote_repository_with_depends_on_everything create_package_dot_fig_with_single_dependency expected = clean_expected(<<-END_EXPECTED_OUTPUT) [package.fig] prerequisite/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies --list-tree>) out.should == expected err.should == '' end it %q<lists almost all packages in the repository without a package.fig> do set_up_local_and_remote_repository_with_depends_on_everything remove_any_package_dot_fig expected = clean_expected(<<-END_EXPECTED_OUTPUT) depends-on-depends-on-everything/1.2.3:indirectly-everything depends-on-everything/1.2.3:everything prerequisite/1.2.3 local-only/1.2.3 prerequisite/1.2.3 remote-only/1.2.3 prerequisite/1.2.3 both/1.2.3 prerequisite/1.2.3 END_EXPECTED_OUTPUT out, err = fig( %w< --list-dependencies --list-tree depends-on-depends-on-everything/1.2.3:indirectly-everything > ) out.should == expected err.should == '' end it %q<lists all packages in the repository with a package.fig> do set_up_local_and_remote_repository_with_depends_on_everything create_package_dot_fig_with_all_dependencies expected = clean_expected(<<-END_EXPECTED_OUTPUT) [package.fig] depends-on-everything/1.2.3 depends-on-everything/1.2.3:everything prerequisite/1.2.3 local-only/1.2.3 prerequisite/1.2.3 remote-only/1.2.3 prerequisite/1.2.3 both/1.2.3 prerequisite/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies --list-tree>) out.should == expected err.should == '' end end describe 'with --list-all-configs' do it %q<lists only the single configuration when there are no dependencies without a package.fig> do set_up_multiple_config_repository remove_any_package_dot_fig expected = clean_expected(<<-END_EXPECTED_OUTPUT) no-dependencies/1.2.3 END_EXPECTED_OUTPUT out, err = fig( %w< --list-dependencies --list-tree --list-all-configs no-dependencies/1.2.3 > ) out.should == expected err.should == '' end it %q<lists only the package and the dependency and not all in the repository with a package.fig> do set_up_multiple_config_repository create_package_dot_fig('no-dependencies') expected = clean_expected(<<-END_EXPECTED_OUTPUT) [package.fig] no-dependencies/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies --list-tree --list-all-configs>) out.should == expected err.should == '' end it %q<lists almost all packages in the repository without a package.fig> do set_up_multiple_config_repository remove_any_package_dot_fig expected = clean_expected(<<-END_EXPECTED_OUTPUT) departments/1.2.3:accounting database/1.2.3:oracle operatingsystem/1.2.3:redhat web/1.2.3:apache operatingsystem/1.2.3:redhat departments/1.2.3:facilities web/1.2.3:lighttpd operatingsystem/3.4.5:ubuntu database/1.2.3:mysql operatingsystem/1.2.3:ubuntu departments/1.2.3:marketing database/1.2.3:postgresql operatingsystem/3.4.5:ubuntu web/1.2.3:lighttpd operatingsystem/3.4.5:ubuntu departments/1.2.3:legal web/1.2.3:iis operatingsystem/1.2.3:windows database/1.2.3:sqlserver operatingsystem/1.2.3:windows END_EXPECTED_OUTPUT out, err = fig( %w< --list-dependencies --list-tree --list-all-configs departments/1.2.3 > ) out.should == expected err.should == '' end it %q<lists only the configs in a package.fig and not all configs in dependencies> do set_up_multiple_config_repository File.open "#{CURRENT_DIRECTORY}/#{Fig::Command::PackageLoader::DEFAULT_PACKAGE_FILE}", 'w' do |handle| handle.print <<-END config machineA include departments/1.2.3:marketing include departments/1.2.3:legal end config machineB include departments/1.2.3:facilities end END end expected = clean_expected(<<-END_EXPECTED_OUTPUT) [package.fig]:machineA departments/1.2.3:marketing database/1.2.3:postgresql operatingsystem/3.4.5:ubuntu web/1.2.3:lighttpd operatingsystem/3.4.5:ubuntu departments/1.2.3:legal web/1.2.3:iis operatingsystem/1.2.3:windows database/1.2.3:sqlserver operatingsystem/1.2.3:windows [package.fig]:machineB departments/1.2.3:facilities web/1.2.3:lighttpd operatingsystem/3.4.5:ubuntu database/1.2.3:mysql operatingsystem/1.2.3:ubuntu END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies --list-tree --list-all-configs>) out.should == expected err.should == '' end it %q<handles the case where a specific config may pick up a different dependency version depending upon the order in which it was reached.> do input_downstream = <<-END_INPUT # This path should work because there's a version of upstream # specified. config default include :include-upstream override upstream/standard end # This path should fail because there's no version of upstream # specified despite the fact that the walk of this file will end up # with the default config being hit before this one. config nondefault include :include-upstream end config include-upstream include upstream end END_INPUT input_upstream = <<-END_INPUT config default end END_INPUT fig(%w<--publish upstream/standard>, input_upstream) fig(%w<--publish upstream/non-standard>, input_upstream) fig(%w<--publish downstream/whatever>, input_downstream) expected = clean_expected(<<-END_EXPECTED_OUTPUT) downstream/whatever downstream/whatever:include-upstream upstream/standard downstream/whatever:nondefault downstream/whatever:include-upstream END_EXPECTED_OUTPUT out, err, exit_code = fig( %w< --list-dependencies --list-tree --list-all-configs downstream/whatever >, :no_raise_on_error => true ) out.should == expected err.should =~ /Cannot retrieve "upstream" without a version/ exit_code.should_not == 0 end end end it %q<handles "include ... override ..."> do set_up_packages_with_overrides remove_any_package_dot_fig expected = clean_expected(<<-END_EXPECTED_OUTPUT) B/1.2.3 C/4.5.6 D/4.5.6 END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies A/1.2.3>) out.should == expected err.should == '' end it %q<handles --config> do input_prerequisite = <<-END_INPUT config default end END_INPUT fig(%w<--publish prerequisite/1.2.3>, input_prerequisite) File.open "#{CURRENT_DIRECTORY}/#{Fig::Command::PackageLoader::DEFAULT_PACKAGE_FILE}", 'w' do |handle| handle.print <<-END config default # No version, which would cause load to fail if it is hit first. include prerequisite end config nondefault include prerequisite/1.2.3 include :default end END end expected = clean_expected(<<-END_EXPECTED_OUTPUT) prerequisite/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-dependencies --config nondefault>) out.should == expected err.should =~ /No version in the package descriptor of "prerequisite" in an include statement/ end it %q<should complain if local repository isn't in the expected format version> do set_up_packages_with_overrides remove_any_package_dot_fig set_local_repository_format_to_future_version out, err, exit_code = fig(%w<--list-dependencies A/1.2.3>, :no_raise_on_error => true) exit_code.should_not == 0 err.should =~ /Local repository is in version \d+ format. This version of fig can only deal with repositories in version \d+ format\./ end end describe '--list-variables' do describe 'no --list-tree' do describe 'no --list-all-configs' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<lists no dependency variables when none should exist without a package.fig> do set_up_list_variables_packages out, err = fig(%w<--list-variables E/1.2.3>) out.should == '' err.should == '' end it %q<lists no dependency variables when none should exist with a package.fig> do set_up_list_variables_packages create_package_dot_fig('E') out, err = fig(%w<--list-variables>) out.should == '' err.should == '' end it %q<lists all dependency variables without a package.fig> do set_up_list_variables_packages expected = clean_expected(<<-END_EXPECTED_OUTPUT) ADDON_A=ding ADDON_B=dong ADDON_C=dang A_BOTH_CONFIGS=default A_DEFAULT=BAR A_OVERRIDES_B_AND_C=A A_OVERRIDES_C_PREPENDING_B=A A_OVERRIDES_D=A A_PATH_DEFAULT=BAR A_PATH_PREPENDS_B_AND_C=A:B:C A_PATH_PREPENDS_D=A:D A_SET_GETS_PREPENDED_WITH_B_AND_C=B:C:A B_DEFAULT=BAR B_OVERRIDES_A_AND_C=B B_OVERRIDES_C=B B_PATH_PREPENDS_A_AND_C=B:C:A C_DEFAULT=BAR D_DEFAULT=BAR D_OVERRIDES_A=D D_PATH_PREPENDS_A=D:A END_EXPECTED_OUTPUT expected.gsub!(/:/,File::PATH_SEPARATOR) out, err = fig(%w<--list-variables A/1.2.3>) out.should == expected err.should =~ %r<No version in the package descriptor of "D" in an include statement in the \.fig file for "B/1\.2\.3" \(line> end it %q<lists all dependency variables with a package.fig> do set_up_list_variables_packages create_package_dot_fig('A') expected = clean_expected(<<-END_EXPECTED_OUTPUT) ADDON_A=ding ADDON_B=dong ADDON_C=dang A_BOTH_CONFIGS=default A_DEFAULT=BAR A_OVERRIDES_B_AND_C=A A_OVERRIDES_C_PREPENDING_B=A A_OVERRIDES_D=A A_PATH_DEFAULT=BAR A_PATH_PREPENDS_B_AND_C=A:B:C A_PATH_PREPENDS_D=A:D A_SET_GETS_PREPENDED_WITH_B_AND_C=B:C:A B_DEFAULT=BAR B_OVERRIDES_A_AND_C=B B_OVERRIDES_C=B B_PATH_PREPENDS_A_AND_C=B:C:A C_DEFAULT=BAR D_DEFAULT=BAR D_OVERRIDES_A=D D_PATH_PREPENDS_A=D:A END_EXPECTED_OUTPUT expected.gsub!(/:/,File::PATH_SEPARATOR) out, err = fig(%w<--list-variables>) out.should == expected err.should =~ %r<No version in the package descriptor of "D" in an include statement in the \.fig file for "B/1\.2\.3" \(line> end end describe 'with --list-all-configs' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<lists no dependency variables when none should exist without a package.fig> do set_up_list_variables_packages out, err = fig(%w<--list-variables --list-all-configs E/1.2.3>) out.should == '' err.should == '' end it %q<lists no dependency variables when none should exist with a package.fig> do set_up_list_variables_packages create_package_dot_fig('E') out, err = fig(%w<--list-variables --list-all-configs>) out.should == '' err.should == '' end it %q<lists all dependency variables without a package.fig> do set_up_list_variables_packages expected = clean_expected(<<-END_EXPECTED_OUTPUT) ADDON_A ADDON_B ADDON_C A_BOTH_CONFIGS A_DEFAULT A_NONDEFAULT A_OVERRIDES_B_AND_C A_OVERRIDES_C_PREPENDING_B A_OVERRIDES_D A_PATH_DEFAULT A_PATH_PREPENDS_B_AND_C A_PATH_PREPENDS_D A_SET_GETS_PREPENDED_WITH_B_AND_C B_DEFAULT B_OVERRIDES_A_AND_C B_OVERRIDES_C B_PATH_PREPENDS_A_AND_C C_DEFAULT C_ONLY_IN_C456 D_DEFAULT D_OVERRIDES_A D_PATH_PREPENDS_A END_EXPECTED_OUTPUT expected.gsub!(/:/,File::PATH_SEPARATOR) out, err = fig(%w<--list-variables --list-all-configs A/1.2.3>) out.should == expected err.should =~ %r<No version in the package descriptor of "D" in an include statement in the \.fig file for "B/1\.2\.3:default" \(line> end it %q<lists all dependency variables with a package.fig> do set_up_list_variables_packages create_package_dot_fig('A') expected = clean_expected(<<-END_EXPECTED_OUTPUT) ADDON_A ADDON_B ADDON_C A_BOTH_CONFIGS A_DEFAULT A_OVERRIDES_B_AND_C A_OVERRIDES_C_PREPENDING_B A_OVERRIDES_D A_PATH_DEFAULT A_PATH_PREPENDS_B_AND_C A_PATH_PREPENDS_D A_SET_GETS_PREPENDED_WITH_B_AND_C B_DEFAULT B_OVERRIDES_A_AND_C B_OVERRIDES_C B_PATH_PREPENDS_A_AND_C C_DEFAULT D_DEFAULT D_OVERRIDES_A D_PATH_PREPENDS_A END_EXPECTED_OUTPUT expected.gsub!(/:/,File::PATH_SEPARATOR) out, err = fig(%w<--list-variables --list-all-configs>) out.should == expected err.should =~ %r<No version in the package descriptor of "D" in an include statement in the \.fig file for "B/1\.2\.3:default" \(line> end end end describe 'with --list-tree' do describe 'no --list-all-configs' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<lists no dependency variables when none should exist without a package.fig> do set_up_list_variables_packages out, err = fig(%w<--list-variables --list-tree E/1.2.3>) out.should == 'E/1.2.3' err.should == '' end it %q<lists no dependency variables when none should exist with a package.fig> do set_up_list_variables_packages create_package_dot_fig('E') expected = clean_expected(<<-END_EXPECTED_OUTPUT) [package.fig] '---E/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-variables --list-tree>) out.should == expected err.should == '' end it %q<lists all dependency variables without a package.fig> do set_up_list_variables_packages expected = clean_expected(<<-END_EXPECTED_OUTPUT) A/1.2.3 | A_BOTH_CONFIGS = default | A_DEFAULT = BAR | D_OVERRIDES_A = A | B_OVERRIDES_A_AND_C = A | A_PATH_DEFAULT = BAR:$A_PATH_DEFAULT | D_PATH_PREPENDS_A = A:$D_PATH_PREPENDS_A | B_PATH_PREPENDS_A_AND_C = A:$B_PATH_PREPENDS_A_AND_C | A_SET_GETS_PREPENDED_WITH_B_AND_C = A | A_OVERRIDES_C_PREPENDING_B = A | A_OVERRIDES_B_AND_C = A | A_OVERRIDES_D = A | A_PATH_PREPENDS_B_AND_C = A:$A_PATH_PREPENDS_B_AND_C | A_PATH_PREPENDS_D = A:$A_PATH_PREPENDS_D '---C/1.2.3 | | C_DEFAULT = BAR | | B_OVERRIDES_C = C | | B_OVERRIDES_A_AND_C = C | | A_OVERRIDES_B_AND_C = C | | B_PATH_PREPENDS_A_AND_C = C:$B_PATH_PREPENDS_A_AND_C | | A_PATH_PREPENDS_B_AND_C = C:$A_PATH_PREPENDS_B_AND_C | | A_SET_GETS_PREPENDED_WITH_B_AND_C = C:$A_SET_GETS_PREPENDED_WITH_B_AND_C | | A_OVERRIDES_C_PREPENDING_B = C:$A_OVERRIDES_C_PREPENDING_B | '---D/1.2.3 | | D_DEFAULT = BAR | | A_OVERRIDES_D = D | | D_OVERRIDES_A = D | | D_PATH_PREPENDS_A = D:$D_PATH_PREPENDS_A | | A_PATH_PREPENDS_D = D:$A_PATH_PREPENDS_D | '---D/1.2.3:addon_a | | ADDON_A = ding | '---D/1.2.3:addon_b | | | ADDON_B = dong | | '---E/1.2.3 | '---D/1.2.3:addon_c | ADDON_C = dang '---B/1.2.3 | B_DEFAULT = BAR | B_OVERRIDES_C = B | B_OVERRIDES_A_AND_C = B | A_OVERRIDES_B_AND_C = B | B_PATH_PREPENDS_A_AND_C = B:$B_PATH_PREPENDS_A_AND_C | A_PATH_PREPENDS_B_AND_C = B:$A_PATH_PREPENDS_B_AND_C | A_SET_GETS_PREPENDED_WITH_B_AND_C = B:$A_SET_GETS_PREPENDED_WITH_B_AND_C | A_OVERRIDES_C_PREPENDING_B = B:$A_OVERRIDES_C_PREPENDING_B '---D/1.2.3 | D_DEFAULT = BAR | A_OVERRIDES_D = D | D_OVERRIDES_A = D | D_PATH_PREPENDS_A = D:$D_PATH_PREPENDS_A | A_PATH_PREPENDS_D = D:$A_PATH_PREPENDS_D '---D/1.2.3:addon_a | ADDON_A = ding '---D/1.2.3:addon_b | | ADDON_B = dong | '---E/1.2.3 '---D/1.2.3:addon_c ADDON_C = dang END_EXPECTED_OUTPUT out, err = fig(%w<--list-variables A/1.2.3 --list-tree>) out.should == expected err.should =~ %r<No version in the package descriptor of "D" in an include statement in the \.fig file for "B/1\.2\.3:default" \(line> end it %q<lists all dependency variables with a package.fig> do set_up_list_variables_packages create_package_dot_fig('A') expected = clean_expected(<<-END_EXPECTED_OUTPUT) [package.fig] '---A/1.2.3 | A_BOTH_CONFIGS = default | A_DEFAULT = BAR | D_OVERRIDES_A = A | B_OVERRIDES_A_AND_C = A | A_PATH_DEFAULT = BAR:$A_PATH_DEFAULT | D_PATH_PREPENDS_A = A:$D_PATH_PREPENDS_A | B_PATH_PREPENDS_A_AND_C = A:$B_PATH_PREPENDS_A_AND_C | A_SET_GETS_PREPENDED_WITH_B_AND_C = A | A_OVERRIDES_C_PREPENDING_B = A | A_OVERRIDES_B_AND_C = A | A_OVERRIDES_D = A | A_PATH_PREPENDS_B_AND_C = A:$A_PATH_PREPENDS_B_AND_C | A_PATH_PREPENDS_D = A:$A_PATH_PREPENDS_D '---C/1.2.3 | | C_DEFAULT = BAR | | B_OVERRIDES_C = C | | B_OVERRIDES_A_AND_C = C | | A_OVERRIDES_B_AND_C = C | | B_PATH_PREPENDS_A_AND_C = C:$B_PATH_PREPENDS_A_AND_C | | A_PATH_PREPENDS_B_AND_C = C:$A_PATH_PREPENDS_B_AND_C | | A_SET_GETS_PREPENDED_WITH_B_AND_C = C:$A_SET_GETS_PREPENDED_WITH_B_AND_C | | A_OVERRIDES_C_PREPENDING_B = C:$A_OVERRIDES_C_PREPENDING_B | '---D/1.2.3 | | D_DEFAULT = BAR | | A_OVERRIDES_D = D | | D_OVERRIDES_A = D | | D_PATH_PREPENDS_A = D:$D_PATH_PREPENDS_A | | A_PATH_PREPENDS_D = D:$A_PATH_PREPENDS_D | '---D/1.2.3:addon_a | | ADDON_A = ding | '---D/1.2.3:addon_b | | | ADDON_B = dong | | '---E/1.2.3 | '---D/1.2.3:addon_c | ADDON_C = dang '---B/1.2.3 | B_DEFAULT = BAR | B_OVERRIDES_C = B | B_OVERRIDES_A_AND_C = B | A_OVERRIDES_B_AND_C = B | B_PATH_PREPENDS_A_AND_C = B:$B_PATH_PREPENDS_A_AND_C | A_PATH_PREPENDS_B_AND_C = B:$A_PATH_PREPENDS_B_AND_C | A_SET_GETS_PREPENDED_WITH_B_AND_C = B:$A_SET_GETS_PREPENDED_WITH_B_AND_C | A_OVERRIDES_C_PREPENDING_B = B:$A_OVERRIDES_C_PREPENDING_B '---D/1.2.3 | D_DEFAULT = BAR | A_OVERRIDES_D = D | D_OVERRIDES_A = D | D_PATH_PREPENDS_A = D:$D_PATH_PREPENDS_A | A_PATH_PREPENDS_D = D:$A_PATH_PREPENDS_D '---D/1.2.3:addon_a | ADDON_A = ding '---D/1.2.3:addon_b | | ADDON_B = dong | '---E/1.2.3 '---D/1.2.3:addon_c ADDON_C = dang END_EXPECTED_OUTPUT out, err = fig(%w<--list-variables --list-tree>) out.should == expected err.should =~ %r<No version in the package descriptor of "D" in an include statement in the \.fig file for "B/1\.2\.3:default" \(line> end end describe 'with --list-all-configs' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<lists no dependency variables when none should exist without a package.fig> do set_up_list_variables_packages out, err = fig(%w<--list-variables --list-all-configs --list-tree E/1.2.3>) out.should == 'E/1.2.3' err.should == '' end it %q<lists no dependency variables when none should exist with a package.fig> do set_up_list_variables_packages create_package_dot_fig('E') expected = clean_expected(<<-END_EXPECTED_OUTPUT) [package.fig] '---E/1.2.3 END_EXPECTED_OUTPUT out, err = fig(%w<--list-variables --list-all-configs --list-tree>) out.should == expected err.should == '' end it %q<lists all dependency variables without a package.fig> do set_up_list_variables_packages expected = clean_expected(<<-END_EXPECTED_OUTPUT) A/1.2.3 | A_BOTH_CONFIGS = default | A_DEFAULT = BAR | D_OVERRIDES_A = A | B_OVERRIDES_A_AND_C = A | A_PATH_DEFAULT = BAR:$A_PATH_DEFAULT | D_PATH_PREPENDS_A = A:$D_PATH_PREPENDS_A | B_PATH_PREPENDS_A_AND_C = A:$B_PATH_PREPENDS_A_AND_C | A_SET_GETS_PREPENDED_WITH_B_AND_C = A | A_OVERRIDES_C_PREPENDING_B = A | A_OVERRIDES_B_AND_C = A | A_OVERRIDES_D = A | A_PATH_PREPENDS_B_AND_C = A:$A_PATH_PREPENDS_B_AND_C | A_PATH_PREPENDS_D = A:$A_PATH_PREPENDS_D '---C/1.2.3 | | C_DEFAULT = BAR | | B_OVERRIDES_C = C | | B_OVERRIDES_A_AND_C = C | | A_OVERRIDES_B_AND_C = C | | B_PATH_PREPENDS_A_AND_C = C:$B_PATH_PREPENDS_A_AND_C | | A_PATH_PREPENDS_B_AND_C = C:$A_PATH_PREPENDS_B_AND_C | | A_SET_GETS_PREPENDED_WITH_B_AND_C = C:$A_SET_GETS_PREPENDED_WITH_B_AND_C | | A_OVERRIDES_C_PREPENDING_B = C:$A_OVERRIDES_C_PREPENDING_B | '---D/1.2.3 | | D_DEFAULT = BAR | | A_OVERRIDES_D = D | | D_OVERRIDES_A = D | | D_PATH_PREPENDS_A = D:$D_PATH_PREPENDS_A | | A_PATH_PREPENDS_D = D:$A_PATH_PREPENDS_D | '---D/1.2.3:addon_a | | ADDON_A = ding | '---D/1.2.3:addon_b | | | ADDON_B = dong | | '---E/1.2.3 | '---D/1.2.3:addon_c | ADDON_C = dang '---B/1.2.3 | B_DEFAULT = BAR | B_OVERRIDES_C = B | B_OVERRIDES_A_AND_C = B | A_OVERRIDES_B_AND_C = B | B_PATH_PREPENDS_A_AND_C = B:$B_PATH_PREPENDS_A_AND_C | A_PATH_PREPENDS_B_AND_C = B:$A_PATH_PREPENDS_B_AND_C | A_SET_GETS_PREPENDED_WITH_B_AND_C = B:$A_SET_GETS_PREPENDED_WITH_B_AND_C | A_OVERRIDES_C_PREPENDING_B = B:$A_OVERRIDES_C_PREPENDING_B '---D/1.2.3 | D_DEFAULT = BAR | A_OVERRIDES_D = D | D_OVERRIDES_A = D | D_PATH_PREPENDS_A = D:$D_PATH_PREPENDS_A | A_PATH_PREPENDS_D = D:$A_PATH_PREPENDS_D '---D/1.2.3:addon_a | ADDON_A = ding '---D/1.2.3:addon_b | | ADDON_B = dong | '---E/1.2.3 '---D/1.2.3:addon_c ADDON_C = dang A/1.2.3:nondefault | A_BOTH_CONFIGS = nondefault | A_NONDEFAULT = BAZ '---C/4.5.6:nondefault C_ONLY_IN_C456 = C END_EXPECTED_OUTPUT out, err = fig(%w<--list-variables --list-all-configs --list-tree A/1.2.3>) out.should == expected err.should =~ %r<No version in the package descriptor of "D" in an include statement in the \.fig file for "B/1\.2\.3:default" \(line> end it %q<lists all dependency variables with a package.fig> do set_up_list_variables_packages create_package_dot_fig('A') expected = clean_expected(<<-'END_EXPECTED_OUTPUT') [package.fig] '---A/1.2.3 | A_BOTH_CONFIGS = default | A_DEFAULT = BAR | D_OVERRIDES_A = A | B_OVERRIDES_A_AND_C = A | A_PATH_DEFAULT = BAR:$A_PATH_DEFAULT | D_PATH_PREPENDS_A = A:$D_PATH_PREPENDS_A | B_PATH_PREPENDS_A_AND_C = A:$B_PATH_PREPENDS_A_AND_C | A_SET_GETS_PREPENDED_WITH_B_AND_C = A | A_OVERRIDES_C_PREPENDING_B = A | A_OVERRIDES_B_AND_C = A | A_OVERRIDES_D = A | A_PATH_PREPENDS_B_AND_C = A:$A_PATH_PREPENDS_B_AND_C | A_PATH_PREPENDS_D = A:$A_PATH_PREPENDS_D '---C/1.2.3 | | C_DEFAULT = BAR | | B_OVERRIDES_C = C | | B_OVERRIDES_A_AND_C = C | | A_OVERRIDES_B_AND_C = C | | B_PATH_PREPENDS_A_AND_C = C:$B_PATH_PREPENDS_A_AND_C | | A_PATH_PREPENDS_B_AND_C = C:$A_PATH_PREPENDS_B_AND_C | | A_SET_GETS_PREPENDED_WITH_B_AND_C = C:$A_SET_GETS_PREPENDED_WITH_B_AND_C | | A_OVERRIDES_C_PREPENDING_B = C:$A_OVERRIDES_C_PREPENDING_B | '---D/1.2.3 | | D_DEFAULT = BAR | | A_OVERRIDES_D = D | | D_OVERRIDES_A = D | | D_PATH_PREPENDS_A = D:$D_PATH_PREPENDS_A | | A_PATH_PREPENDS_D = D:$A_PATH_PREPENDS_D | '---D/1.2.3:addon_a | | ADDON_A = ding | '---D/1.2.3:addon_b | | | ADDON_B = dong | | '---E/1.2.3 | '---D/1.2.3:addon_c | ADDON_C = dang '---B/1.2.3 | B_DEFAULT = BAR | B_OVERRIDES_C = B | B_OVERRIDES_A_AND_C = B | A_OVERRIDES_B_AND_C = B | B_PATH_PREPENDS_A_AND_C = B:$B_PATH_PREPENDS_A_AND_C | A_PATH_PREPENDS_B_AND_C = B:$A_PATH_PREPENDS_B_AND_C | A_SET_GETS_PREPENDED_WITH_B_AND_C = B:$A_SET_GETS_PREPENDED_WITH_B_AND_C | A_OVERRIDES_C_PREPENDING_B = B:$A_OVERRIDES_C_PREPENDING_B '---D/1.2.3 | D_DEFAULT = BAR | A_OVERRIDES_D = D | D_OVERRIDES_A = D | D_PATH_PREPENDS_A = D:$D_PATH_PREPENDS_A | A_PATH_PREPENDS_D = D:$A_PATH_PREPENDS_D '---D/1.2.3:addon_a | ADDON_A = ding '---D/1.2.3:addon_b | | ADDON_B = dong | '---E/1.2.3 '---D/1.2.3:addon_c ADDON_C = dang END_EXPECTED_OUTPUT out, err = fig(%w<--list-variables --list-all-configs --list-tree>) out.should == expected err.should =~ %r<No version in the package descriptor of "D" in an include statement in the \.fig file for "B/1\.2\.3:default" \(line> end end end describe %q<handles "include ... override ...> do before(:each) do clean_up_test_environment set_up_test_environment set_up_packages_with_overrides remove_any_package_dot_fig end it %<plain (goes through RuntimeEnvironment object)> do expected = clean_expected(<<-END_EXPECTED_OUTPUT) C=4.5.6 END_EXPECTED_OUTPUT out, err = fig(%w<--list-variables A/1.2.3>) out.should == expected err.should == '' end it %<with --list-tree (goes through PackageCache object)> do expected = clean_expected(<<-END_EXPECTED_OUTPUT) A/1.2.3 '---B/1.2.3 '---C/4.5.6 | | C = 4.5.6 | '---D/4.5.6 '---D/4.5.6 END_EXPECTED_OUTPUT out, err = fig(%w<--list-variables --list-tree A/1.2.3>) out.should == expected err.should == '' end end it %q<should complain if local repository isn't in the expected format version> do clean_up_test_environment set_up_test_environment set_up_packages_with_overrides remove_any_package_dot_fig set_local_repository_format_to_future_version out, err, exit_code = fig(%w<--list-variables A/1.2.3>, :no_raise_on_error => true) exit_code.should_not == 0 err.should =~ /Local repository is in version \d+ format. This version of fig can only deal with repositories in version \d+ format\./ end end end
klimkin/fig
lib/fig/logging/colorizable.rb
# coding: utf-8 module Fig; end module Fig::Logging; end # A String that has colors associated with it. class Fig::Logging::Colorizable < String attr_reader :foreground, :background def initialize(string = '', foreground = nil, background = nil) super(string) @foreground = foreground @background = background end end
klimkin/fig
lib/fig/command/action/run_command_line.rb
# coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::RunCommandLine include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction def options() return %w<--> end def descriptor_requirement() return nil end def modifies_repository?() return false end def load_base_package?() return true end def register_base_package?() return true end def apply_config?() return true end def apply_base_config?() return true end def configure(options) @command_line = options.shell_command @descriptor = options.descriptor return end def execute() environment = @execution_context.environment base_package = @execution_context.base_package base_config = @execution_context.base_config environment.expand_command_line( base_package, base_config, @descriptor, @command_line ) do |command| @execution_context.operating_system.plain_or_shell_exec command end # Will never get here. end end
klimkin/fig
lib/fig/command/action/list_dependencies/default.rb
# coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/list_base_config' require 'fig/command/action/role/list_dependencies_flat' require 'fig/command/action/role/list_walking_dependency_tree' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListDependencies; end class Fig::Command::Action::ListDependencies::Default include Fig::Command::Action include Fig::Command::Action::Role::ListBaseConfig include Fig::Command::Action::Role::ListDependenciesFlat include Fig::Command::Action::Role::ListWalkingDependencyTree def options() return %w<--list-dependencies> end def descriptor_requirement() return nil end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config? return nil # don't care end def derive_package_strings(packages) return packages.keys end end
klimkin/fig
spec/support/formatters/seed_spitter.rb
<gh_stars>10-100 # coding: utf-8 require 'rspec/core/formatters/documentation_formatter' class SeedSpitter < RSpec::Core::Formatters::DocumentationFormatter def start(*) super output.puts "\nSeed: #{RSpec.configuration.seed}" end end
klimkin/fig
spec/command/grammar_command_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/grammar_spec_helper') describe 'Fig' do describe %q<uses the correct grammar version in the package definition created for publishing> do before(:each) do clean_up_test_environment set_up_test_environment end it 'from unversioned file input with a simple command statement' do check_published_grammar_version 0, <<-'END' config default command "echo foo" end END end it 'from v1 file input with a simple command statement' do check_published_grammar_version 0, <<-'END' grammar v1 config default command "echo foo" end end END end it 'from v1 file input with a multi-component, mixed-quoting command statement' do check_published_grammar_version 1, <<-'END' grammar v1 config default command echo "foo" 'bar baz' end end END end it 'from v1 file input with a command statement containing all keywords' do check_published_grammar_version 1, <<-'END' grammar v1 config default command add append archive command config 'end' # Have to quote this one include override path resource retrieve set end end END end it 'from v1 file input with a single-quoted command statement' do check_published_grammar_version 0, <<-'END' grammar v1 config default command 'bar baz' end end END end it 'from v1 file input with a command statement containing an octothorpe' do check_published_grammar_version 1, <<-'END' grammar v1 config default command "bar#baz" end end END end it 'from v1 file input with a command statement containing a double quote' do check_published_grammar_version 1, <<-'END' grammar v1 config default command bar\"baz end end END end end end # vim: set fileencoding=utf8 :
klimkin/fig
lib/fig/command/action/list_variables/tree.rb
# coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/list_base_config' require 'fig/command/action/role/list_variables_in_a_tree' require 'fig/command/action/role/list_walking_dependency_tree' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListVariables; end class Fig::Command::Action::ListVariables::Tree include Fig::Command::Action include Fig::Command::Action::Role::ListBaseConfig include Fig::Command::Action::Role::ListVariablesInATree include Fig::Command::Action::Role::ListWalkingDependencyTree def options() return %w<--list-variables --list-tree> end end
klimkin/fig
lib/fig/log4r/outputter.rb
# coding: utf-8 require 'colorize' require 'log4r/logger' require 'log4r/outputter/iooutputter' require 'fig/logging/colorizable' require 'fig/operating_system' module Fig; end module Fig::Log4r; end class Fig::Log4r::Outputter < Log4r::IOOutputter def initialize(name, file_handle, hash = {}) @colors = hash.delete(:colors) @colors ||= { :debug => :white, :info => :light_white, :warn => :yellow, :error => :red, :fatal => {:color => :light_yellow, :background => :red} } @colorize = file_handle.tty? && Fig::OperatingSystem.unix? super(name, file_handle, hash) initialize_colors_by_level() end private def initialize_colors_by_level() @colors_by_level = {} Log4r::LNAMES.each_index do |index| name_symbol = Log4r::LNAMES[index].downcase.to_sym color = @colors[name_symbol] if color @colors_by_level[index] = color end end return end def canonical_log(logevent) synch { write( format(logevent), logevent ) } end def write(data, logevent) begin if not @colorize @out.print data else if logevent.data.is_a? Fig::Logging::Colorizable emit_colorizable(data, logevent.data) else color = @colors_by_level[logevent.level] if color @out.print data.colorize(color) @out.print ''.uncolorize else @out.print data end end end @out.flush rescue IOError => error # recover from this instead of crash Log4r::Logger.log_internal {"IOError in Outputter '#{@name}'!"} Log4r::Logger.log_internal {error} close rescue NameError => error Log4r::Logger.log_internal {"Outputter '#{@name}' IO is #{@out.class}!"} Log4r::Logger.log_internal {error} close end return end def emit_colorizable(formatted_data, raw_data) color = {} if raw_data.foreground color[:color] = raw_data.foreground end if raw_data.background color[:background] = raw_data.background end @out.print formatted_data.colorize(color) @out.print ''.uncolorize return end end
klimkin/fig
lib/fig/working_directory_metadata.rb
<gh_stars>10-100 # coding: utf-8 require 'set' module Fig; end # Data about a package within the current working directory. class Fig::WorkingDirectoryMetadata attr_reader :package_name, :current_version def initialize(package_name, current_version = nil) @package_name = package_name @retrieved = false reset_with_version(current_version) end def reset_with_version(new_version) @current_version = new_version @files = Set.new return end def add_file(file) @files << file return end def mark_as_retrieved() @retrieved = true return end def retrieved?() return @retrieved end # So we don't have to expose the files collection. def each_file() @files.each {|file| yield file} return end end
klimkin/fig
spec/environment_variables_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'fig/environment_variables/case_insensitive' require 'fig/environment_variables/case_sensitive' def find_diffs(primary_hash, secondary_hash, diff_hash) primary_hash.each do |key, value| if ! secondary_hash.has_key?(key) diff_hash[key] = value elsif primary_hash[key] != secondary_hash[key] diff_hash[key] = value end end return end def hash_differences(hash_one, hash_two) hash_differences = {} find_diffs(hash_one, hash_two, hash_differences) find_diffs(hash_two, hash_one, hash_differences) return hash_differences end describe 'EnvironmentVariables' do it 'correctly sets and unsets the system environment variables' do env_vars = Fig::EnvironmentVariables::CaseSensitive.new({ 'Foo' => 'BAR' }) sys_vars_prior = {} sys_vars_prior.merge!(ENV.to_hash) sys_vars_set = {} sys_vars_after = {} env_vars['BAR'] = 'BAZ' env_vars.with_environment { sys_vars_set.merge!(ENV.to_hash) } sys_vars_after.merge!(ENV.to_hash) hash_differences(sys_vars_prior, sys_vars_after).should be_empty before_and_during_diff = hash_differences(sys_vars_prior, sys_vars_set) hash_differences(before_and_during_diff, {'BAR' => 'BAZ', 'Foo' => 'BAR'}).should be_empty end describe 'case sensitive' do it 'sets and retrieves variables' do env_vars = Fig::EnvironmentVariables::CaseSensitive.new({ 'Foo' => 'BAR' }) env_vars['FOO'].should == nil env_vars['Foo'].should == 'BAR' env_vars['BAR'] = 'BAZ' env_vars['BAR'].should == 'BAZ' env_vars['bar'].should == nil end it 'prepends values onto variables' do env_vars = Fig::EnvironmentVariables::CaseSensitive.new({ 'Foo' => 'BAR' }) env_vars.prepend_variable('Foo', 'BAZ') env_vars['Foo'].should == 'BAZ' + File::PATH_SEPARATOR + 'BAR' env_vars.prepend_variable('FOO', 'XYZZY') env_vars['FOO'].should == 'XYZZY' end end describe 'case sensitive' do it 'sets and retrieves variables' do env_vars = Fig::EnvironmentVariables::CaseInsensitive.new({ 'Foo' => 'BAR' }) env_vars['FOO'].should == 'BAR' env_vars['foo'].should == 'BAR' env_vars['BAR'] = 'BAZ' env_vars['BAR'].should == 'BAZ' env_vars['bar'].should == 'BAZ' end it 'prepends values onto variables' do env_vars = Fig::EnvironmentVariables::CaseInsensitive.new({ 'Foo' => 'BAR' }) env_vars.prepend_variable('Foo', 'BAZ') env_vars['Foo'].should == 'BAZ' + File::PATH_SEPARATOR + 'BAR' env_vars.prepend_variable('FOO', 'XYZZY') env_vars['Foo'].should == 'XYZZY' + File::PATH_SEPARATOR + 'BAZ' + File::PATH_SEPARATOR + 'BAR' end end end
klimkin/fig
lib/fig/protocol.rb
# coding: utf-8 require 'fig/logging' require 'fig/network_error' module Fig; end # File transfers. module Fig::Protocol def download_list(uri) Fig::Logging.fatal "Protocol not supported: #{uri}" raise Fig::NetworkError.new "Protocol not supported: #{uri}" end # Determine whether we need to update something. Returns nil to indicate # "don't know". def path_up_to_date?(uri, path) return nil # Not implemented end # Returns whether the file was not downloaded because the file already # exists and is already up-to-date. def download(uri, path) Fig::Logging.fatal "Protocol not supported: #{uri}" raise Fig::NetworkError.new "Protocol not supported: #{uri}" end def upload(local_file, uri) Fig::Logging.fatal "Protocol not supported: #{uri}" raise Fig::NetworkError.new "Protocol not supported: #{uri}" end private def strip_paths_for_list(ls_output, packages, path) if not ls_output.nil? ls_output = ls_output.gsub(path + '/', '').gsub(path, '').split("\n") ls_output.each do |line| parts = line.gsub(/\\/, '/').sub(/^\.\//, '').sub(/:$/, '').chomp().split('/') packages << parts.join('/') if parts.size == 2 end end end def log_download(uri, path) Fig::Logging.debug "Downloading #{uri} to #{path}." end end
klimkin/fig
lib/fig/command/action/role/list_variables_in_a_tree.rb
# coding: utf-8 require 'fig/command/action' require 'fig/statement/path' require 'fig/statement/set' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListVariablesInATree def descriptor_requirement() return nil end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config?() return nil # don't care end def execute() # We can't just display as we walk the dependency tree because we need to # know in advance how many configurations we're going display under # another. tree = build_variable_tree() tree.child_configs().each do |child| display_variable_tree_level(child, '', '') end return Fig::Command::Action::EXIT_SUCCESS end private VariableTreePackageConfig = Struct.new( :package, :config_name, :variable_statements, :child_configs, :parent ) def build_variable_tree() tree = VariableTreePackageConfig.new(nil, nil, nil, [], nil) prior_depth = 0 prior_node = nil current_parent = tree walk_dependency_tree( @execution_context.base_package, base_display_config_names() ) do |package, config_name, depth| if depth < prior_depth (depth .. (prior_depth - 1)).each do current_parent = current_parent.parent end elsif depth == prior_depth + 1 current_parent = prior_node elsif depth > prior_depth raise "Bug in code! Descended more than one level! (#{prior_depth} to #{depth}" end variable_statements = gather_variable_statements(package[config_name]) node = VariableTreePackageConfig.new( package, config_name, variable_statements, [], current_parent ) current_parent.child_configs() << node prior_depth = depth prior_node = node end return tree end def gather_variable_statements(config_statement) variable_statements = [] config_statement.walk_statements() do |statement| if statement.is_environment_variable? variable_statements << statement end end return variable_statements end def display_variable_tree_level(node, base_indent, package_indent) print package_indent puts node.package().to_s_with_config(node.config_name()) display_variable_tree_level_variables(node, base_indent) child_configs = node.child_configs() child_count = child_configs.size() new_indent = base_indent + (child_count > 0 ? '|' : ' ') + ' ' * 3 new_package_indent = base_indent + %q<'---> (0 .. (child_count - 2)).each do |child_index| display_variable_tree_level( child_configs[child_index], new_indent, new_package_indent ) end if child_count > 0 display_variable_tree_level( child_configs[-1], (base_indent + ' ' * 4), new_package_indent ) end end def display_variable_tree_level_variables(node, base_indent) if node.child_configs().size() > 0 variable_indent = base_indent + '|' + ' ' * 3 else variable_indent = base_indent + ' ' * 4 end variable_statements = node.variable_statements() name_width = (variable_statements.map { |statement| statement.name().length() }).max() variable_statements.each do |statement| print "#{variable_indent}" print "#{statement.name().ljust(name_width)}" print " = #{statement.tokenized_value.to_escaped_string}" if statement.is_a?(Fig::Statement::Path) print ":$#{statement.name}" end print "\n" end return end end
klimkin/fig
lib/fig/command/action/update.rb
# coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' require 'fig/command/action/role/update' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::Update include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction include Fig::Command::Action::Role::Update def options() return %w<--update> end def prepare_repository(repository) repository.update_unconditionally return end end
klimkin/fig
lib/fig/command/action/list_variables/graphviz.rb
<gh_stars>10-100 # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/list_as_graphviz' require 'fig/command/action/role/list_base_config' require 'fig/command/action/role/list_variables_as_graphviz' require 'fig/command/action/role/list_walking_dependency_tree' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::ListVariables; end class Fig::Command::Action::ListVariables::Graphviz include Fig::Command::Action include Fig::Command::Action::Role::ListAsGraphviz include Fig::Command::Action::Role::ListBaseConfig include Fig::Command::Action::Role::ListVariablesAsGraphviz include Fig::Command::Action::Role::ListWalkingDependencyTree def options() return %w<--list-variables --graphviz> end end
klimkin/fig
lib/fig/statement/resource.rb
# coding: utf-8 require 'fig/statement' require 'fig/statement/asset' require 'fig/url' module Fig; end class Fig::Statement; end # Specifies a file (possibly via a URL) that is part of the current package. # # Differs from an Archive in that the contents will not be extracted. class Fig::Statement::Resource < Fig::Statement include Fig::Statement::Asset def initialize(line_column, source_description, location, glob_if_not_url) super(line_column, source_description) @location = location @glob_if_not_url = glob_if_not_url end def statement_type() return 'resource' end def asset_name() if Fig::URL.is_url?(location()) return standard_asset_name() end # This resource will end up being bundled with others and will not live in # the package by itself. return nil end def deparse_as_version(deparser) return deparser.resource(self) end end
klimkin/fig
lib/fig/external_program.rb
<reponame>klimkin/fig # coding: utf-8 require 'stringio' require 'fig/user_input_error' module Fig; end class Fig::ExternalProgram def self.popen(*cmd) exit_code = nil options = {} stdin_read, stdin_write = IO.pipe Encoding::UTF_8, Encoding::UTF_8 options[:in] = stdin_read stdin_write.sync = true stdout_read, stdout_write = IO.pipe Encoding::UTF_8, Encoding::UTF_8 options[:out] = stdout_write stderr_read, stderr_write = IO.pipe Encoding::UTF_8, Encoding::UTF_8 options[:err] = stderr_write popen_run( cmd, options, [stdin_read, stdout_write, stderr_write], [stdin_write, stdout_read, stderr_read], ) do |stdin, stdout, stderr, wait_thread| yield stdin, stdout, stderr exit_code = wait_thread.value end return exit_code end def self.capture(command_line, input = nil) output = nil errors = nil result = popen(*command_line) do |stdin, stdout, stderr| if ! input.nil? stdin.puts input # Potential deadlock if input is bigger than pipe size. end stdin.close output = StringIO.new errors = StringIO.new input_to_output = {stdout => output, stderr => errors} while ! input_to_output.empty? ready, * = IO.select input_to_output.keys ready.each do |handle| begin # #readpartial() is busted in that it is returning a byte array in # a String with a bogus Encoding, even though the bytes may not be # valid in the Encoding. input_to_output[handle] << handle.readpartial(4096) rescue EOFError input_to_output.delete handle end end end end output_string = string_io_byte_array_to_utf8_string output errors_string = string_io_byte_array_to_utf8_string errors return output_string, errors_string, result end private # Stolen from open3.rb def self.popen_run(cmd, opts, child_io, parent_io) pid = spawn(*cmd, opts) wait_thr = Process.detach(pid) child_io.each {|io| io.close } result = [*parent_io, wait_thr] if defined? yield begin return yield(*result) ensure parent_io.each{|io| io.close unless io.closed?} wait_thr.join end end result end # There appears to be no way to convert from a byte array to a UTF-8 string # cleanly, with a report of where things are wrong. def self.string_io_byte_array_to_utf8_string(string_io) string = string_io.string string.force_encoding(Encoding::UTF_8) if ! string.valid_encoding? # Seriously lame, uninformative error message, but, hopefully, this is # rare and I don't think I can spend the time to gather the information # to make this better right now. raise UserInputError.new 'Got invalid UTF-8 input.' end return string end end
klimkin/fig
spec/command/usage_errors_spec.rb
<filename>spec/command/usage_errors_spec.rb # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'English' require 'fig/command/package_loader' describe 'Fig' do describe 'usage errors: fig' do before(:each) do clean_up_test_environment set_up_test_environment end it %q<prints usage message when passed an unknown option> do out, err, exit_code = fig %w<--no-such-option>, :fork => false, :no_raise_on_error => true exit_code.should_not == 0 err.should =~ / --no-such-option /x err.should =~ / usage /xi out.should == '' end describe %q<prints message when no descriptor is specified and> do describe %q<there's nothing to do and> do it %q<there isn't a package.fig file> do out, err, exit_code = fig [], :fork => false, :no_raise_on_error => true exit_code.should_not == 0 err.should =~ /nothing to do/i out.should == '' end describe %q<there is a package.fig file> do it %q<with no command statement> do write_file( "#{FIG_SPEC_BASE_DIRECTORY}/#{Fig::Command::PackageLoader::DEFAULT_PACKAGE_FILE}", <<-END_PACKAGE_DOT_FIG config default end END_PACKAGE_DOT_FIG ) out, err, exit_code = fig [], :fork => false, :no_raise_on_error => true exit_code.should_not == 0 err.should =~ /nothing to do/i out.should == '' end it %q<with a command statement> do write_file( "#{FIG_SPEC_BASE_DIRECTORY}/#{Fig::Command::PackageLoader::DEFAULT_PACKAGE_FILE}", <<-END_PACKAGE_DOT_FIG config default command "echo foo" end END_PACKAGE_DOT_FIG ) out, err, exit_code = fig [], :fork => false, :no_raise_on_error => true exit_code.should_not == 0 err.should =~ /nothing to do/i out.should == '' end end end end it %q<prints error when extra parameters are given with a package descriptor> do out, err, exit_code = fig( %w<package/descriptor extra bits>, :fork => false, :no_raise_on_error => true ) exit_code.should == 1 err.should =~ / extra /xi err.should =~ / bits /xi out.should == '' end it %q<prints error when a package descriptor consists solely of a version> do out, err, exit_code = fig %w</version>, :fork => false, :no_raise_on_error => true exit_code.should == 1 err.should =~ /package name required/i out.should == '' end it %q<prints error when a package descriptor consists solely of a config> do out, err, exit_code = fig %w<:config>, :fork => false, :no_raise_on_error => true exit_code.should_not == 0 err.should =~ /package name required/i out.should == '' end it %q<prints error when a package descriptor consists solely of a package> do out, err, exit_code = fig %w<package>, :fork => false, :no_raise_on_error => true exit_code.should_not == 0 err.should =~ /version required/i out.should == '' end it %q<prints error when a descriptor and --file is specified> do out, err, exit_code = fig( %w<package/version:default --file some.fig>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ /cannot specify both a package descriptor.*and the --file option/i out.should == '' end it %q<prints error when a descriptor contains a config and --config is specified> do out, err, exit_code = fig( %w<package/version:default --config nondefault>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ /Cannot specify both --config and a config in the descriptor/ out.should == '' end it %q<prints error when extra parameters are given with a command> do out, err, exit_code = fig( %w<extra bits -- echo foo>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ / extra /xi err.should =~ / bits /xi out.should == '' end it %q<prints error when multiple --list-* options are given> do out, err, exit_code = fig( %w<--list-remote --list-variables>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 out.should == '' err.should =~ /cannot specify/i end describe %q<prints error when unknown package is referenced> do it %q<without --update> do out, err, exit_code = fig( %w<no-such-package/version --get PATH>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ / no-such-package /x out.should == '' end it %q<with --update> do out, err, exit_code = fig( %w<no-such-package/version --update --get PATH>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ / no-such-package /x out.should == '' end it %q<with --update-if-missing> do out, err, exit_code = fig( %w<no-such-package/version --update-if-missing --get PATH>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ / no-such-package /x out.should == '' end end describe %q<prints error when referring to non-existent configuration> do it %q<from the command-line as the base package> do fig %w<--publish foo/1.2.3 --set FOO=BAR>, :fork => false out, err, exit_code = fig( %w<foo/1.2.3:non-existent-config --get FOO>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r< non-existent-config >x out.should == '' end it %q<from the command-line as an included package> do fig %w<--publish foo/1.2.3 --set FOO=BAR>, :fork => false out, err, exit_code = fig( %w<--include foo/1.2.3:non-existent-config --get FOO>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r< foo/1\.2\.3:non-existent-config >x out.should == '' end end it %q<prints error when --include is specified without a package version> do out, err, exit_code = fig( %w<--include package-without-version --get FOO>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r< package-without-version >x err.should =~ %r<no version specified>i out.should == '' end it %q<prints error when --override is specified without a package version> do out, err, exit_code = fig( %w<--override package-without-version>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r< package-without-version >x err.should =~ %r<version required>i out.should == '' end it %q<prints error when --override is specified with a package config> do out, err, exit_code = fig( %w<--override package/version:config-should-not-be-here>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r< package/version:config-should-not-be-here >x err.should =~ %r<config forbidden>i out.should == '' end it %q<prints error when --publish-comment is specified when not publishing> do out, err, exit_code = fig( %w<--publish-comment whatever>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r<cannot use --publish-comment when not publishing>i out.should == '' end it %q<prints error when --publish-comment-file is specified when not publishing> do out, err, exit_code = fig( %w<--publish-comment-file whatever>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r<cannot use --publish-comment-file when not publishing>i out.should == '' end describe %q<refuses to publish> do it %q<a package named "_meta"> do out, err, exit_code = fig( %w<--publish _meta/version --set FOO=BAR>, :fork => false, :no_raise_on_error => true ) err.should =~ %r< cannot .* _meta >x exit_code.should_not == 0 out.should == '' end it %q<without a package name> do out, err, exit_code = fig( %w<--publish --set FOO=BAR>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r<specify a descriptor>i out.should == '' end it %q<without a version> do out, err, exit_code = fig( %w<--publish a-package --set FOO=BAR>, :fork => false, :no_raise_on_error => true ) exit_code.should_not == 0 err.should =~ %r<version required>i out.should == '' end it %q<when given the --include-file option> do write_file "#{CURRENT_DIRECTORY}/thingy.fig", 'config default end' out, err, exit_code = fig( [ '--publish', 'package/version', '--include-file', "'#{CURRENT_DIRECTORY}/thingy.fig'", ], :fork => false, :no_raise_on_error => true ) err.should =~ %r< cannot .* include-file >ix exit_code.should_not == 0 out.should == '' end it %q<a package with an include-file statement> do write_file "#{CURRENT_DIRECTORY}/thingy.fig", 'config default end' input = <<-END grammar v2 config default include-file '#{CURRENT_DIRECTORY}/thingy.fig' end END out, err, exit_code = fig( %w<--publish package/version>, input, :fork => false, :no_raise_on_error => true ) err.should =~ %r< cannot .* include-file >ix exit_code.should_not == 0 out.should == '' end it %q<a package with an archive of unknown type> do archive_file = 'unknown.archive-type' write_file "#{CURRENT_DIRECTORY}/#{archive_file}", '' input = <<-END grammar v0 archive #{archive_file} config default end END out, err, exit_code = fig( %w<--publish package/version>, input, :fork => false, :no_raise_on_error => true ) err.should =~ %r< \b #{ Regexp.escape(archive_file) } \b >ix err.should =~ %r< \b unknown [ ] archive [ ] type \b >ix exit_code.should_not == 0 out.should == '' end end it %q<complains about command-line substitution of unreferenced packages> do fig %w<--publish a-package/a-version --set FOO=BAR>, :fork => false out, err, exit_code = fig %w<-- echo @a-package>, :fork => false, :no_raise_on_error => true exit_code.should_not == 0 err.should =~ %r<\ba-package\b.*has not been referenced> out.should == '' end %w< --archive --resource >.each do |option| it %Q<warns about #{option} when not publishing> do out, err = fig ['--get', 'some_variable', option, 'some-asset'], :fork => false err.should =~ /#{option}/ err.should =~ /\bsome-asset\b/ end end describe %q<prints error when attempting a remote operation and FIG_REMOTE_URL is> do it %q<not defined> do begin ENV.delete('FIG_REMOTE_URL') out, err, exit_code = fig %w<--list-remote>, :fork => false, :no_raise_on_error => true err.should =~ %r<FIG_REMOTE_URL> out.should == '' exit_code.should_not == 0 ensure ENV['FIG_REMOTE_URL'] = FIG_REMOTE_URL end end it %q<empty> do begin ENV['FIG_REMOTE_URL'] = '' out, err, exit_code = fig %w<--list-remote>, :fork => false, :no_raise_on_error => true err.should =~ %r<FIG_REMOTE_URL> out.should == '' exit_code.should_not == 0 ensure ENV['FIG_REMOTE_URL'] = FIG_REMOTE_URL end end it %q<all whitespace> do begin ENV['FIG_REMOTE_URL'] = " \n\t" out, err, exit_code = fig %w<--list-remote>, :fork => false, :no_raise_on_error => true err.should =~ %r<FIG_REMOTE_URL> out.should == '' exit_code.should_not == 0 ensure ENV['FIG_REMOTE_URL'] = FIG_REMOTE_URL end end end end end
klimkin/fig
lib/fig/statement/command.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/statement' module Fig; end # Specifies a default command that will be executed for a given Configuration # if no command is specified on the command-line. class Fig::Statement::Command < Fig::Statement attr_reader :command def self.validate_and_process_escapes_in_argument( command_line_argument, &block ) tokenizer = Fig::StringTokenizer.new TOKENIZING_SUBEXPRESSION_MATCHER, '@' return tokenizer.tokenize command_line_argument, &block end def initialize(line_column, source_description, command) super(line_column, source_description) @command = command end def statement_type() return 'command' end def deparse_as_version(deparser) return deparser.command(self) end def minimum_grammar_for_emitting_input() return minimum_grammar() end def minimum_grammar_for_publishing() return minimum_grammar() end private def minimum_grammar() if command.size > 1 return [1, 'contains multiple components'] end argument = command.first.to_escaped_string # Can't have octothorpes anywhere in v0 due to comment stripping via # regex. if argument =~ /#/ return [1, 'contains a comment ("#") character'] end if argument =~ /"/ return [1, %Q<contains a double quote>] end return [0] end TOKENIZING_SUBEXPRESSION_MATCHER = [ { :pattern => %r< \@ [a-zA-Z0-9_.-]* >x, :action => lambda { |subexpression, error_block| Fig::TokenizedString::Token.new :package_path, subexpression } } ] end
klimkin/fig
lib/fig/command/action/role/list_variables_from_data_structure.rb
<reponame>klimkin/fig # coding: utf-8 require 'cgi' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::ListVariablesFromDataStructure def descriptor_requirement() return nil end def load_base_package?() return true end def register_base_package?() return nil # don't care end def apply_config?() return nil # don't care end private def node_content(package, config_name) hash = new_package_config_hash package, config_name statements = variable_statements package, config_name if not statements.empty? hash['variables'] = statements end return hash end def variable_statements(package, config_name) statements = [] package[config_name].walk_statements do |statement| if statement.is_environment_variable? statements << hash_for_variable_statement(statement) end end return statements end def hash_for_variable_statement(statement) return { 'type' => statement.statement_type, 'name' => statement.name, 'value' => statement.tokenized_value.to_escaped_string, } end end
klimkin/fig
lib/fig/statement/synthetic_raw_text.rb
<gh_stars>10-100 # coding: utf-8 require 'fig/statement' module Fig; end # Some raw text that we want emitted as part of unparsing. class Fig::Statement::SyntheticRawText < Fig::Statement attr_reader :text def initialize(line_column, source_description, text) super(line_column, source_description) @text = text end def statement_type() return nil end def deparse_as_version(deparser) return deparser.synthetic_raw_text(self) end def minimum_grammar_for_emitting_input() return [0] end def minimum_grammar_for_publishing() return [0] end end
klimkin/fig
lib/fig/command/action/help_long.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::HelpLong include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction def options() return %w<--help-long> end def execute_immediately_after_command_line_parse? return true end def configure(options) @help_message = options.full_help_message end def execute() puts @help_message return EXIT_SUCCESS end end
klimkin/fig
spec/command/grammar_asset_spec.rb
<gh_stars>10-100 # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/grammar_spec_helper') require 'cgi' require 'fig/operating_system' # I do not understand the scoping rules for RSpec at all. # Block is supposed to publish the package given a URL. def test_published_asset_with_url_with_symbol( asset_type, symbol, quote, version ) file_name = "with#{symbol}symbol.zip" escaped_file = CGI.escape file_name quoted_url = "#{quote}file://#{CURRENT_DIRECTORY}/#{escaped_file}#{quote}" it %Q<with URL «#{quoted_url}» (contains a «#{symbol}»)> do write_file "#{CURRENT_DIRECTORY}/#{file_name}", '' yield quoted_url check_published_grammar_version(version) out, err = fig(%w< foo/1.2.3 --dump-package-definition-text >, :fork => false) # Test that the statement gets rewritten without the URL. # # Assumes that all grammar versions don't put non-whitespace before the # asset statement. out.should =~ / ^ \s* #{asset_type} \s+ ['"]? # Don't worry about what the grammar does with quoting. #{Regexp.escape file_name} \b /x end return end def test_published_command_line_asset_with_url_with_symbol( asset_type, symbol, quote, version ) test_published_asset_with_url_with_symbol( asset_type, symbol, quote, version ) do |quoted_url| fig( [ %w< --publish foo/1.2.3 --set x=y >, "--#{asset_type}", quoted_url ], :fork => false ) end return end def test_published_file_asset_with_url_with_symbol( asset_type, symbol, quote, version ) test_published_asset_with_url_with_symbol( asset_type, symbol, quote, version ) do |quoted_url| input = <<-"END" grammar v1 #{asset_type} #{quoted_url} config default end END fig %w< --publish foo/1.2.3 >, input, :fork => false end return end def test_published_asset_with_file_with_symbol( asset_type, symbol, quote, version ) file_name = "with#{symbol}symbol.zip" quoted_name = "#{quote}#{file_name}#{quote}" it %Q<with file «#{quoted_name}»> do write_file "#{CURRENT_DIRECTORY}/#{file_name}", '' yield quoted_name check_published_grammar_version(version) end return end def test_published_command_line_asset_with_file_with_symbol( asset_type, symbol, quote, version ) test_published_asset_with_file_with_symbol( asset_type, symbol, quote, version ) do |quoted_name| fig( [ %w< --publish foo/1.2.3 --set x=y >, "--#{asset_type}", quoted_name ], :fork => false ) end return end def test_published_file_asset_with_file_with_symbol( asset_type, symbol, quote, version ) test_published_asset_with_file_with_symbol( asset_type, symbol, quote, version ) do |quoted_url| input = <<-"END" grammar v1 #{asset_type} #{quoted_url} config default end END fig %w< --publish foo/1.2.3 >, input, :fork => false end return end def full_glob_characters() return %w< * ? [ ] { } >; end def testable_glob_characters() return full_glob_characters() - Fig::OperatingSystem.file_name_illegal_characters end def v1_special_characters() return full_glob_characters + %w[ # ]; end def v1_non_special_characters() return %w[ < > | ]; end def v0_special_characters() return v1_special_characters + v1_non_special_characters end def testable_v1_special_characters() return v1_special_characters() - Fig::OperatingSystem.file_name_illegal_characters end def testable_v1_non_special_characters() return v1_non_special_characters() - Fig::OperatingSystem.file_name_illegal_characters end def testable_v0_special_characters() return v0_special_characters() - Fig::OperatingSystem.file_name_illegal_characters end describe 'Fig' do describe %q<uses the correct grammar version in the package definition created for publishing> do before(:each) do clean_up_test_environment set_up_test_environment end shared_examples_for 'asset option' do |asset_type| ['', %q<'>, %q<">].each do |quote| begin value = "#{quote}nothing-special.zip#{quote}" it %Q<with file «#{value}»> do write_file "#{CURRENT_DIRECTORY}/nothing-special.zip", '' fig( [%w< --publish foo/1.2.3 --set x=y >, "--#{asset_type}", value], :fork => false ) check_published_grammar_version(0) end end test_published_command_line_asset_with_url_with_symbol( asset_type, '#', quote, 1 ) end testable_glob_characters.each do |symbol| test_published_command_line_asset_with_url_with_symbol( asset_type, symbol, %q<'>, 1 ) ['', %q<">].each do |quote| test_published_command_line_asset_with_url_with_symbol( asset_type, symbol, quote, 0 ) end end end describe 'for --archive' do ['', %q<'>, %q<">].each do |quote| testable_v1_special_characters.each do |symbol| test_published_command_line_asset_with_file_with_symbol( 'archive', symbol, quote, 1 ) end testable_v1_non_special_characters.each do |symbol| test_published_command_line_asset_with_file_with_symbol( 'archive', symbol, quote, 1 ) end end it_behaves_like 'asset option', 'archive' end describe 'for --resource' do ['', %q<'>, %q<">].each do |quote| testable_v0_special_characters.each do |symbol| test_published_command_line_asset_with_file_with_symbol( 'resource', symbol, quote, 0 ) end end it_behaves_like 'asset option', 'resource' end shared_examples_for 'asset statement' do |asset_type| ['', %q<'>, %q<">].each do |quote| begin value = "#{quote}nothing-special.zip#{quote}" it %Q<with file «#{value}»> do write_file "#{CURRENT_DIRECTORY}/nothing-special.zip", '' input = <<-"END" grammar v1 #{asset_type} #{value} config default end END fig %w< --publish foo/1.2.3 >, input, :fork => false check_published_grammar_version(0) end end test_published_file_asset_with_url_with_symbol( asset_type, '#', quote, 1 ) end testable_glob_characters.each do |symbol| test_published_file_asset_with_url_with_symbol( asset_type, symbol, %q<'>, 1 ) ['', %q<">].each do |quote| test_published_file_asset_with_url_with_symbol( asset_type, symbol, quote, 0 ) end end end describe 'for archive statement' do ['', %q<'>, %q<">].each do |quote| (testable_v1_special_characters - %w<#>).each do |symbol| test_published_file_asset_with_file_with_symbol( 'archive', symbol, quote, 1 ) end testable_v1_non_special_characters.each do |symbol| test_published_file_asset_with_file_with_symbol( 'archive', symbol, quote, 1 ) end end [%q<'>, %q<">].each do |quote| test_published_file_asset_with_file_with_symbol( 'archive', '#', quote, 1 ) end it_behaves_like 'asset statement', 'archive' end describe 'for resource statement' do ['', %q<'>, %q<">].each do |quote| (testable_v0_special_characters - %w<#>).each do |symbol| test_published_file_asset_with_file_with_symbol( 'resource', symbol, quote, 0 ) end end [%q<'>, %q<">].each do |quote| test_published_file_asset_with_file_with_symbol( 'resource', '#', quote, 0 ) end it_behaves_like 'asset statement', 'resource' end end describe %q<uses the correct grammar version in the package definition after parsing> do before(:each) do clean_up_test_environment set_up_test_environment end %w< archive resource >.each do |asset_type| describe "#{asset_type} statement" do [%q<'>, %q<">].each do |quote| value = "#{quote}contains#octothorpe#{quote}" it %Q<with input containing «#{value}»> do input = <<-"END" grammar v1 #{asset_type} #{value} END out, err = fig ['--dump-package-definition-parsed'], input, :fork => false out.should =~ /\b grammar [ ] v1 \b/x err.should == '' end end end end end end # vim: set fileencoding=utf8 :
klimkin/fig
lib/fig/command/action/role/update.rb
# coding: utf-8 require 'fig/command/action' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::Update def descriptor_requirement() return nil end def allow_both_descriptor_and_file?() # We don't care, so we let the base action say what it wants. return true end def modifies_repository?() return true end def load_base_package?() return true end def register_base_package?() return true end def apply_config?() return true end def apply_base_config?() return true end def retrieves_should_happen?() return true end def remote_operation_necessary?() return true end def execute() # Don't do anything. return Fig::Command::Action::EXIT_SUCCESS end end
klimkin/fig
lib/fig/command/package_loader.rb
# coding: utf-8 require 'fig/not_yet_parsed_package' require 'fig/package_descriptor' require 'fig/parser' module Fig; end class Fig::Command; end # Loads the base package. class Fig::Command::PackageLoader attr_reader :package_load_path_description DEFAULT_PACKAGE_FILE = 'package.fig' DEFAULT_APPLICATION_FILE = 'application.fig' def initialize( application_configuration, descriptor, package_definition_file, base_config, repository ) @application_configuration = application_configuration @descriptor = descriptor @package_definition_file = package_definition_file @base_config = base_config @repository = repository end def load_package_object_from_file() definition_text = load_package_definition_file_contents() parse_package_definition_file(definition_text) return @base_package end def load_package_object() if @descriptor.nil? load_package_object_from_file() else set_base_package @repository.get_package(@descriptor) end return @base_package end def package_source_description() if @package_load_path_description return @package_load_path_description elsif @descriptor return Fig::PackageDescriptor.format( @descriptor.name, @descriptor.version, nil ) end return nil end private def load_package_definition_file_contents() if @package_definition_file == :none return nil elsif @package_definition_file == '-' @package_load_path_description = '<standard input>' return $stdin.read elsif @package_definition_file.nil? if File.exist?(DEFAULT_PACKAGE_FILE) @package_load_path_description = DEFAULT_PACKAGE_FILE @package_load_path = DEFAULT_PACKAGE_FILE elsif File.exist?(DEFAULT_APPLICATION_FILE) @package_load_path_description = DEFAULT_APPLICATION_FILE @package_load_path = DEFAULT_APPLICATION_FILE end if @package_load_path return File.read(@package_load_path) end else return read_in_package_definition_file(@package_definition_file) end return end def read_in_package_definition_file(config_file) if File.exist?(config_file) @package_load_path_description = config_file @package_load_path = config_file @package_include_file_base_directory = File.dirname config_file return File.read(config_file) else raise Fig::UserInputError.new(%Q<File "#{config_file}" does not exist.>) end end def parse_package_definition_file(definition_text) if definition_text.nil? # This package gets a free ride in terms of requiring a base config; we # synthesize it. set_base_package_to_empty_synthetic_one() return end source_description = package_source_description() descriptor = Fig::PackageDescriptor.new( nil, nil, nil, :file_path => @package_load_path, :description => @package_load_path ? nil : source_description, :source_description => source_description ) unparsed_package = Fig::NotYetParsedPackage.new unparsed_package.descriptor = descriptor unparsed_package.working_directory = '.' unparsed_package.include_file_base_directory = @package_include_file_base_directory || '.' unparsed_package.source_description = source_description unparsed_package.unparsed_text = definition_text set_base_package( Fig::Parser.new( @application_configuration, :check_include_versions ).parse_package(unparsed_package) ) return end def set_base_package_to_empty_synthetic_one() set_base_package( Fig::Package.new( nil, # Name nil, # Version nil, # File path 'synthetic', '.', # Working '.', # Base [ Fig::Statement::Configuration.new( nil, %Q<[synthetic statement created in #{__FILE__} line #{__LINE__}]>, @base_config, [] ) ], :is_synthetic, ) ) return end def set_base_package(package) @base_package = package package.set_base true return end end
klimkin/fig
lib/fig/command/action/role/list_from_data_structure.rb
<reponame>klimkin/fig # coding: utf-8 require 'set' module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end # Requires #node_content(package, config_name) and #walk_dependency_tree() # methods. module Fig::Command::Action::Role::ListFromDataStructure private def set_up_object_to_be_serialized @package_configs = {} base_package = @execution_context.base_package base_configs = base_display_config_names walk_dependency_tree( base_package, base_configs, include_gather, &package_gather ) base_id = package_id base_package if base_configs.size > 1 @object_to_be_serialized = @package_configs[base_id].keys.collect do |config_name| @package_configs[base_id][config_name] end else @object_to_be_serialized = @package_configs[base_id][base_configs[0]] end end def include_gather visited = Set.new return lambda do |including_package, including_config, included_package, included_config| including_name = including_package.to_s_with_config including_config included_name = included_package.to_s_with_config included_config edge = [including_name, included_name] if ! visited.include? edge visited << edge included_id = package_id included_package including_id = package_id including_package including_hash = @package_configs[including_id][including_config] including_hash['dependencies'] ||= [] including_hash['dependencies'] << @package_configs[included_id][included_config] end end end def package_gather visited = Set.new return lambda do |package, config_name, depth| name = package.to_s_with_config config_name if ! visited.include? name visited << name id = package_id package @package_configs[id] ||= {} @package_configs[id][config_name] = node_content package, config_name end end end def new_package_config_hash(package, config_name) hash = {} if package.name hash['name'] = package.name end if package.version hash['version'] = package.version end if package.file_path hash['file'] = package.file_path end if package.description hash['description'] = package.description end hash['config'] = config_name return hash end def package_id(package) if package.name return package.to_s end if file = package.file_path return "file: #{file}" end return "description: #{package.description}" end end
klimkin/fig
lib/fig/command/action/role/has_no_sub_action.rb
<reponame>klimkin/fig # coding: utf-8 module Fig; end class Fig::Command; end module Fig::Command::Action; end module Fig::Command::Action::Role; end module Fig::Command::Action::Role::HasNoSubAction def sub_action? false end end
klimkin/fig
lib/fig/tokenized_string/plain_segment.rb
# coding: utf-8 module Fig; end class Fig::TokenizedString; end class Fig::TokenizedString::PlainSegment attr_reader :raw_value def initialize(raw_value) @raw_value = raw_value return end def type return nil end def to_expanded_string(&block) return @raw_value.gsub(%r< \\ (.) >xm, '\1') end def to_escaped_string() return @raw_value end # Should not be invoked if original string was single quoted. def to_single_quoted_string() # Raw value will have come from a non-single quoted string, so we unescape # everything (including backslashes) and then escape backslashes and single # quotes (which cannot be escaped outside of single quotes). return \ @raw_value.gsub(%r< \\ (.) >xm, '\1').gsub(%r< ([\\']) >xm, '\\\\\1') end # Should not be invoked if original string was not single quoted. def to_double_quotable_string(metacharacters) quoted_value = @raw_value.gsub %r< ( ["#{metacharacters}] ) >xm, '\\\\\1' quoted_value.gsub!( %r< ( (?: ^ | [^\\] ) # New line or non-backslash (\\{2})* # Even number of backslashes ) # All single quotes must have been escaped. The important bit is to # not lose escaped backslashes. \\' >xm, %q<\1'> ) return quoted_value end end
klimkin/fig
lib/fig/command/coverage_support.rb
<gh_stars>10-100 # coding: utf-8 # This is not a normal module/class. It contains code to be run by bin/fig and # bin/fig-debug when doing coverage. # Depends upon setup done by spec/spec_helper.rb. if ! ENV['FIG_COVERAGE_RUN_COUNT'] || ! ENV['FIG_COVERAGE_ROOT_DIRECTORY'] $stderr.puts \ 'FIG_COVERAGE_RUN_COUNT or FIG_COVERAGE_ROOT_DIRECTORY not set. Cannot do coverage correctly.' exit 1 end require 'simplecov' # Normal load of .simplecov does not work because SimpleCov assumes that # everything is relative to the current directory. The manipulation of # SimpleCov.root below takes care of most things, but that doesn't affect # .simplecov handling done in the "require 'simplecov'" above. load File.expand_path( File.join(ENV['FIG_COVERAGE_ROOT_DIRECTORY'], '.simplecov') ) # We may run the identical fig command-line multiple times, so we need to give # additional value to make the run name unique. SimpleCov.command_name( "fig run #{ENV['FIG_COVERAGE_RUN_COUNT']} (#{ARGV.join(' ')})" ) SimpleCov.root ENV['FIG_COVERAGE_ROOT_DIRECTORY'] SimpleCov.at_exit do # Have to invoke result() in order to get coverage data saved. # # Default at_exit() further invokes format(): # # 1) We save time by not doing it on each fig run and let the rspec run # handle that. # 2) The formatter emits a message to stdout, which screws up tests of # the fig output. SimpleCov.result end SimpleCov.start
klimkin/fig
spec/command/suppress_includes_spec.rb
# coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'fig/operating_system' describe 'Fig' do describe 'include processing' do let(:publish_from_directory) { "#{FIG_SPEC_BASE_DIRECTORY}/publish-home" } before(:each) do clean_up_test_environment FileUtils.mkdir_p CURRENT_DIRECTORY FileUtils.rm_rf(publish_from_directory) FileUtils.mkdir_p(publish_from_directory) fig( %w<--publish dependency/1.2.3 --append FOO=dependency>, :current_directory => publish_from_directory ) input = <<-END config default include dependency/1.2.3 include :level-one add FOO=default end config level-one include :level-two add FOO=level-one end config level-two add FOO=level-two end END fig( %w<--publish dependent/1.2.3>, input, :current_directory => publish_from_directory ) end it 'happens by default' do # Really, this is just a test of the test setup... out, * = fig %w<dependent/1.2.3 --get FOO> out.should == "default#{File::PATH_SEPARATOR}level-one#{File::PATH_SEPARATOR}level-two#{File::PATH_SEPARATOR}dependency" end it 'is limited by --suppress-cross-package-includes' do out, * = fig %w<dependent/1.2.3 --suppress-cross-package-includes --get FOO> out.should == "default#{File::PATH_SEPARATOR}level-one#{File::PATH_SEPARATOR}level-two" end it 'is blocked by --suppress-all-includes' do out, * = fig %w<dependent/1.2.3 --suppress-all-includes --get FOO> out.should == 'default' end end end
klimkin/fig
lib/fig/command/options.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/command/action/clean' require 'fig/command/action/dump_package_definition_for_command_line' require 'fig/command/action/dump_package_definition_parsed' require 'fig/command/action/dump_package_definition_text' require 'fig/command/action/get' require 'fig/command/action/help' require 'fig/command/action/help_long' require 'fig/command/action/list_configs' require 'fig/command/action/list_dependencies' require 'fig/command/action/list_dependencies/all_configs' require 'fig/command/action/list_dependencies/default' require 'fig/command/action/list_dependencies/graphviz' require 'fig/command/action/list_dependencies/graphviz_all_configs' require 'fig/command/action/list_dependencies/json' require 'fig/command/action/list_dependencies/json_all_configs' require 'fig/command/action/list_dependencies/tree' require 'fig/command/action/list_dependencies/tree_all_configs' require 'fig/command/action/list_dependencies/yaml' require 'fig/command/action/list_dependencies/yaml_all_configs' require 'fig/command/action/list_local' require 'fig/command/action/list_remote' require 'fig/command/action/list_variables' require 'fig/command/action/list_variables/all_configs' require 'fig/command/action/list_variables/default' require 'fig/command/action/list_variables/graphviz' require 'fig/command/action/list_variables/graphviz_all_configs' require 'fig/command/action/list_variables/json' require 'fig/command/action/list_variables/json_all_configs' require 'fig/command/action/list_variables/tree' require 'fig/command/action/list_variables/tree_all_configs' require 'fig/command/action/list_variables/yaml' require 'fig/command/action/list_variables/yaml_all_configs' require 'fig/command/action/options' require 'fig/command/action/publish' require 'fig/command/action/publish_local' require 'fig/command/action/run_command_line' require 'fig/command/action/run_command_statement' require 'fig/command/action/source_package' require 'fig/command/action/update' require 'fig/command/action/update_if_missing' require 'fig/command/action/version' require 'fig/command/action/version_plain' require 'fig/command/option_error' require 'fig/command/options/parser' require 'fig/package_descriptor' require 'fig/statement/archive' require 'fig/statement/command' require 'fig/statement/include' require 'fig/statement/path' require 'fig/statement/resource' require 'fig/statement/set' module Fig; end class Fig::Command; end # Command-line processing. class Fig::Command::Options attr_reader :asset_statements attr_reader :command_extra_argv attr_reader :config attr_reader :descriptor attr_reader :environment_statements attr_reader :exit_code attr_reader :figrc attr_reader :file_to_find_package_for attr_reader :home attr_reader :log_config attr_reader :log_to_stdout attr_reader :log_level attr_reader :package_definition_file attr_reader :parser attr_reader :publish_comment attr_reader :publish_comment_path attr_reader :shell_command attr_reader :suppress_cleanup_of_retrieves attr_reader :suppress_includes attr_reader :suppress_retrieves attr_reader :update_lock_response attr_reader :variable_to_get attr_accessor :version_message attr_accessor :version_plain def initialize() @home = ENV['FIG_HOME'] || File.expand_path('~/.fighome') @parser = Fig::Command::Options::Parser.new() end def process_command_line(argv) argv = argv.clone strip_shell_command(argv) set_up_parser() @parser.parse!(argv) if not exit_code.nil? return end if argv.size > 1 $stderr.puts %q<Extra arguments. Should only have a package/version after all other options. Had "> + argv.join(%q<", ">) + %q<" left over.> @exit_code = 1 return end derive_primary_descriptor(argv.first) if not @base_action and @descriptor set_base_action(Fig::Command::Action::RunCommandStatement) end set_up_sub_actions() validate actions().each {|action| action.configure(self)} return end def actions() actions = [] # Update has got to come first so that the Repository knows what's going # on. if @update_action actions << @update_action end if @base_action actions << @base_action end return actions end def force?() return @force end def suppress_vcs_comments_in_published_packages?() return @suppress_vcs_comments_in_published_packages end def short_help_message() return @parser.short_help end def full_help_message() return @parser.full_help + EXTRA_OPTIONS_DESCRIPTION end def options_message() return @parser.options_message + EXTRA_OPTIONS_DESCRIPTION end def login?() return @login end def no_figrc?() return @no_figrc end def no_remote_figrc?() return @no_remote_figrc end def suppress_warning_include_statement_missing_version?() return @suppress_warning_include_statement_missing_version end def suppress_warning_unused_retrieve?() return @suppress_warning_unused_retrieve end private EXTRA_OPTIONS_DESCRIPTION = <<-'END_DESCRIPTION' Running commands: -- end of Fig options; anything after this is used as a command to run --command-extra-args end of Fig options; anything after this is appended to the end of a "command" statement in a "config" block. END_DESCRIPTION # Note that OptionParser insists that the regex match the entire value, not # just matches the regex in general. In effect, OptionParser is wrapping the # regex with "\A" and "\z". STARTS_WITH_NON_HYPHEN = %r< \A [^-] .* >xm def list_all_configs?() return @list_all_configs end def list_tree?() return @list_tree end def json?() return @json end def yaml?() return @yaml end def graphviz?() return @graphviz end def strip_shell_command(argv) argv.each_with_index do |arg, i| case arg when '--' set_base_action(Fig::Command::Action::RunCommandLine) @shell_command = tokenize_command_arguments '--', argv[(i+1)..-1] if @shell_command.empty? raise Fig::Command::OptionError.new( %q<The "--" option was used, but no command was specified.> ) end when '--command-extra-args' set_base_action(Fig::Command::Action::RunCommandStatement) @command_extra_argv = tokenize_command_arguments '--command-extra-args', argv[(i+1)..-1] end if @base_action argv.slice!(i..-1) break end end return end def set_up_parser() set_up_package_definition() set_up_remote_repository_access() set_up_commands() set_up_environment_statements() set_up_asset_statements() set_up_queries() set_up_program_configuration() set_up_help() return end FILE_OPTION_VALUE_PATTERN = %r< \A (?: - # Solely a hyphen, to allow for stdin | [^-] .* # or anything not starting with a hyphen. ) \z >x def set_up_package_definition() @parser.separator 'Package definition:' @parser.on( '-c', '--config CONFIG', STARTS_WITH_NON_HYPHEN, %q<apply configuration CONFIG, default is "default"> ) do |config| @config = config end @parser.on( '--file FILE', FILE_OPTION_VALUE_PATTERN, %q<read package definition FILE. Use '-' for stdin. See also --no-file> ) do |path| set_package_definition_file(path) end @parser.on( '--no-file', 'ignore package.fig/application.fig file in current directory' ) do set_package_definition_file(:none) end @parser.on( '--suppress-all-includes', %q<don't process include statements>, ) do set_suppress_includes(:all) end @parser.on( '--suppress-cross-package-includes', %q<don't process includes of configs from other packages>, ) do set_suppress_includes(:cross_package) end return end def set_up_remote_repository_access() @parser.separator '' @parser.separator 'Remote repository access:' @parser.on( '-u', '--update', 'check remote repo for updates, download to $FIG_HOME and process retrieves' ) do set_update_action(Fig::Command::Action::Update) end @parser.on( '-m', '--update-if-missing', 'check remote repo for updates only if package missing from $FIG_HOME' ) do set_update_action(Fig::Command::Action::UpdateIfMissing) end @parser.on( '-R', '--suppress-retrieves', %q<don't process retrieves, even if they would otherwise be active>, ) do @suppress_retrieves = true end @parser.on( '--suppress-cleanup-of-retrieves', %q<don't delete files from unreferenced retrieves>, ) do @suppress_cleanup_of_retrieves = true end @parser.on( '-l', '--login', 'login to FTP repo as a non-anonymous user' ) do @login = true end return end def set_up_commands() @parser.separator '' @parser.separator 'Commands:' @parser.on( '--publish', 'install package in $FIG_HOME and in remote repo' ) do |publish| set_base_action(Fig::Command::Action::Publish) end @parser.on( '--publish-local', 'install package only in $FIG_HOME' ) do |publish_local| set_base_action(Fig::Command::Action::PublishLocal) end @parser.on( '--publish-comment COMMENT', STARTS_WITH_NON_HYPHEN, 'comment to include in published package' ) do |comment| @publish_comment = comment end @parser.on( '--publish-comment-file PATH', STARTS_WITH_NON_HYPHEN, 'file to include as a comment in published package' ) do |path| @publish_comment_path = path end @force = nil @parser.on( '--force', 'force-overwrite existing version of a package to the remote repo' ) do |force| @force = force end @parser.on( '--suppress-vcs-comments-in-published-packages', %q<don't attempt to identify version control information when publishing> ) do |suppress| @suppress_vcs_comments_in_published_packages = suppress end @parser.on('--clean', 'remove package from $FIG_HOME') do set_base_action(Fig::Command::Action::Clean) end @parser.on( '--run-command-statement', 'run the command in package definition file (i.e. with no package descriptor specified)' ) do set_base_action(Fig::Command::Action::RunCommandStatement) end return end def set_up_environment_statements() @parser.separator '' @parser.separator 'Environment variable statement equivalents:' @environment_statements = [] @parser.on( '-p', '--append VARIABLE=VALUE', STARTS_WITH_NON_HYPHEN, 'append (actually, prepend) VALUE to PATH-like environment variable VARIABLE' ) do |name_value| @environment_statements << new_variable_statement('--append', name_value, Fig::Statement::Path) end @parser.add_argument_description( %w<-p --append>, %q<The value of this option must look like "NAME=VALUE".> ) @parser.on( '--add VARIABLE=VALUE', STARTS_WITH_NON_HYPHEN, 'prepend VALUE to PATH-like environment variable VARIABLE (synonym for --append)' ) do |name_value| @environment_statements << new_variable_statement('--add', name_value, Fig::Statement::Path) end @parser.add_argument_description( %w<--add>, %q<The value of this option must look like "NAME=VALUE".> ) @parser.on( '-s', '--set VARIABLE=VALUE', STARTS_WITH_NON_HYPHEN, 'set environment variable VARIABLE to VALUE' ) do |name_value| @environment_statements << new_variable_statement('--set', name_value, Fig::Statement::Set) end @parser.add_argument_description( %w<-s --set>, %q<The value of this option must look like "NAME=VALUE".> ) @parser.separator '' @parser.separator 'Package includes and overrides:' @parser.on( '-i', '--include DESCRIPTOR', STARTS_WITH_NON_HYPHEN, 'include package/version:config specified in DESCRIPTOR in environment' ) do |descriptor_string| statement = Fig::Statement::Include.new( nil, '--include option', Fig::Statement::Include.parse_descriptor( descriptor_string, :validation_context => ' given in a --include option' ), nil, nil ) # We've never allowed versionless includes from the command-line. Hooray! statement.complain_if_version_missing() @environment_statements << statement end @parser.on( '--include-file PATH:CONFIG', STARTS_WITH_NON_HYPHEN, 'include package-definition-in-file:config in environment (incompatible with --publish)' ) do |path_with_config| path, config_name = Fig::Statement::IncludeFile.parse_path_with_config(path_with_config) { |message| @parser.raise_invalid_argument( '--include-file', path_with_config, message ) } statement = Fig::Statement::IncludeFile.new( nil, '--include-file option', path, config_name, nil, ) @environment_statements << statement end @parser.on( '--override DESCRIPTOR', STARTS_WITH_NON_HYPHEN, 'dictate version of package as specified in DESCRIPTOR' ) do |descriptor_string| descriptor = Fig::Statement::Override.parse_descriptor( descriptor_string, :validation_context => ' given in a --override option' ) statement = Fig::Statement::Override.new( nil, '--override option', descriptor.name, descriptor.version ) @environment_statements << statement end return end def set_up_asset_statements() @parser.separator '' @parser.separator 'Asset statement equivalents:' @asset_statements = [] @parser.on( '--archive PATH', STARTS_WITH_NON_HYPHEN, 'include PATH archive in package (when using --publish)' ) do |path| @asset_statements << new_asset_statement('--archive', path, Fig::Statement::Archive) end @parser.on( '--resource PATH', STARTS_WITH_NON_HYPHEN, 'include PATH resource in package (when using --publish)' ) do |path| @asset_statements << new_asset_statement('--resource', path, Fig::Statement::Resource) end return end def set_up_queries() @parser.separator '' @parser.separator 'Querying:' @parser.on( '-g', '--get VARIABLE', STARTS_WITH_NON_HYPHEN, 'print value of environment variable VARIABLE' ) do |variable_to_get| set_base_action(Fig::Command::Action::Get) @variable_to_get = variable_to_get end @parser.on( '--source-package FILE', STARTS_WITH_NON_HYPHEN, 'print package FILE was retrieved from' ) do |file_to_find_package_for| set_base_action(Fig::Command::Action::SourcePackage) @file_to_find_package_for = file_to_find_package_for end @parser.on( '-T', '--dump-package-definition-text', 'emit the unparsed definition of the base package, if there is one' ) do set_base_action(Fig::Command::Action::DumpPackageDefinitionText) end @parser.on( '--dump-package-definition-parsed', 'emit the parsed definition of the base package' ) do set_base_action(Fig::Command::Action::DumpPackageDefinitionParsed) end @parser.on( '--dump-package-definition-for-command-line', 'emit the synthetic package for the other options (--set/--archive/etc.)' ) do set_base_action(Fig::Command::Action::DumpPackageDefinitionForCommandLine) end set_up_listings() return end def set_up_listings() @parser.separator '' @parser.separator 'Querying repository contents:' option_mapping = { :local_packages => [ ['--list-local', '--list', 'list packages in $FIG_HOME'], Fig::Command::Action::ListLocal ], :remote_packages => [ ['--list-remote', 'list packages in remote repository'], Fig::Command::Action::ListRemote ], } option_mapping.each_pair do | type, specification_action_class | specification, action_class = *specification_action_class @parser.on(*specification) do set_base_action(action_class) end end @parser.separator '' @parser.separator 'Querying package data:' option_mapping = { :configs => [ ['--list-configs', 'list configurations'], Fig::Command::Action::ListConfigs ], :dependencies => [ ['--list-dependencies', 'list package dependencies, recursively'], Fig::Command::Action::ListDependencies ], :variables => [ [ '--list-variables', 'list all variables defined/used by package and its dependencies' ], Fig::Command::Action::ListVariables ], } option_mapping.each_pair do | type, specification_action_class | specification, action_class = *specification_action_class @parser.on(*specification) do set_base_action(action_class) end end @parser.on( '--list-tree', 'for listings, output a tree instead of a list' ) do @list_tree = true end @parser.on( '--json', 'for listings, output JSON (http://json.org)' ) do @json = true end @parser.on( '--yaml', 'for listings, output YAML (http://yaml.org)' ) do @yaml = true end @parser.on( '--graphviz', 'for listings, output DOT (http://graphviz.org/content/dot-language)' ) do @graphviz = true end @parser.on( '--list-all-configs', 'for listings, follow all configurations of the base package' ) do @list_all_configs = true end return end LOG_LEVELS = %w< off fatal error warn info debug all > LOG_ALIASES = { 'warning' => 'warn' } def set_up_program_configuration() @parser.separator '' @parser.separator 'Fig configuration:' @parser.on( '--figrc PATH', STARTS_WITH_NON_HYPHEN, 'add PATH to configuration used for Fig' ) do |path| @figrc = path end @parser.on('--no-figrc', 'ignore ~/.figrc') { @no_figrc = true } @parser.on('--no-remote-figrc', 'ignore $FIG_REMOTE_URL/_meta/figrc') { @no_remote_figrc = true } @parser.on( '--log-config PATH', STARTS_WITH_NON_HYPHEN, 'use PATH file as configuration for Log4r' ) do |path| @log_config = path end @parser.on( '--log-to-stdout', 'write log output to stdout instead of stderr', ) do @log_to_stdout = true end level_list = LOG_LEVELS.join(', ') @parser.on( '--log-level LEVEL', LOG_LEVELS, LOG_ALIASES, 'set logging level to LEVEL', " (#{level_list})" ) do |log_level| @log_level = log_level end @update_lock_response = nil # Nil means wait, but warn. update_lock_responses = [:wait, :fail, :ignore] response_list = update_lock_responses.join(', ') @parser.on( '--update-lock-response TYPE', update_lock_responses, 'what to do when update lock already exists', " (#{response_list}, default is wait)" ) do |response| @update_lock_response = response end @parser.on( '--suppress-warning-include-statement-missing-version', %q<don't complain about an include statement without a version> ) do @suppress_warning_include_statement_missing_version = true end @parser.on( '--suppress-warning-unused-retrieve', %q<don't complain about a retrieve statement that isn't used> ) do @suppress_warning_unused_retrieve = true end return end def set_up_help() @parser.separator '' @parser.separator 'Help:' @parser.on( '-?', '-h', '--help', 'display short usage summary' ) do set_base_action(Fig::Command::Action::Help) end @parser.on( '--help-long', 'display full usage' ) do set_base_action(Fig::Command::Action::HelpLong) end @parser.on( '--options', 'just list Fig options' ) do set_base_action(Fig::Command::Action::Options) end @parser.on('-v', '--version', 'print Fig version') do set_base_action(Fig::Command::Action::Version) end @parser.on( '--version-plain', 'print Fig version without embellishment (no newline)' ) do set_base_action(Fig::Command::Action::VersionPlain) end end def set_base_action(action_class) action = action_class.new # Help overrides anything. if action_class == Fig::Command::Action::Help @base_action = action return end if @base_action return if @base_action.class == Fig::Command::Action::Help return if @base_action.class == action_class end if @base_action raise Fig::Command::OptionError.new( "Cannot specify both #{@base_action.primary_option()} and #{action.primary_option()}." ) end @base_action = action return end def set_package_definition_file(value) if @package_definition_file raise Fig::Command::OptionError.new( 'Can only specify one --file/--no-file option.' ) end @package_definition_file = value return end def set_suppress_includes(value) if @suppress_includes raise Fig::Command::OptionError.new( 'Can only specify one --suppress-all-includes/--suppress-cross-package-includes option.' ) end @suppress_includes = value return end def set_update_action(update_action_class) update_action = update_action_class.new if @update_action raise Fig::Command::OptionError.new( "Cannot specify both #{@update_action.primary_option()} and #{update_action.primary_option()}." ) end @update_action = update_action return end def new_variable_statement(option, name_value, statement_class) variable, value = statement_class.parse_name_value(name_value) { |message| @parser.raise_invalid_argument(option, name_value, message) } return statement_class.new(nil, "#{option} option", variable, value) end def new_asset_statement(option, raw_path, statement_class) tokenized_path = statement_class.validate_and_process_escapes_in_location(raw_path) do |error_description| @parser.raise_invalid_argument(option, raw_path, error_description) end path = tokenized_path.to_expanded_string need_to_glob = ! tokenized_path.single_quoted? return statement_class.new(nil, "#{option} option", path, need_to_glob) end def validate() if suppress_includes # Not conceptually incompatible, just not implemented (would need to # handle in command/action/role/list_*) if list_tree? raise Fig::Command::OptionError.new( 'Cannot use --suppress-all-includes/--suppress-cross-package-includes with --list-tree.' ) elsif json? raise Fig::Command::OptionError.new( 'Cannot use --suppress-all-includes/--suppress-cross-package-includes with --json.' ) elsif yaml? raise Fig::Command::OptionError.new( 'Cannot use --suppress-all-includes/--suppress-cross-package-includes with --yaml.' ) elsif graphviz? raise Fig::Command::OptionError.new( 'Cannot use --suppress-all-includes/--suppress-cross-package-includes with --graphviz.' ) elsif list_all_configs? raise Fig::Command::OptionError.new( 'Cannot use --suppress-all-includes/--suppress-cross-package-includes with --list-all-configs.' ) elsif @base_action if @base_action.list_dependencies? raise Fig::Command::OptionError.new( %q<It doesn't make much sense to suppress dependencies when attempting to list them.> ) elsif @base_action.publish? # Don't want to support broken publishes (though versionless includes # are pretty broken). raise Fig::Command::OptionError.new( 'Cannot use --suppress-all-includes/--suppress-cross-package-includes when publishing.' ) end end elsif list_tree? validate_list_option '--list-tree' elsif json? validate_list_option '--json' elsif yaml? validate_list_option '--yaml' elsif graphviz? validate_list_option '--graphviz' elsif list_all_configs? validate_list_option '--list-all-configs' end if list_tree? validate_list_options_with_nodes('--list-tree') end if list_all_configs? validate_list_options_with_nodes('--list-all-configs') end if graphviz? if json? raise Fig::Command::OptionError.new( 'Cannot use --graphviz and --json at the same time.' ) elsif yaml? raise Fig::Command::OptionError.new( 'Cannot use --graphviz and --yaml at the same time.' ) end end if json? and yaml? raise Fig::Command::OptionError.new( 'Cannot use --json and --yaml at the same time.' ) end if @publish_comment && (! @base_action || ! @base_action.publish?) raise Fig::Command::OptionError.new( 'Cannot use --publish-comment when not publishing.' ) end if @publish_comment_path && (! @base_action || ! @base_action.publish?) raise Fig::Command::OptionError.new( 'Cannot use --publish-comment-file when not publishing.' ) end if @log_to_stdout && @log_config raise Fig::Command::OptionError.new( 'Cannot use --log-to-stdout and --log-config at the same time.' ) end return end def validate_list_option(option) if ( ! @base_action \ || ! @base_action.list_dependencies? && ! @base_action.list_variables? ) raise Fig::Command::OptionError.new( %Q<The #{option} option isn't useful without --list-dependencies/--list-variables.> ) end return end def validate_list_options_with_nodes(conflicting_option) if graphviz? raise Fig::Command::OptionError.new( "Cannot use #{conflicting_option} and --graphviz at the same time." ) elsif json? raise Fig::Command::OptionError.new( "Cannot use #{conflicting_option} and --json at the same time." ) elsif yaml? raise Fig::Command::OptionError.new( "Cannot use #{conflicting_option} and --json at the same time." ) end return end def set_up_sub_actions() if @base_action and @base_action.sub_action? # This is a cheat because the only things with sub-actions at present are # --list-dependencies and --list-variables. This will need to be # refactored if we get further sub-action actions. sub_action_name = :Default if list_tree? sub_action_name = list_all_configs? ? :TreeAllConfigs : :Tree elsif json? sub_action_name = list_all_configs? ? :JSONAllConfigs : :JSON elsif yaml? sub_action_name = list_all_configs? ? :YAMLAllConfigs : :YAML elsif graphviz? sub_action_name = list_all_configs? ? :GraphvizAllConfigs : :Graphviz elsif list_all_configs? sub_action_name = :AllConfigs end @base_action.sub_action = @base_action.class.const_get(sub_action_name).new end end # This will be the base package, unless we're publishing (in which case it's # the name to publish to). def derive_primary_descriptor(raw_string) return if raw_string.nil? @descriptor = Fig::PackageDescriptor.parse( raw_string, :name => :required, :version => :required, :validation_context => ' specified on command line' ) if @descriptor.config && config() $stderr.puts \ %Q<Cannot specify both --config and a config in the descriptor "#{raw_string}".> @exit_code = 1 end return end def tokenize_command_arguments(option, arguments) return arguments.map do |argument| Fig::Statement::Command.validate_and_process_escapes_in_argument( argument ) do |error_description| @parser.raise_invalid_argument(option, argument, error_description) end end end end
klimkin/fig
lib/fig/command/action/publish_local.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/command/action' require 'fig/command/action/role/has_no_sub_action' require 'fig/command/action/role/publish' require 'fig/logging' module Fig; end class Fig::Command; end module Fig::Command::Action; end class Fig::Command::Action::PublishLocal include Fig::Command::Action include Fig::Command::Action::Role::HasNoSubAction include Fig::Command::Action::Role::Publish def options() return %w<--publish-local> end def execute() publish_preflight() Fig::Logging.info "Publishing #{@descriptor.to_string()} locally." @execution_context.repository.publish_package( @publish_statements, @descriptor, :publish_local, @execution_context.base_package, false ) return EXIT_SUCCESS end end
klimkin/fig
lib/fig/url_access_disallowed_error.rb
<reponame>klimkin/fig # coding: utf-8 require 'fig/user_input_error' module Fig # Package definition attempted to specify a URL outside of the whitelist. class URLAccessDisallowedError < UserInputError attr_reader :urls, :descriptor def initialize(urls, descriptor) @urls = urls @descriptor = descriptor end end end
klimkin/fig
lib/fig/statement/include_file.rb
<filename>lib/fig/statement/include_file.rb # coding: utf-8 require 'fig/package_descriptor' require 'fig/statement' require 'fig/user_input_error' module Fig; end # Like an include, but of an unpublished file. class Fig::Statement::IncludeFile < Fig::Statement def self.parse_path_with_config(path_with_config, &block) if match = PATH_WITH_CONFIG_PATTERN.match(path_with_config) return validate_and_process_raw_path_and_config_name( match[:path], match[:config], &block ) end yield 'could not be understood as a path followed by a config name.' return end def self.validate_and_process_raw_path_and_config_name( raw_path, config_name, &block ) if raw_path !~ /['"]/ && raw_path =~ /:/ yield 'has an unquoted colon (:) in the path portion.' return end if ( ! config_name.nil? && config_name !~ Fig::PackageDescriptor::COMPONENT_PATTERN ) yield "contains an invalid config name (#{config_name})." return end tokenized_path = validate_and_process_escapes_in_path(raw_path, &block) return if tokenized_path.nil? return tokenized_path.to_expanded_string, config_name end private def self.validate_and_process_escapes_in_path(path, &block) return Fig::StringTokenizer.new.tokenize(path, &block) end public attr_reader :path attr_reader :config_name attr_reader :containing_package_descriptor def initialize( line_column, source_description, path, config_name, containing_package_descriptor ) super(line_column, source_description) @path = path @config_name = config_name @containing_package_descriptor = containing_package_descriptor end def statement_type() return 'include-file' end def full_path_relative_to(including_package) return File.expand_path(path, including_package.include_file_base_directory) end def deparse_as_version(deparser) return deparser.include_file(self) end def minimum_grammar_for_emitting_input() return [2, %q<didn't exist prior to v2>] end def minimum_grammar_for_publishing() raise Fig::UserInputError.new 'Cannot publish an include-file statement.' end private PATH_WITH_CONFIG_PATTERN = / \A (?<path> .+?) (?: [:] (?<config> #{Fig::PackageDescriptor::UNBRACKETED_COMPONENT_PATTERN}) )? \z /x end
xsoulsyndicate/yp-api
lib/yp_api/review.rb
require "json" class YpApi::Review attr_accessor :rating, :review_body, :review_date, :review_subject, :reviewer @@path = "/search-api/search/devapi/reviews" def self.path @@path end def self.find(id) res = YpApi::Connection.get(path,:format => :json,:listingid => id.to_s) data = JSON.parse(res)['ratingsAndReviewsResult'] return [] unless data && data["reviews"] && data["reviews"]["review"] reviews = [] data["reviews"]["review"].each do |review_json| reviews << new(review_json) end reviews end def initialize(data = {}) data.each do |name,val| send("#{name.scan(/[a-z0-9]+|[A-Z]+[a-z0-9]*/).map(&:downcase).join("_")}=",val) end end end
xsoulsyndicate/yp-api
spec/yp_api_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe YpApi do subject{described_class} it {should respond_to :key} it {should respond_to 'key='} it {should respond_to :base_url} it {should respond_to 'base_url='} end
xsoulsyndicate/yp-api
lib/yp-api.rb
# bootstrap file require 'yp_api' require 'yp_api/version' require 'yp_api/connection' require 'yp_api/listing' require 'yp_api/review'
xsoulsyndicate/yp-api
spec/spec_helper.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'rspec' require 'yaml' require 'ruby-debug' require 'webmock/rspec' require 'rack' require 'yp-api' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} def file_fixture(filename) open(File.join(File.dirname(__FILE__), 'fixtures', "#{filename.to_s}")).read end RSpec.configure do |config| config.before(:suite) do WebMock.disable_net_connect! end config.after(:suite) do WebMock.allow_net_connect! end end
xsoulsyndicate/yp-api
lib/yp_api/listing.rb
<filename>lib/yp_api/listing.rb require "json" class YpApi::Listing attr_accessor :accreditations, :ad_image, :ad_image_click, :additional_texts, :after_hours_phone, :akas, :amenities, :associations, :attribution, :attribution_logo, :audio_url, :average_rating, :base_click_url, :business_name, :categories, :certification, :city, :claimed, :claimed_status, :coupon_flag, :coupon_image_url, :coupon_url, :coupons, :custom_link, :custom_link_text, :description1, :description2, :detailed_hours, :distrib_ad_image, :distrib_ad_image_click, :email, :emergency_phone, :extra_emails, :extra_fax, :extra_phone, :extra_toll_free, :extra_website_urls, :features, :general_info, :has_display_address, :has_priority_shading, :in_business_since, :is_red_listing, :languages_spoken, :latitude, :listing_id, :longitude, :mobile_phone, :more_info_url, :neighborhoods, :omit_address, :omit_phone, :open_hours, :open_status, :payment_methods, :phone, :primary_category, :print_ad_image, :print_ad_image_click, :rating_count, :services, :slogan, :state, :street, :video_url, :view_phone, :website_url, :zip @@path = "/search-api/search/devapi/details" def self.path @@path end def self.find(id) res = YpApi::Connection.get(path,:format => :json,:listingid => id.to_s) data = JSON.parse(res)['listingsDetailsResult'] #debugger return nil unless data && data["listingsDetails"] && data['listingsDetails']['listingDetail'] new(data['listingsDetails']['listingDetail'].first) end def initialize(data = {}) data.each do |name,val| send("#{name.scan(/[a-z0-9]+|[A-Z]+[a-z0-9]*/).map(&:downcase).join("_")}=",val) end end end
xsoulsyndicate/yp-api
spec/connection_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe YpApi::Connection do subject{described_class} it{should respond_to :get} context "calling .get with a valid api path and url params" do before do @valid_path = "/listings/v1/search" @valid_params = {:searchloc => 83854, :term => "saw blades",:key => YpApi.key} @full_url = YpApi.base_url + @valid_path + '?' + URI.encode_www_form(@valid_params) stub_request(:any,@full_url).to_return(:body => "{}") end describe "the response" do subject{described_class.get(@valid_path,@valid_params)} it {should be_a RestClient::Response} its(:code){should be 200} end end end
xsoulsyndicate/yp-api
lib/yp_api/connection.rb
<reponame>xsoulsyndicate/yp-api<filename>lib/yp_api/connection.rb require 'rest_client' class YpApi::Connection def self.get(path,opts = {}) RestClient.get(YpApi.base_url + path,:params => opts.merge(:key => YpApi.key)) end end
xsoulsyndicate/yp-api
spec/support/testing.rb
<reponame>xsoulsyndicate/yp-api module YpApi module Testing def stub_api_response(verb,url,opts = {}) api = FakeApi.new(opts) stub_request(verb,url).to_rack(api) api # return instance end def file_fixture(filename) open(File.join(File.dirname(__FILE__), 'fixtures', "#{filename.to_s}")).read end class FakeApi attr_accessor :headers, :response_code, :body, :auth def initialize(opts) self.response_code = opts[:code] || 200 self.headers = { 'Content-Type' => opts[:content_type] || 'text/plain' } self.body = opts[:body] || '' end def response # Extracted for message testing in rspec # inst.should_receive(:call){|env| ... test input ... }.and_return(inst.response) [@response_code,@headers,[@body.strip]] end def call(env) response end def body=(b) @headers['Content-Length'] = b.length.to_s @body = b end end end end
xsoulsyndicate/yp-api
spec/listing_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe YpApi::Listing do subject{described_class} it {should respond_to :path} describe ".find" do context "Given a valid listing_id(81344) as the first parameter" do before do @listing_id = 81344 full_url = YpApi.base_url + YpApi::Listing.path + "?" + URI.encode_www_form(:format => :json,:key => YpApi.key,:listingid=>@listing_id) stub_request(:get,full_url).to_return(:body => file_fixture('listing_81344.json')) end describe "The Result" do subject{YpApi::Listing.find(@listing_id)} it {should be_a YpApi::Listing} its(:listing_id){should eql @listing_id} its(:business_name){should_not be_nil} end end end end
xsoulsyndicate/yp-api
lib/yp_api.rb
<gh_stars>0 module YpApi @@base_url = "http://pubapi.yp.com" @@key = "CHANGEME" def self.key @@key end def self.key=(k) @@key = k end def self.base_url @@base_url end def self.base_url=(u) @@base_url = u end end
xsoulsyndicate/yp-api
spec/review_spec.rb
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') describe YpApi::Review do subject{described_class} it {should respond_to :path} describe ".find" do context "Given a valid listing_id(81344) as the first parameter" do before do @listing_id = 81344 full_url = YpApi.base_url + YpApi::Review.path + "?" + URI.encode_www_form(:format => :json,:key => YpApi.key,:listingid=>@listing_id) stub_request(:get,full_url).to_return(:body => file_fixture('review_81344.json')) end describe "The Result" do subject{YpApi::Review.find(@listing_id)} it {should be_a Array} its(:count){should eql 5} its(:first){should be_a YpApi::Review} end end context "Given a valid listing_id(7602113) with no reviews" do before do @listing_id = 7602113 full_url = YpApi.base_url + YpApi::Review.path + "?" + URI.encode_www_form(:format => :json,:key => YpApi.key,:listingid=>@listing_id) stub_request(:get,full_url).to_return(:body => file_fixture('review_none_7602113.json')) end describe "The Result" do subject{YpApi::Review.find(@listing_id)} it {should be_a Array} its(:count){should eql 0} end end end end
Dremora/homebrew-cask
Casks/psequel.rb
cask :v1 => 'psequel' do version '1.3.3' sha256 'b73e2eb0f7eb03704b284009182caf202617d7410328dff48d6634f45e3fb098' url "http://www.psequel.com/download?version=#{version}" name 'PSequel' homepage 'http://www.psequel.com' license :closed app 'PSequel.app' end
Dremora/homebrew-cask
Casks/black-ink.rb
<reponame>Dremora/homebrew-cask cask :v1 => 'black-ink' do version '1.6.2' sha256 '4bce28eaa25f980c0e13147594c503b97276f4be1738a823a3eb909ea4fec002' url "https://red-sweater.com/blackink/BlackInk#{version}.zip" appcast 'https://red-sweater.com/blackink/appcast1.php', :sha256 => '2c18470c2510e32cf8eacc19867067f88d5f01fd8f9fd6aa590d0237d4984695' name '<NAME>' homepage 'https://red-sweater.com/blackink/' license :commercial app 'Black Ink.app' end
Dremora/homebrew-cask
Casks/nomad.rb
<gh_stars>0 cask :v1 => 'nomad' do version '0.1.2' sha256 '8fcff1029c6cc9bf24ee441d749ef1039a6132e62ef486561a8a8d9e6e519fbf' # hashicorp.com is the official download host per the vendor homepage url "https://releases.hashicorp.com/nomad/#{version}/nomad_#{version}_darwin_amd64.zip" name 'Nomad' homepage 'https://nomadproject.io/' license :mpl binary 'nomad' end
Dremora/homebrew-cask
Casks/todoist.rb
<gh_stars>0 cask :v1 => 'todoist' do version '6.0.3' sha256 '5457917cbc22092e12f736dfd7b1d22a2cb62ad0cda82d7b1c053fe287d9112e' # cloudfront.net is the official download host per the appcast feed url 'https://d2dq6e731uoz0t.cloudfront.net/f34bc666b8a2458496a5c00a115f7cbd/as/Todoist.zip' appcast 'https://todoist.com/static/native_apps/mac_app.xml' name 'Todoist' homepage 'https://todoist.com' license :gratis app 'Todoist.app' postflight do suppress_move_to_applications end zap :delete => [ '~/Library/Application Support/Todoist', '~/Library/Preferences/com.todoist.mac.Todoist.plist', ] end
Dremora/homebrew-cask
Casks/codekit.rb
cask :v1 => 'codekit' do version '2.5.1-19076' sha256 '7e41f7a0e3b36607fb33a758d21f1f51ea3902888448facd26ddf009b4c79f70' url "https://incident57.com/codekit/files/codekit-#{version.sub(%r{.*-},'')}.zip" appcast 'https://incident57.com/codekit/appcast/ck2appcast.xml', :sha256 => '72fc08fe815cb3faf6a6fb19dfcb4f0c4f0494bbdb7b1e8da8b87772db5dd88c' name 'CodeKit' homepage 'https://incident57.com/codekit/' license :commercial app 'CodeKit.app' end
Dremora/homebrew-cask
Casks/extrabuildphase.rb
cask :v1 => 'extrabuildphase' do version '0.3' sha256 'd4023faf158677b455458cb4ce4267e27907bf790fed29fc8d046099dc477277' url "https://github.com/norio-nomura/ExtraBuildPhase/releases/download/#{version}/ExtraBuildPhase-#{version}.pkg" appcast 'https://github.com/norio-nomura/ExtraBuildPhase/releases.atom' name 'ExtraBuildPhase' homepage 'https://github.com/norio-nomura/ExtraBuildPhase' license :mit pkg "ExtraBuildPhase-#{version}.pkg" uninstall :pkgutil => 'io.github.norio-nomura.ExtraBuildPhase' end
Dremora/homebrew-cask
Casks/qtpass.rb
cask :v1 => 'qtpass' do version '1.0.4' sha256 'cb5eb74ba37ded2a36d3362cc85e4a3c45aad095be7fe77252eab885f7d32c86' url "https://github.com/IJHack/qtpass/releases/download/v#{version}/qtpass-#{version}.dmg" appcast 'https://github.com/IJHack/qtpass/releases.atom' name 'QtPass' homepage 'https://qtpass.org/' license :gpl app 'QtPass.app' end
alexruperez/SafeBrowsing
SafeBrowsing.podspec
Pod::Spec.new do |s| s.name = 'SafeBrowsing' s.version = '0.1.2' s.summary = 'Protect your users against malware and phishing threats using Google Safe Browsing' s.homepage = 'https://github.com/alexruperez/SafeBrowsing' s.license = { :type => 'MIT', :file => 'LICENSE' } s.authors = { '<NAME>' => '<EMAIL>' } s.source = { :git => 'https://github.com/alexruperez/SafeBrowsing.git', :tag => s.version.to_s } s.social_media_url = "https://twitter.com/alexruperez" s.ios.deployment_target = '10.0' s.source_files ="SafeBrowsing/*.{h,swift}" end
rubenandrebarreiro/blockchain-on-rails-demo
blockchain-on-rails-demo.rb
# BLOCKCHAIN ON RAILS DEMO # Description: # - A simple Demo for a Blockchain, in Ruby on Rails; # Author: # - <NAME> # - Computer Science/Engineering #!/usr/bin/ruby -w puts "\n\n\n-- WELCOME TO THE BLOCKCHAIN ON RAILS DEMO --\n\n"; class Client @@no_of_clients = 0 def initialize(id, first_name, last_name) @client_id = id @client_first_name = first_name @client_last_name = last_name @client_money_balance = 0.0 @client_gems = 0.0 end def get_client_id() @client_id end def get_client_first_name() @client_first_name end def get_client_last_name() @client_last_name end def get_client_money_balance() @client_money_balance end def set_client_money_balance(client_new_money_balance) @client_money_balance = client_new_money_balance end def get_client_gems() @client_gems end def set_client_gems(client_new_gems) @client_gems = client_new_gems end end # Array of Registered Clients clients = Array.new # Array of Transactions transactions = Array.new # Array of Opened Transactions opened_transactions = Array.new # Array of Closed Transactions closed_transactions = Array.new # Array of Mined Blocks mined_blocks = Array.new $choice = -1 while(true) do # Main Menu - Choose Option while $choice < 0 or $choice > 12 do puts("Please, choose an option, from the following:\n\n") puts("0) Create a Client;") puts("1) Deposit Money for a Client; [NOTE: Just For Fun/Debug]") puts("2) Withdraw Money for a Client; [NOTE: Just For Fun/Debug]") puts("3) Transfer Money between Clients; [NOTE: Just For Fun/Debug]") puts("4) Deposit Gems for a Client; [NOTE: Just For Fun/Debug]") puts("5) Withdraw Gems for a Client; [NOTE: Just For Fun/Debug]") puts("6) Transfer Gems between Clients; [NOTE: Just For Fun/Debug]") puts("7) Create a Transaction;") puts("8) Create and Try to Solve a Block of Transactions;") puts("9) List all the Registered Clients;") puts("10) List all the Transactions;") puts("11) List all the Closed/Mined Blocks;") puts("12) Exit/Quit") puts("\n\n") $choice = gets.chomp.to_i puts("\n\n") end # Chosen Option #0 - Create Client if($choice == 0) $client_id = clients.length $client_first_name = -1 $client_last_name = -1 puts("Choose the First Name for the Client:") $client_first_name = gets.chomp puts("\n\n") puts("Choose the Last Name for the Client:") $client_last_name = gets.chomp puts("\n\n") $new_client = Client.new($client_id, $client_first_name, $client_last_name) clients.push($new_client) puts("\nClient created successfully!!!") $choice = -1 end # Chosen Option #1 - Deposit Money for a Client if($choice == 1) $client_found = false $client_id = -1 $client_money_amount_deposit = -1 puts("Choose the Client ID:") $client_id = gets.chomp.to_i puts("\n\n") puts("Choose the Money Amount to be Deposited:") $client_money_amount_deposit = gets.chomp.to_f puts("\n\n") clients.each do |client| if(client.get_client_id == $client_id) $client_old_amount = client.get_client_money_balance $client_new_amount = $client_old_amount + $client_money_amount_deposit client.set_client_money_balance($client_new_amount) $client_found = true end end if($client_found == true) puts("\nClient deposited %0.2f EUR successfully!!!" % [$client_money_amount_deposit]) else puts("\nClient with the given ID not found!!!") end $choice = -1 end # Chosen Option #2 - Withdraw Money for a Client if($choice == 2) $client_found = false $client_id = -1 $client_money_amount_withraw = -1 $client_old_amount = -1 puts("Choose the Client ID:") $client_id = gets.chomp.to_i puts("\n\n") puts("Choose the Money Amount to be Withdrawn:") $client_money_amount_withraw = gets.chomp.to_f puts("\n\n") clients.each do |client| if(client.get_client_id == $client_id) $client_old_amount = client.get_client_money_balance if( ($client_old_amount - $client_money_amount_withraw) >= 0) $client_new_amount = $client_old_amount - $client_money_amount_withraw client.set_client_money_balance($client_new_amount) end $client_found = true end end if($client_found == true) if( ($client_old_amount - $client_money_amount_withraw) < 0) puts("\nClient don't have the necessary Money Amount Balance to do this operation!!!") else puts("\nClient withrawn %0.2f EUR successfully!!!" % [$client_money_amount_withraw]) end else puts("\nClient with the given ID not found!!!") end $choice = -1 end # Chosen Option #3 - Transfer Money between Clients if($choice == 3) $client_from_found = false $client_to_found = false $client_from_id = -1 $client_to_id = -1 $client_money_amount_transfer = -1 $client_from_old_amount = -1 $client_to_old_amount = -1 puts("Choose the FROM Client ID:") $client_from_id = gets.chomp.to_i puts("\n\n") puts("Choose the TO Client ID:") $client_to_id = gets.chomp.to_i puts("\n\n") puts("Choose the Money Amount to be Transferred:") $client_money_amount_transfer = gets.chomp.to_f puts("\n\n") clients.each do |client_from| if(client_from.get_client_id == $client_from_id) clients.each do |client_to| if(client_to.get_client_id == $client_to_id) $client_from_old_amount = client_from.get_client_money_balance if( ($client_from_old_amount - $client_money_amount_transfer) >= 0) $client_from_new_amount = $client_from_old_amount - $client_money_amount_transfer client_from.set_client_money_balance($client_from_new_amount) $client_to_new_amount = $client_to_old_amount + $client_money_amount_transfer client_to.set_client_money_balance($client_to_new_amount) end $client_to_found = true end end $client_from_found = true end end if($client_from_found == true) if($client_to_found == true) if( ($client_from_old_amount - $client_money_amount_transfer) < 0) puts("\nClient FROM don't have the necessary Money Amount Balance to do this operation!!!") else puts("\nClient Transferred %0.2f EUR successfully!!!" % [$client_money_amount_transfer]) end else puts("\nClient TO with the given ID not found!!!") end else puts("\nClient FROM with the given ID not found!!!") end $choice = -1 end # Chosen Option #9 - Exit/Quit if($choice == 9) if(clients.length == 0) puts("No Clients registered in the system yet...") else puts("All the Clients registered in the system:\n\n") end $client_num = 1 clients.each do |client| puts("Client #%d: {\n" % [$client_num]) puts(" ID: %d\n" % [client.get_client_id]) puts(" First Name: %s\n" % [client.get_client_first_name]) puts(" Last Name: %s\n" % [client.get_client_last_name]) puts(" Money Amount Balance: %0.2f EUR\n" % [client.get_client_money_balance]) puts("}") $client_num = $client_num + 1 puts("\n\n") end $choice = -1 end if($choice == 12) exit end puts "\n\n\n" end
chrisjgilbert/thermostat-app
app.rb
<reponame>chrisjgilbert/thermostat-app<gh_stars>0 require 'sinatra/base' require 'json' class ThermostatApp < Sinatra::Base enable :sessions before do headers 'Access-Control-Allow-Methods' => '*' end get '/' do erb :index end get '/temperature' do temperature = session[:temperature] || 20.to_s content_type :json { temperature: temperature}.to_json end post '/temperature' do session[:temperature] = params[:temperature] redirect '/' end run! if app_file == $0 end
MiniDOM/MiniDOM
MiniDOM.podspec
Pod::Spec.new do |s| s.name = "MiniDOM" s.version = "1.0.3" s.summary = "A minimal XML DOM parser for Swift." s.homepage = "https://minidom.github.io/" s.license = { :type => "MIT", :file => "LICENSE" } s.author = "<NAME>" s.ios.deployment_target = "8.4" s.osx.deployment_target = "10.10" s.tvos.deployment_target = "9.0" s.watchos.deployment_target = "2.0" s.swift_version = "5.1" s.source = { :git => "https://github.com/MiniDOM/MiniDOM.git", :tag => "#{s.version}" } s.source_files = "Sources/MiniDOM/" s.exclude_files = ["Examples", "Tests"] s.documentation_url = "https://minidom.github.io/Documentation" end
sandfox-im/journald-logger
lib/journald/classes/trace_logger.rb
module Journald class TraceLogger def initialize(progname = nil, min_priority = nil, **tags) @wrapped_logger = ::Journald::Logger.new(progname, min_priority, **tags) end PASSTHROUGH_METHODS = [ :tag, :tag_value, :untag, :progname, :progname=, :level, :level=, :sev_threshold, :sev_threshold=, :min_priority, :min_priority=, ] METHODS = (Journald::Logger.public_instance_methods(false) + Journald::Logger::Exceptionable.public_instance_methods(false) + Journald::Logger::Loggable.public_instance_methods(false) + Journald::Logger::Sysloggable.public_instance_methods(false)) METHODS.each do |method| if PASSTHROUGH_METHODS.include? method define_method(method) do |*args, &block| @wrapped_logger.public_send(method, *args, &block) end else define_method(method) do |*args, &block| @wrapped_logger.__send__(:tag_trace_location, caller_locations(1..1).first) @wrapped_logger.public_send(method, *args, &block) end end end end end
sandfox-im/journald-logger
lib/journald/modules/version.rb
<filename>lib/journald/modules/version.rb module Journald class Logger VERSION = "3.1.0" end end
MrSayyod/Ruby-Capstone-Project-Scraper
lib/loop.rb
require_relative '../lib/scraper.rb' class Loop < Scraper attr_reader :total, :page def initialize(total, page) @total = total @page = page end def start iteration_url = "https://www.simplyhired.com/search?q=junior+web+developer&pn=#{page}" iteration_doc = ::OpenURI.open_uri(iteration_url) iteration_unparsed_page = iteration_doc.read iteration_parsed_page = Nokogiri::HTML(iteration_unparsed_page) iteration_parsed_page.css('div.SerpJob-jobCard') end def scraper @list = [] iteration_jobs_list = start iteration_jobs_list.each do |x| jobs = { position: x.css('div.jobposting-title-container').css('a.card-link').text, url: x.css('div.jobposting-title-container').css('a')[0].attributes['href'].value, location: x.css('h3.jobposting-subtitle').css('span.jobposting-location').text, company: x.css('h3.jobposting-subtitle').css('span.jobposting-company').text, salary: x.css('div.SerpJob-metaInfo').css('span.jobposting-salary').text.delete_prefix!('Estimated: ') } @list.push(jobs) end @page += 1 end end
uriji/uriji-emoji-picker
lib/helper/emoji_helper.rb
<filename>lib/helper/emoji_helper.rb<gh_stars>0 require_relative './emoji_regex' # UrijiEmojiPicker module UrijiEmojiPicker def emojify(text) find_emoji(text) end private def find_emoji(text) string = replace_unicode_moji_with_images(text) || text emoji = string.scan(regex) unicodes = [] index = UrijiEmojiPicker::EmojiMap.new emoji.each do |e| next if e.empty? tmp_emoji = e.join('') moji = index.find_by_moji(tmp_emoji) if moji flags = exceptions_emoji(tmp_emoji) if flags.empty? name = moji[0] if moji[0] char = moji[1]['char'] if moji[1]['char'] hash_emoji = { name: name, char: char } else hash_emoji = flags end else hash_emoji = exceptions_emoji(tmp_emoji) end unicodes << hash_emoji end unicodes.each do |hash| next if hash.nil? hash.reject! { |i| i.nil? } insert_image_to_image_tag(string, hash) if hash[:char] end string.respond_to?(:html_safe) ? string.html_safe : string end def replace_unicode_moji_with_images(string) index = UrijiEmojiPicker::EmojiMap.new string.gsub!(regex) do |moji| if moji.size < 2 && index.find_by_moji(moji) alt = index.find_by_moji(moji)[0] else tmp = exceptions_emoji(moji) alt = tmp[:name] if tmp.key?(:name) end %(<span class='emoji-image'><img alt='#{alt}' class="emoji" src="#{moji}"></span>) end end def insert_image_to_image_tag(string, img) stanadrt_replace(string, img) end def stanadrt_replace(string, img) string.gsub!(img[:char], "#{Emoji.asset_host}#{Emoji.asset_path}/#{img[:name]}.png") end def regex UrijiEmojiPicker::EmojiRegex.regex end def emoji_map UrijiEmojiPicker::EmojiMap end def exceptions_emoji(emoji) UrijiEmojiPicker::EmojiExceptions.call(emoji) end end
uriji/uriji-emoji-picker
lib/uriji_emoji_picker.rb
<filename>lib/uriji_emoji_picker.rb require 'uriji_emoji_picker/version' require 'uriji_emoji_picker/engine' if defined?(Rails) require 'emoji' require 'helper/emoji_map' require 'helper/emoji_exceptions' require 'helper/emoji_helper' # UrijiEmojiPicker module UrijiEmojiPicker; end
uriji/uriji-emoji-picker
lib/generators/uriji_emoji_picker/install_generator.rb
module UrijiEmojiPicker module Generators class InstallGenerator < Rails::Generators::Base source_root File.dirname(__FILE__) def copy_images directory 'emoji_img', 'app/assets/images/emoji_picker' directory 'emoji', 'app/assets/images/emoji' end def info puts " ===================================================== #{yellow '😼 😼 😼 Uriji Emoji Picker'} #{yellow UrijiEmojiPicker::VERSION} #{yellow '😼 😼 😼'} #{blue 'Repository'}: 'https://github.com/ID25/uriji_emoji_picker' #{blue 'Author'}: <NAME> (ID25) 1. Add this data-attribute to your input/text field #{green 'data: { emojiable: true }'} 2. Wrap your input with #{yellow '.emoji-picker-container'} css-class #{green 'p.emoji-picker-container'} 3. To show text with emoji, use helper emojify Exaple: #{green 'p.emoji-picker-container'} #{green '= f.text_field :title, class: "form-control", data: { emojiable: true }'} #{green '= emojify(@post.title)'} ===================================================== " end private def colorize(text, color_code) "\e[#{color_code}m#{text}\e[0m" end def green(text) colorize(text, 32) end def yellow(text) colorize(text, 33) end def blue(text) colorize(text, 36) end end end end
uriji/uriji-emoji-picker
lib/uriji_emoji_picker/engine.rb
<reponame>uriji/uriji-emoji-picker<filename>lib/uriji_emoji_picker/engine.rb<gh_stars>0 module UrijiEmojiPicker class Engine < Rails::Engine config.autoload_paths += Dir["#{config.root}/lib/**/"] initializer 'initialize uriji_emoji_picker helper' do |_app| ActiveSupport.on_load(:action_view) do include UrijiEmojiPicker end end end end
bolasblack/programr
lib/programr/facade.rb
<reponame>bolasblack/programr<gh_stars>1-10 module ProgramR class Facade attr_reader :environment, :history # Create a new robot # # @param custom_environment the custom {Environment} class # @param custom_history the custom {History} class def initialize custom_environment = Environment, custom_history = History @history = custom_history.new @environment = custom_environment.new @history @graphmaster = Graphmaster.new @parser = AimlParser.new @graphmaster, @environment, @history end # Learn knowledges # # @param content [String, Array<String>] folder array of aiml files or plain aiml content def learn content if content.is_a? Array read_aiml(content) { |f| @parser.parse f } else @parser.parse content end end # Talk with robot # # @!method get_reaction(stimula) # @param stimula [String] the message speak to robot # @return [String] the message robot said def get_reaction(stimula, firstStimula = true) starGreedy = [] #TODO verify if case insensitive. Cross check with parser @history.update_stimula(stimula.upcase) if firstStimula reaction = @graphmaster.get_reaction stimula.upcase, @history.that, @history.topic, starGreedy @history.update_star_matches starGreedy res = evaluate(reaction, starGreedy).flatten.reduce([]) do |memo, part| # clean case [" ", "part 1 ", " ", "part 2", " "] if !memo.last || !memo.last.end_with?(' ') memo << part elsif part && memo.last.end_with?(' ') && !part.strip.empty? memo << part end memo end.join('').strip #TODO verify if case insensitive. Cross check with main program & parser @history.update_response(res.upcase) if firstStimula res end # Register segmenter for specified language # # @param lang [Symbol] the language tag segmenter for # @param block [Block] the segmenter # @note # Graphmaster decide which segmenters process aiml partten by read # `language` attribute of `Category` tag. # # But it will not detect which language of user stimula, Graphmaster # will pass stimula to all segmenter, block should decide what to do # by it self. def register_segmenter lang, &block @graphmaster.register_segmenter lang, &block end # Reset Graphmaster def reset @graphmaster.reset end def to_s @graphmaster.to_s end private def evaluate reaction, starGreedy thinkIsActive = false reaction.map do |token| if token.is_a? Srai # TODO: execute srai in a sandbox token = get_reaction token.pattern, false # restore context before Srai, otherwise next part will # run in the error history @history.update_star_matches starGreedy end if token.is_a? Think thinkIsActive = !thinkIsActive next end responses = token.is_a?(String) ? token : token.execute if thinkIsActive '' elsif responses.is_a? Array evaluate responses, starGreedy else responses end end end def read_aiml files_and_dirs, &block files_and_dirs.map do |file| if File.file?(file) && File.fnmatch?('*.aiml', file) File.open(file, 'r') { |content| block.call content } else read_aiml Dir["#{file}/*"], &block end end end end end
bolasblack/programr
lib/programr/environment.rb
<gh_stars>1-10 module ProgramR class Environment # @group Custom Environment required methods # @param history the {History} instance which passed in {Facade#initialize} def initialize history @readonly_tags_file = "#{File.dirname(__FILE__)}/../../conf/readOnlyTags.yaml" @readonly_tags = YAML::load(File.open(@readonly_tags_file)) @history = history end def get key return @history.send(key) if key =~ /that$/ return questions.sample if key == 'question' return @readonly_tags[key] if @readonly_tags.key?(key) nil end def set key, value @history.topic = value if key == 'topic' @readonly_tags[key] = value end # @endgroup def readonly_tags_file @readonly_tags_file end def readonly_tags_file= file unless File.exist? file raise "File #{file} not exist" end @readonly_tags_file = file @readonly_tags = YAML::load(File.open(file)) end private def questions @readonly_tags['question'] end end end
bolasblack/programr
spec/utils/fake_graphmaster.rb
class FakeGraphmaster attr_reader :learned def initialize @learned = [] end def learn category @learned << category end end
bolasblack/programr
lib/programr/history.rb
module ProgramR class History attr_accessor :topic def initialize @topic = 'undef' @inputs = [] @responses = [] @star_greedy = [] @that_greedy = [] @topic_greedy = [] end # @param index [Numeric] get stimula, 0 is the nearest one # @return [String, nil] def get_stimula index @inputs[index] end # @param stimula [String] def update_stimula stimula @inputs.unshift stimula end # @param index [Numeric] get response, 0 is the nearest one # @return [String, nil] def get_response index @responses[index] end # @param response [String] def update_response response @responses.unshift response end # @return [String] return last response or 'undef' def that return 'undef' unless @responses[0] @responses[0] end # @return [String] return last second response or 'undef' def justbeforethat return 'undef' unless @responses[1] @responses[1] end # @return [String] return last input or 'undef' def justthat return 'undef' unless @inputs[0] @inputs[0] end # @return [String] return last second input or 'undef' def beforethat return 'undef' unless @inputs[1] @inputs[1] end # @param index [Numeric] get star, 0 is the nearest one # @return [String] def get_star index return 'undef' unless @star_greedy[index] @star_greedy[index].join(' ') end # @param index [Numeric] get thatstar, 0 is the nearest one # @return [String] def get_thatstar index return 'undef' unless @that_greedy[index] @that_greedy[index].join(' ') end # @param index [Numeric] get topicstar, 0 is the nearest one # @return [String] def get_topicstar index return 'undef' unless @topic_greedy[index] @topic_greedy[index].join(' ') end # @param star_greedy_array [Array<String>] def update_star_matches star_greedy_array @star_greedy = [] @that_greedy = [] @topic_greedy = [] current_greedy = @star_greedy star_greedy_array.each do |greedy| if greedy == GraphMark::THAT current_greedy = @that_greedy elsif greedy == GraphMark::TOPIC current_greedy = @topic_greedy elsif greedy == '<star>' current_greedy.push([]) else current_greedy.last.push(greedy) end end end end end
bolasblack/programr
lib/programr/graphmaster.rb
module ProgramR class Graphmaster attr_reader :graph def initialize @segmenter_map = {} reset end def learn category segmenter = @segmenter_map[category.language] if category.language.nil? or segmenter.nil? path = category.patterns else path = segmenter.call category.patterns end path += [GraphMark::THAT] + category.thats unless category.thats.empty? path += [GraphMark::TOPIC] + category.topics unless category.topics.empty? @graph.learn(category, path) end def get_reaction stimula, last_said, cur_topic, starGreedy if @segmenter_map.empty? segmented_reaction = [stimula] else segmented_reaction = @segmenter_map.reduce [stimula] do |last_state, kvmap| kvmap.last.call last_state end end path = "#{segmented_reaction.join ' '} #{GraphMark::THAT} #{last_said} #{GraphMark::TOPIC} #{cur_topic}".split(/\s+/) template = @graph.get_template(path, starGreedy) template ? template.value : [] end def reset @graph = GraphNode.new end def to_s @graph.inspect_node end def register_segmenter lang, &block if block_given? @segmenter_map[lang] = block end end end end
bolasblack/programr
spec/utils/fake_environment.rb
<filename>spec/utils/fake_environment.rb class FakeEnvironment def initialize history = nil @stage = {} @history = history end def get key @stage[key] end def set key, value @stage[key] = value end end
bolasblack/programr
lib/programr/aiml_parser.rb
<filename>lib/programr/aiml_parser.rb # Listen block arguments document: # http://ruby-doc.org/stdlib-2.0.0/libdoc/rexml/rdoc/REXML/SAX2Listener.html # gli accenti nel file di input vengono trasformati in &apos; !!! # module ProgramR class AimlParser def initialize learner, environment, history @learner = learner @history = history @environment = environment end def parse aiml category = nil openLabels = [] patternIsOpen = false thatIsOpen = false currentLanguage = nil currentCondition = nil currentConditionItem = nil currentSrai = nil currentGender = nil currentPerson = nil currentPerson2 = nil currentTopic = nil @parser = REXML::Parsers::SAX2Parser.new(aiml) @parser.listen(%w{ category }) do |uri, localname, qname, attributes| category = Category.new language: currentLanguage category.topic = currentTopic if currentTopic end @parser.listen(:end_element, %w{ category }) { @learner.learn(category) } @parser.listen(%w{ topicstar thatstar star }) do |uri, localname, qname, attributes| openLabels[-1].add(Star.new(localname, attributes, @history)) end ### meta @parser.listen(:start_element, %w{ aiml }) do |uri, localname, qname, attributes| if localname == 'meta' and attributes["name"] == 'language' currentLanguage = attributes["content"].to_sym end end @parser.listen(:end_element, %w{ aiml }) do currentLanguage = nil end ### condition @parser.listen(%w{ condition }) do |uri, localname, qname, attributes| if attributes.has_key?('value') currentCondition = Condition.new attributes, @environment else currentCondition = ListCondition.new attributes end openLabels[-1].add(currentCondition) openLabels.push(currentCondition) end @parser.listen(%w{ random }) do |uri, localname, qname, attributes| currentCondition = Random.new openLabels[-1].add(currentCondition) openLabels.push(currentCondition) end @parser.listen(:characters, %w{ condition }) do |text| next if text =~ /^\s+$/ currentCondition.add(text) end @parser.listen(:end_element, %w{ condition random }) do currentCondition = nil openLabels.pop end @parser.listen(%w{ li }) do |uri, localname, qname, attributes| next unless currentCondition currentConditionItem = ConditionItem.new attributes, currentCondition, @environment currentCondition.setListElement(currentConditionItem) openLabels.push currentConditionItem end @parser.listen(:characters, %w{ li }) do |text| next unless currentConditionItem next if text =~ /^\s+$/ currentConditionItem.add text end @parser.listen(:end_element, %w{ li }) do next unless currentConditionItem currentConditionItem = nil openLabels.pop end ### end condition ### get @parser.listen([/^get.*/, /^bot_*/, 'for_fun', /that$/, 'question']) do |uri, localname, qname, attributes| unless openLabels.empty? openLabels[-1].add(GetTag.new localname, attributes, @environment) end end @parser.listen(%w{ bot name }) do |uri, localname, qname, attributes| if localname == 'bot' localname = 'bot_' + attributes['name'] else localname = 'bot_name' end if patternIsOpen category.add_pattern(GetTag.new(localname, {}, @environment)) elsif thatIsOpen category.add_that(GetTag.new(localname, {}, @environment)) else openLabels[-1].add(GetTag.new(localname, {}, @environment)) end end ### end get ### set @parser.listen([/^set_*/, 'set']) do |uri, localname, qname, attributes| setObj = SetTag.new localname, attributes, @environment openLabels[-1].add(setObj) openLabels.push(setObj) end @parser.listen(:characters, [/^set_*/]) do |text| openLabels[-1].add(text) end @parser.listen(:end_element, [/^set_*/, 'set']) do openLabels.pop end ### end set ### pattern @parser.listen(%w{ pattern }){ patternIsOpen = true } @parser.listen(:characters, %w{ pattern }) do |text| #TODO verify if case insensitive. Cross check with facade category.add_pattern(text.upcase) end @parser.listen(:end_element, %w{ pattern }){ patternIsOpen = false } #end pattern ### that @parser.listen(%w{ that }){ thatIsOpen = true } @parser.listen(:characters, %w{ that }){ |text| category.add_that(text) } @parser.listen(:end_element, %w{ that }){ thatIsOpen = false } ### end that ### template @parser.listen(%w{ template }) do category.template = Template.new openLabels.push(category.template) end @parser.listen(:characters, %w{ template }) do |text| category.template.append(text) end @parser.listen(:end_element, %w{ template }) do openLabels.pop end ### end template @parser.listen(%w{ input }) do |uri, localname, qname, attributes| category.template.add(Input.new(attributes, @history)) end ### think @parser.listen(:start_element, %w{ think }) do openLabels[-1].add(Think.new('start')) end @parser.listen(:end_element, %w{ think }) do openLabels[-1].add(Think.new('end')) end ###end think @parser.listen(:characters, %w{ uppercase }) do |text| openLabels[-1].add(text.upcase.gsub(/\s+/, ' ')) end @parser.listen(:characters, %w{ lowercase }) do |text| openLabels[-1].add(text.downcase.gsub(/\s+/, ' ')) end @parser.listen(:characters, %w{ formal }) do |text| text.gsub!(/(\w+)/){ $1.capitalize } openLabels[-1].add(text.gsub(/\s+/, ' ')) end @parser.listen(:characters, %w{ sentence }) do |text| openLabels[-1].add(text.capitalize.gsub(/\s+/, ' ')) end @parser.listen(%w{ date }) do openLabels[-1].add(Sys_Date.new) end @parser.listen(:characters, %w{ system }) do |text| openLabels[-1].add(Command.new(text)) end @parser.listen(%w{ size }) do openLabels[-1].add(Size.new) end ### srai @parser.listen(%w{ sr }) do |uri, localname, qname, attributes| openLabels[-1].add(Srai.new(Star.new('star', {}, @history))) end @parser.listen(%w{ srai }) do |uri, localname, qname, attributes| currentSrai = Srai.new openLabels[-1].add(currentSrai) openLabels.push(currentSrai) end @parser.listen(:characters, %w{ srai }) do |text| currentSrai.add(text) end @parser.listen(:end_element, %w{ srai }) do currentSrai = nil openLabels.pop end ### end srai ### gender @parser.listen(%w{ gender }) do |uri, localname, qname, attributes| currentGender = Gender.new openLabels[-1].add(currentGender) openLabels.push(currentGender) end @parser.listen(:characters, %w{ gender }) do |text| currentGender.add(text) end @parser.listen(:end_element, %w{ gender }) do currentGender = nil openLabels.pop end ### end gender ### person @parser.listen(%w{ person }) do |uri, localname, qname, attributes| currentPerson = Person.new @environment openLabels[-1].add(currentPerson) openLabels.push(currentPerson) end @parser.listen(:characters, %w{ person }) do |text| currentPerson.add(text) end @parser.listen(:end_element, %w{ person }) do currentPerson = nil openLabels.pop end ### end person ### person2 @parser.listen(%w{ person2 }) do |uri, localname, qname, attributes| currentPerson2 = Person2.new openLabels[-1].add(currentPerson2) openLabels.push(currentPerson2) end @parser.listen(:characters, %w{ person2 }) do |text| currentPerson2.add(text) end @parser.listen(:end_element, %w{ person2 }) do currentPerson2 = nil openLabels.pop end ### end perso2 ### topic @parser.listen(%w{ topic }) do |uri, localname, qname, attributes| currentTopic = attributes['name'] end @parser.listen(:end_element, %w{ topic }) do currentTopic = nil end ### end topic @parser.parse end end #Aiml@parser end
bolasblack/programr
spec/facade_spec.rb
# coding: utf-8 require 'securerandom' require File.join(File.dirname(__FILE__), './utils/fake_environment') describe ProgramR::Facade do let(:robot) do robot = ProgramR::Facade.new robot.environment.readonly_tags_file = 'spec/data/readOnlyTags.yaml' robot end after { robot.reset } it 'can custon environment' do robot = ProgramR::Facade.new FakeEnvironment robot.learn <<-AIML <category> <pattern>set test</pattern> <template> <think><set_hello>world</set_hello></think> </template> </category> AIML robot.get_reaction 'set test' expect(robot.environment.get 'hello').to eq 'world' end describe '#learn' do it "can read plain aiml" do pattern = SecureRandom.hex result = SecureRandom.hex robot.learn <<-AIML <category> <pattern>#{pattern}</pattern> <template>#{result}</template> </category> AIML expect(robot.get_reaction pattern).to eq result end it "can read aiml folder" do robot.learn ['spec/data/for_learn_test'] expect(robot.get_reaction 'single file').to eq 'OK' expect(robot.get_reaction 'in dir').to eq 'OK' expect(robot.get_reaction 'in sub dir').to eq 'OK' expect(robot.get_reaction 'badfile').to eq '' end end describe '#get_reaction' do before { robot.learn ['spec/data/facade.aiml'] } shared_examples 'alice' do |opt = {}| if opt[:in_test] message = "support #{opt[:in_test]}" else message = "can handle message #{opt[:with_stimula]}" end def bind_proc proc, instance instance.define_singleton_method :_, &proc fn = instance.method(:_).unbind instance.instance_eval { undef :_ } fn.bind instance end it message do bind_proc(opt[:prepare], self).call unless opt[:prepare].nil? robot.learn aiml if self.respond_to? :aiml response = opt[:response].is_a?(Proc) ? opt[:response].call : opt[:response] expect(robot.get_reaction(opt[:with_stimula])).to eq response bind_proc(opt[:asserts], self).call response unless opt[:asserts].nil? end end describe 'with paratactic condition' do before { robot.learn ['spec/data/condition.aiml'] } it_behaves_like 'alice', response: 'You sound very handsome.', with_stimula: 'I AM BROWN', in_test: 'normal case' it_behaves_like 'alice', response: 'You sound very handsome.', with_stimula: 'I AM CYAN', in_test: 'item value include start' it_behaves_like 'alice', response: 'You sound very attractive.', with_stimula: 'I AM GREEN', in_test: 'not exist attribute' it_behaves_like 'alice', response: 'You sound very attractive.', with_stimula: 'I AM PINK', in_test: 'null value' end describe 'with condition list' do before { robot.learn ['spec/data/condition.aiml'] } it_behaves_like 'alice', response: 'You sound very handsome.', with_stimula: 'I AM RED', in_test: 'normal case' it_behaves_like 'alice', response: 'You sound very handsome.', with_stimula: 'I AM BLOND', in_test: 'item value include star' it_behaves_like 'alice', response: 'You sound very handsome.', with_stimula: 'I AM BLACK', in_test: 'switch style' it_behaves_like 'alice', response: 'You sound very handsome.', with_stimula: 'I AM WHITE', in_test: 'not exist attribute' it_behaves_like 'alice', response: 'You sound very attractive.', with_stimula: 'I AM BLUE', in_test: 'null value' it_behaves_like 'alice', response: 'You sound very nice.', with_stimula: 'I AM GRAY', in_test: 'default item' end describe 'with srai tag' do before { robot.learn ['spec/data/srai.aiml'] } it_behaves_like 'alice', response: 'world', with_stimula: 'test1', in_test: 'normal case' it_behaves_like 'alice', response: 'world', with_stimula: 'test2', in_test: 'included by other tag' end describe 'with set tag' do before { robot.learn ['spec/data/set.aiml'] } it_behaves_like 'alice', response: 'male.female.female', with_stimula:'test set', in_test: 'normal case' it_behaves_like 'alice', response: "Got it, INPUT", with_stimula: 'input', in_test: 'set star matched content' end it_behaves_like 'alice', response: 'are you never tired to do the same things every day?', with_stimula:'question test' do srand(2) end it_behaves_like 'alice', response: 'test succeeded', with_stimula: 'srai test', asserts: -> (response) do expect(robot.history.topic).to eq 'WORK' end it_behaves_like 'alice', response: 'new test succeeded', with_stimula: 'atomic test', in_test: 'TOPIC', prepare: -> { robot.history.topic = 'WORK' } it_behaves_like 'alice', response: 'that test 1', with_stimula: 'that test', in_test: 'THAT 1', prepare: -> { robot.history.update_response 'NEW TEST SUCCEEDED' } it_behaves_like 'alice', response: 'that test 2', with_stimula:'that test', in_test: "THAT 2", prepare: -> { robot.history.update_response 'THAT TEST 1' } it_behaves_like 'alice', response: 'topic star test succeeded OK', with_stimula:'atomic test', in_test: "STAR TOPIC", prepare: -> { robot.history.topic = 'OK GAME' } it_behaves_like 'alice', response: 'the UPPERCASE test', with_stimula:'uppercase test' it_behaves_like 'alice', response: 'the lowercase test', with_stimula:'LOWERCASE TEST' it_behaves_like 'alice', response: -> { Date.today.to_s }, with_stimula:'DATE TEST' it_behaves_like 'alice', response: -> { 'time:' + `date`.chomp }, with_stimula:'SYSTEM TEST' it_behaves_like 'alice', response: -> { ProgramR::Category.cardinality.to_s }, with_stimula:'SIZE TEST' it_behaves_like 'alice', response: "TEST SPACE", with_stimula:"SPACE TEST" it_behaves_like 'alice', response: 'test bot name', with_stimula:'get test 1' it_behaves_like 'alice', response: 'TEST SPACE', with_stimula:'justbeforethat tag test', prepare: -> do robot.history.update_response 'TEST SPACE' robot.history.update_response 'padding' end it_behaves_like 'alice', response: 'TEST SPACE', with_stimula:'that tag test', prepare: -> do robot.history.update_response 'TEST SPACE' end it_behaves_like 'alice', response: 'localhost', with_stimula:'get test 2' it_behaves_like 'alice', response: 'ok.', with_stimula:'think test. i am male' it_behaves_like 'alice', response: 'The sentence test', with_stimula:'sentence test' it_behaves_like 'alice', response: 'The Formal Test', with_stimula:'formal test' it_behaves_like 'alice', response: 'A', with_stimula:'random test' it_behaves_like 'alice', response: 'RANDOM TEST.FORMAL TEST', with_stimula:'test input', prepare: -> do robot.history.update_stimula 'FORMAL TEST' robot.history.update_stimula 'RANDOM TEST' end it_behaves_like 'alice', response: 'she told to him to take a hike but her ego was too much for him', with_stimula:'test gender' it_behaves_like 'alice', response: 'she TOLD to him', with_stimula:'test gender wrap star he told to her' it_behaves_like 'alice', response: 'he TOLD MAURO EVERYTHING OK WITH his PROBLEM BUT i ANSWERS NO', with_stimula:'test person wrap star i told mauro everything ok with my problem but he answers no' it_behaves_like 'alice', response: 'i say everything ok to you', with_stimula:'you say everything ok to me' it_behaves_like 'alice', response: 'star wins', with_stimula:'This is her' it_behaves_like 'alice', response: 'underscore wins', with_stimula:'This is you' it_behaves_like 'alice', response: 'explicit pattern wins', with_stimula:'This is clearly you' it_behaves_like 'alice', response: 'first star is ARE NEAT AND second star is GOOD AS', with_stimula:'These are neat and clearly good as them' describe 'thatstar tag' do it_behaves_like 'alice', response: 'ALSO MINE IS AC MILAN', with_stimula:'AC milan', prepare: -> do robot.history.update_response 'WHAT IS YOUR FAVORITE FOOTBALL TEAM' end it_behaves_like 'alice', response: 'ok yes ALSO MINE IS AC MILAN', with_stimula: 'yes AC milan', prepare: -> do robot.history.update_response 'WHAT IS YOUR FAVORITE FOOTBALL TEAM' end end end end
bolasblack/programr
spec/environment_spec.rb
describe ProgramR::Environment do before do @env = ProgramR::Environment.new ProgramR::History.new end it "can set readonly tags file" do @env.readonly_tags_file = 'spec/data/readOnlyTags.yaml' expect(@env.get 'bot_name').to eq 'test bot name' end end
bolasblack/programr
programr.gemspec
# -*- encoding: utf-8 -*- require File.expand_path('../lib/programr/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["<NAME>, <NAME>, <NAME>, <NAME>, c4605"] gem.email = ["<EMAIL>"] gem.description = %q{Ruby interpreter for the AIML} gem.summary = %q{ProgramR is a Ruby implementation of an interpreter for the Artificial Intelligence Markup Language (AIML) based on the work of Dr. Wallace and defined by the Alicebot and AIML Architecture Committee of the A.L.I.C.E. AI Foundation (http://alicebot.org} gem.homepage = "https://github.com/bolasblack/programr" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "programr" gem.require_paths = ["lib"] gem.version = Programr::VERSION gem.add_development_dependency 'rspec', '~> 3.2.0' gem.add_development_dependency 'pry', '~> 0.10.1' gem.add_development_dependency 'yard', '~> 0.8.7.6' gem.add_dependency 'activesupport', '~> 4.1.8' end
bolasblack/programr
lib/programr/graph_node.rb
# coding: utf-8 module ProgramR class GraphNode attr_reader :children, :template MATCHERS = %w{_ *} def initialize @template = nil @children = {} end # @param category [Category] # @param path [Array<String>] def learn category, path branch = path.first # Only the tail node has @template return @template = category.template if branch.nil? (@children[branch] ||= GraphNode.new).learn(category, array_tail(path)) end def get_template_with_matcher input_path, matched, matcher current_branch = input_path.first if input_path.empty? @template elsif matcher_ending? input_path, matched new_matched = [] if template = get_template_without_matcher(input_path, new_matched) matched.concat new_matched template end else matched << current_branch get_template_with_matcher array_tail(input_path), matched, matcher end end def get_template_without_matcher input_path, matched, current_section = nil current_branch = input_path.first if current_branch == GraphMark::THAT current_section = GraphMark::THAT elsif current_branch == GraphMark::TOPIC current_section = GraphMark::TOPIC end if input_path.empty? or rest_section_not_exists_in_tree?(input_path) template = @template elsif @children.has_key? current_branch template = @children[current_branch].get_template_without_matcher(array_tail(input_path), matched, current_section) elsif current_branch == GraphMark::THAT skip_result = skip_that_section current_branch, input_path template = get_template_without_matcher skip_result[:input_path], matched end # if any node have @template, it must be an ending of a branch even # though it have @children return template if template MATCHERS.each do |matcher| new_matched = [current_branch] next unless @children.has_key? matcher next unless template = @children[matcher].get_template_with_matcher(array_tail(input_path), new_matched, matcher) matched.concat (current_section ? [current_section, '<star>'] : ['<star>']) + new_matched return template end nil end # Get template for input by the matching algorithm # # Open https://docs.google.com/document/d/1wNT25hJRyupcG51aO89UcQEiG-HkXRXusukADpFnDs4/pub # and search `7. AIML Pattern Matching` to get information about the matching algorithm # # This function will only return `nil` or `@template` if path ending, # # @param input [Array<String>] # @param matched [Array<String>] def get_template input, matched get_template_without_matcher clean_undef_section(input), matched end # @!method inspect_node def inspect_node branch = nil, indent_level = 0 line_head = [0, 1].include?(indent_level) ? '' : '┃ ' * (indent_level - 2) + '┣ ' line_content = (branch ? branch.to_s : '') + (@template ? ": [#{@template.inspect}]" : '') line_tail = indent_level == 0 ? '' : "\n" str = line_head + line_content + line_tail @children.each_key do |child_branch| str += @children[child_branch].inspect_node(child_branch, indent_level + 1) end str end private def array_tail array array.slice(1, array.length - 1) end def clean_undef_section input_path splited = input_path.reduce({input: [], that: [], topic: [], current_section: nil}) do |memo, part| if GraphMark::ALL.include? part memo[:current_section] = part next memo end if not memo[:current_section] memo[:input].push part elsif memo[:current_section] == GraphMark::THAT and part != 'undef' memo[:that].push part elsif memo[:current_section] == GraphMark::TOPIC and part != 'undef' memo[:topic].push part end memo end result = splited[:input] result.concat [GraphMark::THAT] + splited[:that] if not splited[:that].empty? result.concat [GraphMark::TOPIC] + splited[:topic] if not splited[:topic].empty? result end # The AIML pattern matching is non-greedy def matcher_ending? path, matched return false if matched.count < 1 next_word = path.is_a?(Array) ? path.first : path @children.has_key?(next_word) || GraphMark::ALL.include?(next_word) || MATCHERS.any? { |matcher| @children.has_key? matcher } end def rest_section_not_exists_in_tree? input_path clone_input_path = input_path.clone branch = clone_input_path.shift if not @children.has_key?(branch) and branch == GraphMark::THAT # the `topic` section is the last section branch = clone_input_path.shift until (branch.nil? or branch == GraphMark::TOPIC) end if not @children.has_key?(branch) and branch == GraphMark::TOPIC branch = clone_input_path.shift until branch.nil? end branch.nil? and clone_input_path.empty? end def skip_that_section branch, input_path clone_input_path = input_path.clone if branch == GraphMark::THAT # the `topic` section is the last section branch = clone_input_path.shift until (branch.nil? or clone_input_path.first == GraphMark::TOPIC) end {branch: branch, input_path: clone_input_path} end def current_section_finished? current_input_path current_input_path.empty? or GraphMark::ALL.include? current_input_path[1] end end end
bolasblack/programr
lib/programr/aiml_elements.rb
module ProgramR class AimlTag def inspect inspect_str = respond_to?(:to_inspect, true) ? to_inspect : execute "<#{self.class.name.demodulize.tableize.singularize} -> #{inspect_str}>" end def to_s respond_to?(:execute) ? execute : super end private def to_response inputs = nil, need_puts = false return [''] if inputs.nil? inputs = [inputs].to_a unless inputs.is_a? Array result = inputs.map { |input| input.is_a?(Srai) ? input : input.to_s } puts result if need_puts result end end class Category < AimlTag attr_accessor :template, :that, :topic, :language @@cardinality = 0 def self.cardinality @@cardinality end def initialize **opt @@cardinality += 1 @pattern = [] @that = [] @language = opt[:language] end def add_pattern anObj @pattern.push anObj end def add_that anObj @that.push anObj end def patterns @pattern.map(&:to_s).join('').split(/\s+/) end def thats @that.map(&:to_s).join('').split(/\s+/) end def topics return [] if @topic.nil? @topic.split(/\s+/) end end class Template < AimlTag attr_accessor :value def initialize @value = [] end def add anObj @value << anObj end def append aString @value << aString.gsub(/\s+/, ' ') end def inspect @value.map(&:inspect) end end class Random < AimlTag def initialize @condition_items = [] end def setListElement condition_item @condition_items << condition_item end def add aBody @condition_items[-1].add(aBody) end def execute @condition_items.sample.execute end end class Condition < AimlTag def initialize someAttributes, environment @environment = environment @conditions = {} pick_condition someAttributes do |name, value| @property = name @currentCondition = value end end def add aBody unless @conditions[@currentCondition] @conditions[@currentCondition] = [] end @conditions[@currentCondition].push(aBody) end def setListElement someAttributes pick_condition someAttributes do |name, value| @property = name @currentCondition = value end end def execute condition_valid? ? text : '' end def condition_valid? if @property.nil? false elsif @environment.get(@property).nil? @currentCondition.nil? elsif @environment.get(@property) =~ /^#{@currentCondition}$/ true else false end end private def to_inspect "if #{@property} == #{@currentCondition} then #{text}" end def pick_condition attributes name = string_not_empty(attributes['name']) ? attributes['name'] : @property value = string_not_empty(attributes['value']) ? attributes['value'] : nil yield name, parse_value(value) end def string_not_empty string !(string.nil? or string.empty?) end def parse_value value value && value.sub('*', '.*') end def text texts = @conditions[@currentCondition] to_response (texts.nil? || texts.empty?) ? [''] : texts end end class ListCondition < Condition attr_reader :property def initialize someAttributes @condition_items = [] @property = someAttributes['name'] if someAttributes.has_key? 'name' end def add text @condition_items[-1].add text end def setListElement condition_item @condition_items << condition_item end def execute @condition_items.each do |item| return item.execute if item.condition_valid? end default_item_result || to_response end private def to_inspect @condition_items.map(&:to_inspect).join ' || ' end def default_item_result get_default_item = -> do @condition_items.each { |item| return item if item.default_item? } end item = get_default_item.call item.is_a?(Array) ? nil : item.execute end end class ConditionItem < Condition def initialize someAttributes, conditionContainer, environment @conditionContainer = conditionContainer @conditions = {} @environment = environment if @conditionContainer.is_a? ListCondition pick_condition someAttributes do |name, value| @property = name || @conditionContainer.property @currentCondition = value end end end def default_item? @property.nil? && @currentCondition.nil? end def execute if @conditionContainer.is_a?(Random) or default_item? text else super end end def to_inspect if default_item? text else "if #{@property} == #{@currentCondition} then #{text}" end end end class SetTag < AimlTag def initialize aLocalname, attributes, environment @environment = environment @value = [] if attributes['name'].nil? @localname = aLocalname.sub(/^set_/, '') else @localname = attributes['name'] end end def add aBody @value.push(aBody) end def value @value.map(&:to_s).join('').strip end def execute @environment.set(@localname, value) to_response value end private def to_inspect "#{@localname}: #{value}" end end class Input < AimlTag def initialize someAttributes, history @history = history @index = 1 @index = someAttributes['index'].to_i if someAttributes.has_key?('index') end def execute to_response to_inspect end private def to_inspect @history.get_stimula @index end end class Star < AimlTag def initialize aStarName, someAttributes, history @history = history @star = aStarName @index = 0 @index = someAttributes['index'].to_i - 1 unless someAttributes.empty? end def execute to_response get_star end private def get_star @history.send("get_#{@star}", @index) end def to_inspect "#{@star} #{@index} (#{get_star})" end end class GetTag < AimlTag def initialize aLocalname, someAttributes, environment @environment = environment @localname = aLocalname.sub(/^get_/, '') if someAttributes.has_key?('index') && @localname == 'that' @localname = 'justbeforethat' if someAttributes['index'] == '2,1' someAttributes = {} end @attributed = someAttributes end def execute to_response @environment.get(@attributed['name'] || @localname) end private def to_inspect "#{@localname}: #{execute}" end end class Think < AimlTag attr_reader :status def initialize aStatus @status = aStatus end def execute to_response @status end end class Size < AimlTag def execute to_response Category.cardinality.to_s end end class Sys_Date < AimlTag def execute to_response Date.today.to_s end end class Srai < AimlTag def initialize anObj = nil @pattern = [] add(anObj) if anObj end def add anObj @pattern.push anObj end def pattern @pattern.map(&:to_s).join('').strip end alias_method :to_inspect, :pattern end class Command < AimlTag def initialize text @command = text end def execute to_response `#{@command}` end end class ReplaceTag < AimlTag Map = {} def initialize @sentence = [] end def add anObj @sentence.push anObj end def execute res = @sentence.map(&:to_s).join('').strip self.class::Map.each_pair do |matcher, fn| res = res.gsub(matcher) { |match| replace fn, $~ } end res end private def replace fn, matches fn.call matches end end class Person < ReplaceTag @@swap = {'male' => {'me' => 'him', 'my' => 'his', 'myself' => 'himself', 'mine' => 'his', 'i' => 'he', 'he' => 'i', 'she' => 'i'}, 'female' => {'me' => 'her', 'my' => 'her', 'myself' => 'herself', 'mine' => 'hers', 'i' => 'she', 'he' => 'i', 'she' => 'i'}} Map = { /\b(she|he|i|me|my|myself|mine)\b/i => -> (match, environment) do gender = environment.get('gender') @@swap[gender][match[1].downcase] end } def initialize environment @environment = environment super() end private def replace fn, matches fn.call matches, @environment end end class Person2 < ReplaceTag @@swap = {'me' => 'you', 'you' => 'me'} Map = { /\b((with|to|of|for|give|gave|giving) (you|me)|you|i)\b/i => -> (match) do if match[3] match[2].downcase + ' ' + @@swap[match[3].downcase] elsif match[1].downcase == 'you' 'i' elsif match[1].downcase == 'i' 'you' end end } end class Gender < ReplaceTag Map = { /\b(she|he|him|his|(for|with|on|in|to) her|her)\b/i => -> (match) do case match[1].downcase when 'she' then 'he' when 'he' then 'she' when 'him', 'his' then 'her' when 'her' then 'his' else "#{match[2].downcase} him" end end } end end #ProgramR